3 * Implements the User class for the %MediaWiki software.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use MediaWiki\MediaWikiServices
;
24 use MediaWiki\Session\SessionManager
;
25 use MediaWiki\Session\Token
;
26 use MediaWiki\Auth\AuthManager
;
27 use MediaWiki\Auth\AuthenticationResponse
;
28 use MediaWiki\Auth\AuthenticationRequest
;
29 use MediaWiki\User\UserIdentity
;
31 use Wikimedia\ScopedCallback
;
32 use Wikimedia\Rdbms\Database
;
33 use Wikimedia\Rdbms\DBExpectedError
;
34 use Wikimedia\Rdbms\IDatabase
;
37 * The User object encapsulates all of the user-specific settings (user_id,
38 * name, rights, email address, options, last login time). Client
39 * classes use the getXXX() functions to access these fields. These functions
40 * do all the work of determining whether the user is logged in,
41 * whether the requested option can be satisfied from cookies or
42 * whether a database query is needed. Most of the settings needed
43 * for rendering normal pages are set in the cookie to minimize use
46 class User
implements IDBAccessObject
, UserIdentity
{
48 * @const int Number of characters in user_token field.
50 const TOKEN_LENGTH
= 32;
53 * @const string An invalid value for user_token
55 const INVALID_TOKEN
= '*** INVALID ***';
58 * Global constant made accessible as class constants so that autoloader
60 * @deprecated since 1.27, use \MediaWiki\Session\Token::SUFFIX
62 const EDIT_TOKEN_SUFFIX
= Token
::SUFFIX
;
65 * @const int Serialized record version.
70 * Exclude user options that are set to their default value.
73 const GETOPTIONS_EXCLUDE_DEFAULTS
= 1;
78 const CHECK_USER_RIGHTS
= true;
83 const IGNORE_USER_RIGHTS
= false;
86 * Array of Strings List of member variables which are saved to the
87 * shared cache (memcached). Any operation which changes the
88 * corresponding database fields must call a cache-clearing function.
91 protected static $mCacheVars = [
99 'mEmailAuthenticated',
101 'mEmailTokenExpires',
106 // user_properties table
113 * Array of Strings Core rights.
114 * Each of these should have a corresponding message of the form
118 protected static $mCoreRights = [
163 'move-categorypages',
164 'move-rootuserpages',
168 'override-export-depth',
190 'userrights-interwiki',
198 * String Cached results of getAllRights()
200 protected static $mAllRights = false;
202 /** Cache variables */
215 /** @var string TS_MW timestamp from the DB */
217 /** @var string TS_MW timestamp from cache */
218 protected $mQuickTouched;
222 public $mEmailAuthenticated;
224 protected $mEmailToken;
226 protected $mEmailTokenExpires;
228 protected $mRegistration;
230 protected $mEditCount;
231 /** @var UserGroupMembership[] Associative array of (group name => UserGroupMembership object) */
232 protected $mGroupMemberships;
234 protected $mOptionOverrides;
238 * Bool Whether the cache variables have been loaded.
241 public $mOptionsLoaded;
244 * Array with already loaded items or true if all items have been loaded.
246 protected $mLoadedItems = [];
250 * String Initialization data source if mLoadedItems!==true. May be one of:
251 * - 'defaults' anonymous user initialised from class defaults
252 * - 'name' initialise from mName
253 * - 'id' initialise from mId
254 * - 'actor' initialise from mActorId
255 * - 'session' log in from session if possible
257 * Use the User::newFrom*() family of functions to set this.
262 * Lazy-initialized variables, invalidated with clearInstanceCache
266 protected $mDatePreference;
274 protected $mBlockreason;
276 protected $mEffectiveGroups;
278 protected $mImplicitGroups;
280 protected $mFormerGroups;
282 protected $mGlobalBlock;
290 /** @var WebRequest */
297 protected $mAllowUsertalk;
300 private $mBlockedFromCreateAccount = false;
302 /** @var int User::READ_* constant bitfield used to load data */
303 protected $queryFlagsUsed = self
::READ_NORMAL
;
305 public static $idCacheByName = [];
308 * Lightweight constructor for an anonymous user.
309 * Use the User::newFrom* factory functions for other kinds of users.
313 * @see newFromActorId()
314 * @see newFromConfirmationCode()
315 * @see newFromSession()
318 public function __construct() {
319 $this->clearInstanceCache( 'defaults' );
325 public function __toString() {
326 return (string)$this->getName();
330 * Test if it's safe to load this User object.
332 * You should typically check this before using $wgUser or
333 * RequestContext::getUser in a method that might be called before the
334 * system has been fully initialized. If the object is unsafe, you should
335 * use an anonymous user:
337 * $user = $wgUser->isSafeToLoad() ? $wgUser : new User;
343 public function isSafeToLoad() {
344 global $wgFullyInitialised;
346 // The user is safe to load if:
347 // * MW_NO_SESSION is undefined AND $wgFullyInitialised is true (safe to use session data)
348 // * mLoadedItems === true (already loaded)
349 // * mFrom !== 'session' (sessions not involved at all)
351 return ( !defined( 'MW_NO_SESSION' ) && $wgFullyInitialised ) ||
352 $this->mLoadedItems
=== true ||
$this->mFrom
!== 'session';
356 * Load the user table data for this object from the source given by mFrom.
358 * @param int $flags User::READ_* constant bitfield
360 public function load( $flags = self
::READ_NORMAL
) {
361 global $wgFullyInitialised;
363 if ( $this->mLoadedItems
=== true ) {
367 // Set it now to avoid infinite recursion in accessors
368 $oldLoadedItems = $this->mLoadedItems
;
369 $this->mLoadedItems
= true;
370 $this->queryFlagsUsed
= $flags;
372 // If this is called too early, things are likely to break.
373 if ( !$wgFullyInitialised && $this->mFrom
=== 'session' ) {
374 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
375 ->warning( 'User::loadFromSession called before the end of Setup.php', [
376 'exception' => new Exception( 'User::loadFromSession called before the end of Setup.php' ),
378 $this->loadDefaults();
379 $this->mLoadedItems
= $oldLoadedItems;
383 switch ( $this->mFrom
) {
385 $this->loadDefaults();
388 // Make sure this thread sees its own changes
389 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
390 if ( $lb->hasOrMadeRecentMasterChanges() ) {
391 $flags |
= self
::READ_LATEST
;
392 $this->queryFlagsUsed
= $flags;
395 $this->mId
= self
::idFromName( $this->mName
, $flags );
397 // Nonexistent user placeholder object
398 $this->loadDefaults( $this->mName
);
400 $this->loadFromId( $flags );
404 // Make sure this thread sees its own changes, if the ID isn't 0
405 if ( $this->mId
!= 0 ) {
406 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
407 if ( $lb->hasOrMadeRecentMasterChanges() ) {
408 $flags |
= self
::READ_LATEST
;
409 $this->queryFlagsUsed
= $flags;
413 $this->loadFromId( $flags );
416 // Make sure this thread sees its own changes
417 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
418 if ( $lb->hasOrMadeRecentMasterChanges() ) {
419 $flags |
= self
::READ_LATEST
;
420 $this->queryFlagsUsed
= $flags;
423 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
424 $row = wfGetDB( $index )->selectRow(
426 [ 'actor_user', 'actor_name' ],
427 [ 'actor_id' => $this->mActorId
],
434 $this->loadDefaults();
435 } elseif ( $row->actor_user
) {
436 $this->mId
= $row->actor_user
;
437 $this->loadFromId( $flags );
439 $this->loadDefaults( $row->actor_name
);
443 if ( !$this->loadFromSession() ) {
444 // Loading from session failed. Load defaults.
445 $this->loadDefaults();
447 Hooks
::run( 'UserLoadAfterLoadFromSession', [ $this ] );
450 throw new UnexpectedValueException(
451 "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
456 * Load user table data, given mId has already been set.
457 * @param int $flags User::READ_* constant bitfield
458 * @return bool False if the ID does not exist, true otherwise
460 public function loadFromId( $flags = self
::READ_NORMAL
) {
461 if ( $this->mId
== 0 ) {
462 // Anonymous users are not in the database (don't need cache)
463 $this->loadDefaults();
467 // Try cache (unless this needs data from the master DB).
468 // NOTE: if this thread called saveSettings(), the cache was cleared.
469 $latest = DBAccessObjectUtils
::hasFlags( $flags, self
::READ_LATEST
);
471 if ( !$this->loadFromDatabase( $flags ) ) {
472 // Can't load from ID
476 $this->loadFromCache();
479 $this->mLoadedItems
= true;
480 $this->queryFlagsUsed
= $flags;
487 * @param string $wikiId
490 public static function purge( $wikiId, $userId ) {
491 $cache = ObjectCache
::getMainWANInstance();
492 $key = $cache->makeGlobalKey( 'user', 'id', $wikiId, $userId );
493 $cache->delete( $key );
498 * @param WANObjectCache $cache
501 protected function getCacheKey( WANObjectCache
$cache ) {
502 return $cache->makeGlobalKey( 'user', 'id', wfWikiID(), $this->mId
);
506 * @param WANObjectCache $cache
510 public function getMutableCacheKeys( WANObjectCache
$cache ) {
511 $id = $this->getId();
513 return $id ?
[ $this->getCacheKey( $cache ) ] : [];
517 * Load user data from shared cache, given mId has already been set.
522 protected function loadFromCache() {
523 $cache = ObjectCache
::getMainWANInstance();
524 $data = $cache->getWithSetCallback(
525 $this->getCacheKey( $cache ),
527 function ( $oldValue, &$ttl, array &$setOpts ) use ( $cache ) {
528 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
529 wfDebug( "User: cache miss for user {$this->mId}\n" );
531 $this->loadFromDatabase( self
::READ_NORMAL
);
533 $this->loadOptions();
536 foreach ( self
::$mCacheVars as $name ) {
537 $data[$name] = $this->$name;
540 $ttl = $cache->adaptiveTTL( wfTimestamp( TS_UNIX
, $this->mTouched
), $ttl );
542 // if a user group membership is about to expire, the cache needs to
543 // expire at that time (T163691)
544 foreach ( $this->mGroupMemberships
as $ugm ) {
545 if ( $ugm->getExpiry() ) {
546 $secondsUntilExpiry = wfTimestamp( TS_UNIX
, $ugm->getExpiry() ) - time();
547 if ( $secondsUntilExpiry > 0 && $secondsUntilExpiry < $ttl ) {
548 $ttl = $secondsUntilExpiry;
555 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'version' => self
::VERSION
]
558 // Restore from cache
559 foreach ( self
::$mCacheVars as $name ) {
560 $this->$name = $data[$name];
566 /** @name newFrom*() static factory methods */
570 * Static factory method for creation from username.
572 * This is slightly less efficient than newFromId(), so use newFromId() if
573 * you have both an ID and a name handy.
575 * @param string $name Username, validated by Title::newFromText()
576 * @param string|bool $validate Validate username. Takes the same parameters as
577 * User::getCanonicalName(), except that true is accepted as an alias
578 * for 'valid', for BC.
580 * @return User|bool User object, or false if the username is invalid
581 * (e.g. if it contains illegal characters or is an IP address). If the
582 * username is not present in the database, the result will be a user object
583 * with a name, zero user ID and default settings.
585 public static function newFromName( $name, $validate = 'valid' ) {
586 if ( $validate === true ) {
589 $name = self
::getCanonicalName( $name, $validate );
590 if ( $name === false ) {
593 // Create unloaded user object
597 $u->setItemLoaded( 'name' );
603 * Static factory method for creation from a given user ID.
605 * @param int $id Valid user ID
606 * @return User The corresponding User object
608 public static function newFromId( $id ) {
612 $u->setItemLoaded( 'id' );
617 * Static factory method for creation from a given actor ID.
620 * @param int $id Valid actor ID
621 * @return User The corresponding User object
623 public static function newFromActorId( $id ) {
624 global $wgActorTableSchemaMigrationStage;
626 if ( $wgActorTableSchemaMigrationStage <= MIGRATION_OLD
) {
627 throw new BadMethodCallException(
628 'Cannot use ' . __METHOD__
. ' when $wgActorTableSchemaMigrationStage is MIGRATION_OLD'
635 $u->setItemLoaded( 'actor' );
640 * Static factory method for creation from an ID, name, and/or actor ID
642 * This does not check that the ID, name, and actor ID all correspond to
646 * @param int|null $userId User ID, if known
647 * @param string|null $userName User name, if known
648 * @param int|null $actorId Actor ID, if known
651 public static function newFromAnyId( $userId, $userName, $actorId ) {
652 global $wgActorTableSchemaMigrationStage;
655 $user->mFrom
= 'defaults';
657 if ( $wgActorTableSchemaMigrationStage > MIGRATION_OLD
&& $actorId !== null ) {
658 $user->mActorId
= (int)$actorId;
659 if ( $user->mActorId
!== 0 ) {
660 $user->mFrom
= 'actor';
662 $user->setItemLoaded( 'actor' );
665 if ( $userName !== null && $userName !== '' ) {
666 $user->mName
= $userName;
667 $user->mFrom
= 'name';
668 $user->setItemLoaded( 'name' );
671 if ( $userId !== null ) {
672 $user->mId
= (int)$userId;
673 if ( $user->mId
!== 0 ) {
676 $user->setItemLoaded( 'id' );
679 if ( $user->mFrom
=== 'defaults' ) {
680 throw new InvalidArgumentException(
681 'Cannot create a user with no name, no ID, and no actor ID'
689 * Factory method to fetch whichever user has a given email confirmation code.
690 * This code is generated when an account is created or its e-mail address
693 * If the code is invalid or has expired, returns NULL.
695 * @param string $code Confirmation code
696 * @param int $flags User::READ_* bitfield
699 public static function newFromConfirmationCode( $code, $flags = 0 ) {
700 $db = ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
701 ?
wfGetDB( DB_MASTER
)
702 : wfGetDB( DB_REPLICA
);
704 $id = $db->selectField(
708 'user_email_token' => md5( $code ),
709 'user_email_token_expires > ' . $db->addQuotes( $db->timestamp() ),
713 return $id ? self
::newFromId( $id ) : null;
717 * Create a new user object using data from session. If the login
718 * credentials are invalid, the result is an anonymous user.
720 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
723 public static function newFromSession( WebRequest
$request = null ) {
725 $user->mFrom
= 'session';
726 $user->mRequest
= $request;
731 * Create a new user object from a user row.
732 * The row should have the following fields from the user table in it:
733 * - either user_name or user_id to load further data if needed (or both)
735 * - all other fields (email, etc.)
736 * It is useless to provide the remaining fields if either user_id,
737 * user_name and user_real_name are not provided because the whole row
738 * will be loaded once more from the database when accessing them.
740 * @param stdClass $row A row from the user table
741 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
744 public static function newFromRow( $row, $data = null ) {
746 $user->loadFromRow( $row, $data );
751 * Static factory method for creation of a "system" user from username.
753 * A "system" user is an account that's used to attribute logged actions
754 * taken by MediaWiki itself, as opposed to a bot or human user. Examples
755 * might include the 'Maintenance script' or 'Conversion script' accounts
756 * used by various scripts in the maintenance/ directory or accounts such
757 * as 'MediaWiki message delivery' used by the MassMessage extension.
759 * This can optionally create the user if it doesn't exist, and "steal" the
760 * account if it does exist.
762 * "Stealing" an existing user is intended to make it impossible for normal
763 * authentication processes to use the account, effectively disabling the
764 * account for normal use:
765 * - Email is invalidated, to prevent account recovery by emailing a
766 * temporary password and to disassociate the account from the existing
768 * - The token is set to a magic invalid value, to kill existing sessions
769 * and to prevent $this->setToken() calls from resetting the token to a
771 * - SessionManager is instructed to prevent new sessions for the user, to
772 * do things like deauthorizing OAuth consumers.
773 * - AuthManager is instructed to revoke access, to invalidate or remove
774 * passwords and other credentials.
776 * @param string $name Username
777 * @param array $options Options are:
778 * - validate: As for User::getCanonicalName(), default 'valid'
779 * - create: Whether to create the user if it doesn't already exist, default true
780 * - steal: Whether to "disable" the account for normal use if it already
781 * exists, default false
785 public static function newSystemUser( $name, $options = [] ) {
787 'validate' => 'valid',
792 $name = self
::getCanonicalName( $name, $options['validate'] );
793 if ( $name === false ) {
797 $dbr = wfGetDB( DB_REPLICA
);
798 $userQuery = self
::getQueryInfo();
799 $row = $dbr->selectRow(
800 $userQuery['tables'],
801 $userQuery['fields'],
802 [ 'user_name' => $name ],
808 // Try the master database...
809 $dbw = wfGetDB( DB_MASTER
);
810 $row = $dbw->selectRow(
811 $userQuery['tables'],
812 $userQuery['fields'],
813 [ 'user_name' => $name ],
821 // No user. Create it?
822 return $options['create']
823 ? self
::createNew( $name, [ 'token' => self
::INVALID_TOKEN
] )
827 $user = self
::newFromRow( $row );
829 // A user is considered to exist as a non-system user if it can
830 // authenticate, or has an email set, or has a non-invalid token.
831 if ( $user->mEmail ||
$user->mToken
!== self
::INVALID_TOKEN ||
832 AuthManager
::singleton()->userCanAuthenticate( $name )
834 // User exists. Steal it?
835 if ( !$options['steal'] ) {
839 AuthManager
::singleton()->revokeAccessForUser( $name );
841 $user->invalidateEmail();
842 $user->mToken
= self
::INVALID_TOKEN
;
843 $user->saveSettings();
844 SessionManager
::singleton()->preventSessionsForUser( $user->getName() );
853 * Get the username corresponding to a given user ID
854 * @param int $id User ID
855 * @return string|bool The corresponding username
857 public static function whoIs( $id ) {
858 return UserCache
::singleton()->getProp( $id, 'name' );
862 * Get the real name of a user given their user ID
864 * @param int $id User ID
865 * @return string|bool The corresponding user's real name
867 public static function whoIsReal( $id ) {
868 return UserCache
::singleton()->getProp( $id, 'real_name' );
872 * Get database id given a user name
873 * @param string $name Username
874 * @param int $flags User::READ_* constant bitfield
875 * @return int|null The corresponding user's ID, or null if user is nonexistent
877 public static function idFromName( $name, $flags = self
::READ_NORMAL
) {
878 $nt = Title
::makeTitleSafe( NS_USER
, $name );
879 if ( is_null( $nt ) ) {
884 if ( !( $flags & self
::READ_LATEST
) && array_key_exists( $name, self
::$idCacheByName ) ) {
885 return self
::$idCacheByName[$name];
888 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
889 $db = wfGetDB( $index );
894 [ 'user_name' => $nt->getText() ],
899 if ( $s === false ) {
902 $result = $s->user_id
;
905 self
::$idCacheByName[$name] = $result;
907 if ( count( self
::$idCacheByName ) > 1000 ) {
908 self
::$idCacheByName = [];
915 * Reset the cache used in idFromName(). For use in tests.
917 public static function resetIdByNameCache() {
918 self
::$idCacheByName = [];
922 * Does the string match an anonymous IP address?
924 * This function exists for username validation, in order to reject
925 * usernames which are similar in form to IP addresses. Strings such
926 * as 300.300.300.300 will return true because it looks like an IP
927 * address, despite not being strictly valid.
929 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
930 * address because the usemod software would "cloak" anonymous IP
931 * addresses like this, if we allowed accounts like this to be created
932 * new users could get the old edits of these anonymous users.
934 * @param string $name Name to match
937 public static function isIP( $name ) {
938 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
939 || IP
::isIPv6( $name );
943 * Is the user an IP range?
948 public function isIPRange() {
949 return IP
::isValidRange( $this->mName
);
953 * Is the input a valid username?
955 * Checks if the input is a valid username, we don't want an empty string,
956 * an IP address, anything that contains slashes (would mess up subpages),
957 * is longer than the maximum allowed username size or doesn't begin with
960 * @param string $name Name to match
963 public static function isValidUserName( $name ) {
964 global $wgContLang, $wgMaxNameChars;
967 || self
::isIP( $name )
968 ||
strpos( $name, '/' ) !== false
969 ||
strlen( $name ) > $wgMaxNameChars
970 ||
$name != $wgContLang->ucfirst( $name )
975 // Ensure that the name can't be misresolved as a different title,
976 // such as with extra namespace keys at the start.
977 $parsed = Title
::newFromText( $name );
978 if ( is_null( $parsed )
979 ||
$parsed->getNamespace()
980 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
984 // Check an additional blacklist of troublemaker characters.
985 // Should these be merged into the title char list?
986 $unicodeBlacklist = '/[' .
987 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
988 '\x{00a0}' . # non-breaking space
989 '\x{2000}-\x{200f}' . # various whitespace
990 '\x{2028}-\x{202f}' . # breaks and control chars
991 '\x{3000}' . # ideographic space
992 '\x{e000}-\x{f8ff}' . # private use
994 if ( preg_match( $unicodeBlacklist, $name ) ) {
1002 * Usernames which fail to pass this function will be blocked
1003 * from user login and new account registrations, but may be used
1004 * internally by batch processes.
1006 * If an account already exists in this form, login will be blocked
1007 * by a failure to pass this function.
1009 * @param string $name Name to match
1012 public static function isUsableName( $name ) {
1013 global $wgReservedUsernames;
1014 // Must be a valid username, obviously ;)
1015 if ( !self
::isValidUserName( $name ) ) {
1019 static $reservedUsernames = false;
1020 if ( !$reservedUsernames ) {
1021 $reservedUsernames = $wgReservedUsernames;
1022 Hooks
::run( 'UserGetReservedNames', [ &$reservedUsernames ] );
1025 // Certain names may be reserved for batch processes.
1026 foreach ( $reservedUsernames as $reserved ) {
1027 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
1028 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
1030 if ( $reserved == $name ) {
1038 * Return the users who are members of the given group(s). In case of multiple groups,
1039 * users who are members of at least one of them are returned.
1041 * @param string|array $groups A single group name or an array of group names
1042 * @param int $limit Max number of users to return. The actual limit will never exceed 5000
1043 * records; larger values are ignored.
1044 * @param int $after ID the user to start after
1045 * @return UserArrayFromResult
1047 public static function findUsersByGroup( $groups, $limit = 5000, $after = null ) {
1048 if ( $groups === [] ) {
1049 return UserArrayFromResult
::newFromIDs( [] );
1052 $groups = array_unique( (array)$groups );
1053 $limit = min( 5000, $limit );
1055 $conds = [ 'ug_group' => $groups ];
1056 if ( $after !== null ) {
1057 $conds[] = 'ug_user > ' . (int)$after;
1060 $dbr = wfGetDB( DB_REPLICA
);
1061 $ids = $dbr->selectFieldValues(
1068 'ORDER BY' => 'ug_user',
1072 return UserArray
::newFromIDs( $ids );
1076 * Usernames which fail to pass this function will be blocked
1077 * from new account registrations, but may be used internally
1078 * either by batch processes or by user accounts which have
1079 * already been created.
1081 * Additional blacklisting may be added here rather than in
1082 * isValidUserName() to avoid disrupting existing accounts.
1084 * @param string $name String to match
1087 public static function isCreatableName( $name ) {
1088 global $wgInvalidUsernameCharacters;
1090 // Ensure that the username isn't longer than 235 bytes, so that
1091 // (at least for the builtin skins) user javascript and css files
1092 // will work. (T25080)
1093 if ( strlen( $name ) > 235 ) {
1094 wfDebugLog( 'username', __METHOD__
.
1095 ": '$name' invalid due to length" );
1099 // Preg yells if you try to give it an empty string
1100 if ( $wgInvalidUsernameCharacters !== '' ) {
1101 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
1102 wfDebugLog( 'username', __METHOD__
.
1103 ": '$name' invalid due to wgInvalidUsernameCharacters" );
1108 return self
::isUsableName( $name );
1112 * Is the input a valid password for this user?
1114 * @param string $password Desired password
1117 public function isValidPassword( $password ) {
1118 // simple boolean wrapper for getPasswordValidity
1119 return $this->getPasswordValidity( $password ) === true;
1123 * Given unvalidated password input, return error message on failure.
1125 * @param string $password Desired password
1126 * @return bool|string|array True on success, string or array of error message on failure
1128 public function getPasswordValidity( $password ) {
1129 $result = $this->checkPasswordValidity( $password );
1130 if ( $result->isGood() ) {
1134 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
1135 $messages[] = $error['message'];
1137 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
1138 $messages[] = $warning['message'];
1140 if ( count( $messages ) === 1 ) {
1141 return $messages[0];
1148 * Check if this is a valid password for this user
1150 * Create a Status object based on the password's validity.
1151 * The Status should be set to fatal if the user should not
1152 * be allowed to log in, and should have any errors that
1153 * would block changing the password.
1155 * If the return value of this is not OK, the password
1156 * should not be checked. If the return value is not Good,
1157 * the password can be checked, but the user should not be
1158 * able to set their password to this.
1160 * @param string $password Desired password
1164 public function checkPasswordValidity( $password ) {
1165 global $wgPasswordPolicy;
1167 $upp = new UserPasswordPolicy(
1168 $wgPasswordPolicy['policies'],
1169 $wgPasswordPolicy['checks']
1172 $status = Status
::newGood();
1173 $result = false; // init $result to false for the internal checks
1175 if ( !Hooks
::run( 'isValidPassword', [ $password, &$result, $this ] ) ) {
1176 $status->error( $result );
1180 if ( $result === false ) {
1181 $status->merge( $upp->checkUserPassword( $this, $password ) );
1183 } elseif ( $result === true ) {
1186 $status->error( $result );
1187 return $status; // the isValidPassword hook set a string $result and returned true
1192 * Given unvalidated user input, return a canonical username, or false if
1193 * the username is invalid.
1194 * @param string $name User input
1195 * @param string|bool $validate Type of validation to use:
1196 * - false No validation
1197 * - 'valid' Valid for batch processes
1198 * - 'usable' Valid for batch processes and login
1199 * - 'creatable' Valid for batch processes, login and account creation
1201 * @throws InvalidArgumentException
1202 * @return bool|string
1204 public static function getCanonicalName( $name, $validate = 'valid' ) {
1205 // Force usernames to capital
1207 $name = $wgContLang->ucfirst( $name );
1209 # Reject names containing '#'; these will be cleaned up
1210 # with title normalisation, but then it's too late to
1212 if ( strpos( $name, '#' ) !== false ) {
1216 // Clean up name according to title rules,
1217 // but only when validation is requested (T14654)
1218 $t = ( $validate !== false ) ?
1219 Title
::newFromText( $name, NS_USER
) : Title
::makeTitle( NS_USER
, $name );
1220 // Check for invalid titles
1221 if ( is_null( $t ) ||
$t->getNamespace() !== NS_USER ||
$t->isExternal() ) {
1225 // Reject various classes of invalid names
1226 $name = AuthManager
::callLegacyAuthPlugin(
1227 'getCanonicalName', [ $t->getText() ], $t->getText()
1230 switch ( $validate ) {
1234 if ( !self
::isValidUserName( $name ) ) {
1239 if ( !self
::isUsableName( $name ) ) {
1244 if ( !self
::isCreatableName( $name ) ) {
1249 throw new InvalidArgumentException(
1250 'Invalid parameter value for $validate in ' . __METHOD__
);
1256 * Return a random password.
1258 * @deprecated since 1.27, use PasswordFactory::generateRandomPasswordString()
1259 * @return string New random password
1261 public static function randomPassword() {
1262 global $wgMinimalPasswordLength;
1263 return PasswordFactory
::generateRandomPasswordString( $wgMinimalPasswordLength );
1267 * Set cached properties to default.
1269 * @note This no longer clears uncached lazy-initialised properties;
1270 * the constructor does that instead.
1272 * @param string|bool $name
1274 public function loadDefaults( $name = false ) {
1276 $this->mName
= $name;
1277 $this->mActorId
= null;
1278 $this->mRealName
= '';
1280 $this->mOptionOverrides
= null;
1281 $this->mOptionsLoaded
= false;
1283 $loggedOut = $this->mRequest
&& !defined( 'MW_NO_SESSION' )
1284 ?
$this->mRequest
->getSession()->getLoggedOutTimestamp() : 0;
1285 if ( $loggedOut !== 0 ) {
1286 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1288 $this->mTouched
= '1'; # Allow any pages to be cached
1291 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1292 $this->mEmailAuthenticated
= null;
1293 $this->mEmailToken
= '';
1294 $this->mEmailTokenExpires
= null;
1295 $this->mRegistration
= wfTimestamp( TS_MW
);
1296 $this->mGroupMemberships
= [];
1298 Hooks
::run( 'UserLoadDefaults', [ $this, $name ] );
1302 * Return whether an item has been loaded.
1304 * @param string $item Item to check. Current possibilities:
1308 * @param string $all 'all' to check if the whole object has been loaded
1309 * or any other string to check if only the item is available (e.g.
1313 public function isItemLoaded( $item, $all = 'all' ) {
1314 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1315 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1319 * Set that an item has been loaded
1321 * @param string $item
1323 protected function setItemLoaded( $item ) {
1324 if ( is_array( $this->mLoadedItems
) ) {
1325 $this->mLoadedItems
[$item] = true;
1330 * Load user data from the session.
1332 * @return bool True if the user is logged in, false otherwise.
1334 private function loadFromSession() {
1337 Hooks
::run( 'UserLoadFromSession', [ $this, &$result ], '1.27' );
1338 if ( $result !== null ) {
1342 // MediaWiki\Session\Session already did the necessary authentication of the user
1343 // returned here, so just use it if applicable.
1344 $session = $this->getRequest()->getSession();
1345 $user = $session->getUser();
1346 if ( $user->isLoggedIn() ) {
1347 $this->loadFromUserObject( $user );
1348 if ( $user->isBlocked() ) {
1349 // If this user is autoblocked, set a cookie to track the Block. This has to be done on
1350 // every session load, because an autoblocked editor might not edit again from the same
1351 // IP address after being blocked.
1352 $this->trackBlockWithCookie();
1355 // Other code expects these to be set in the session, so set them.
1356 $session->set( 'wsUserID', $this->getId() );
1357 $session->set( 'wsUserName', $this->getName() );
1358 $session->set( 'wsToken', $this->getToken() );
1367 * Set the 'BlockID' cookie depending on block type and user authentication status.
1369 public function trackBlockWithCookie() {
1370 $block = $this->getBlock();
1371 if ( $block && $this->getRequest()->getCookie( 'BlockID' ) === null ) {
1372 $config = RequestContext
::getMain()->getConfig();
1373 $shouldSetCookie = false;
1375 if ( $this->isAnon() && $config->get( 'CookieSetOnIpBlock' ) ) {
1376 // If user is logged-out, set a cookie to track the Block
1377 $shouldSetCookie = in_array( $block->getType(), [
1378 Block
::TYPE_IP
, Block
::TYPE_RANGE
1380 if ( $shouldSetCookie ) {
1381 $block->setCookie( $this->getRequest()->response() );
1383 // temporary measure the use of cookies on ip blocks
1384 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
1385 $stats->increment( 'block.ipblock.setCookie.success' );
1387 } elseif ( $this->isLoggedIn() && $config->get( 'CookieSetOnAutoblock' ) ) {
1388 $shouldSetCookie = $block->getType() === Block
::TYPE_USER
&& $block->isAutoblocking();
1389 if ( $shouldSetCookie ) {
1390 $block->setCookie( $this->getRequest()->response() );
1397 * Load user and user_group data from the database.
1398 * $this->mId must be set, this is how the user is identified.
1400 * @param int $flags User::READ_* constant bitfield
1401 * @return bool True if the user exists, false if the user is anonymous
1403 public function loadFromDatabase( $flags = self
::READ_LATEST
) {
1405 $this->mId
= intval( $this->mId
);
1407 if ( !$this->mId
) {
1408 // Anonymous users are not in the database
1409 $this->loadDefaults();
1413 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
1414 $db = wfGetDB( $index );
1416 $userQuery = self
::getQueryInfo();
1417 $s = $db->selectRow(
1418 $userQuery['tables'],
1419 $userQuery['fields'],
1420 [ 'user_id' => $this->mId
],
1426 $this->queryFlagsUsed
= $flags;
1427 Hooks
::run( 'UserLoadFromDatabase', [ $this, &$s ] );
1429 if ( $s !== false ) {
1430 // Initialise user table data
1431 $this->loadFromRow( $s );
1432 $this->mGroupMemberships
= null; // deferred
1433 $this->getEditCount(); // revalidation for nulls
1438 $this->loadDefaults();
1444 * Initialize this object from a row from the user table.
1446 * @param stdClass $row Row from the user table to load.
1447 * @param array $data Further user data to load into the object
1449 * user_groups Array of arrays or stdClass result rows out of the user_groups
1450 * table. Previously you were supposed to pass an array of strings
1451 * here, but we also need expiry info nowadays, so an array of
1452 * strings is ignored.
1453 * user_properties Array with properties out of the user_properties table
1455 protected function loadFromRow( $row, $data = null ) {
1456 global $wgActorTableSchemaMigrationStage;
1458 if ( !is_object( $row ) ) {
1459 throw new InvalidArgumentException( '$row must be an object' );
1464 $this->mGroupMemberships
= null; // deferred
1466 if ( $wgActorTableSchemaMigrationStage > MIGRATION_OLD
) {
1467 if ( isset( $row->actor_id
) ) {
1468 $this->mActorId
= (int)$row->actor_id
;
1469 if ( $this->mActorId
!== 0 ) {
1470 $this->mFrom
= 'actor';
1472 $this->setItemLoaded( 'actor' );
1478 if ( isset( $row->user_name
) && $row->user_name
!== '' ) {
1479 $this->mName
= $row->user_name
;
1480 $this->mFrom
= 'name';
1481 $this->setItemLoaded( 'name' );
1486 if ( isset( $row->user_real_name
) ) {
1487 $this->mRealName
= $row->user_real_name
;
1488 $this->setItemLoaded( 'realname' );
1493 if ( isset( $row->user_id
) ) {
1494 $this->mId
= intval( $row->user_id
);
1495 if ( $this->mId
!== 0 ) {
1496 $this->mFrom
= 'id';
1498 $this->setItemLoaded( 'id' );
1503 if ( isset( $row->user_id
) && isset( $row->user_name
) && $row->user_name
!== '' ) {
1504 self
::$idCacheByName[$row->user_name
] = $row->user_id
;
1507 if ( isset( $row->user_editcount
) ) {
1508 $this->mEditCount
= $row->user_editcount
;
1513 if ( isset( $row->user_touched
) ) {
1514 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1519 if ( isset( $row->user_token
) ) {
1520 // The definition for the column is binary(32), so trim the NULs
1521 // that appends. The previous definition was char(32), so trim
1523 $this->mToken
= rtrim( $row->user_token
, " \0" );
1524 if ( $this->mToken
=== '' ) {
1525 $this->mToken
= null;
1531 if ( isset( $row->user_email
) ) {
1532 $this->mEmail
= $row->user_email
;
1533 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1534 $this->mEmailToken
= $row->user_email_token
;
1535 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1536 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1542 $this->mLoadedItems
= true;
1545 if ( is_array( $data ) ) {
1546 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1547 if ( !count( $data['user_groups'] ) ) {
1548 $this->mGroupMemberships
= [];
1550 $firstGroup = reset( $data['user_groups'] );
1551 if ( is_array( $firstGroup ) ||
is_object( $firstGroup ) ) {
1552 $this->mGroupMemberships
= [];
1553 foreach ( $data['user_groups'] as $row ) {
1554 $ugm = UserGroupMembership
::newFromRow( (object)$row );
1555 $this->mGroupMemberships
[$ugm->getGroup()] = $ugm;
1560 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1561 $this->loadOptions( $data['user_properties'] );
1567 * Load the data for this user object from another user object.
1571 protected function loadFromUserObject( $user ) {
1573 foreach ( self
::$mCacheVars as $var ) {
1574 $this->$var = $user->$var;
1579 * Load the groups from the database if they aren't already loaded.
1581 private function loadGroups() {
1582 if ( is_null( $this->mGroupMemberships
) ) {
1583 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
1584 ?
wfGetDB( DB_MASTER
)
1585 : wfGetDB( DB_REPLICA
);
1586 $this->mGroupMemberships
= UserGroupMembership
::getMembershipsForUser(
1592 * Add the user to the group if he/she meets given criteria.
1594 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1595 * possible to remove manually via Special:UserRights. In such case it
1596 * will not be re-added automatically. The user will also not lose the
1597 * group if they no longer meet the criteria.
1599 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1601 * @return array Array of groups the user has been promoted to.
1603 * @see $wgAutopromoteOnce
1605 public function addAutopromoteOnceGroups( $event ) {
1606 global $wgAutopromoteOnceLogInRC;
1608 if ( wfReadOnly() ||
!$this->getId() ) {
1612 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1613 if ( !count( $toPromote ) ) {
1617 if ( !$this->checkAndSetTouched() ) {
1618 return []; // raced out (bug T48834)
1621 $oldGroups = $this->getGroups(); // previous groups
1622 $oldUGMs = $this->getGroupMemberships();
1623 foreach ( $toPromote as $group ) {
1624 $this->addGroup( $group );
1626 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1627 $newUGMs = $this->getGroupMemberships();
1629 // update groups in external authentication database
1630 Hooks
::run( 'UserGroupsChanged', [ $this, $toPromote, [], false, false, $oldUGMs, $newUGMs ] );
1631 AuthManager
::callLegacyAuthPlugin( 'updateExternalDBGroups', [ $this, $toPromote ] );
1633 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1634 $logEntry->setPerformer( $this );
1635 $logEntry->setTarget( $this->getUserPage() );
1636 $logEntry->setParameters( [
1637 '4::oldgroups' => $oldGroups,
1638 '5::newgroups' => $newGroups,
1640 $logid = $logEntry->insert();
1641 if ( $wgAutopromoteOnceLogInRC ) {
1642 $logEntry->publish( $logid );
1649 * Builds update conditions. Additional conditions may be added to $conditions to
1650 * protected against race conditions using a compare-and-set (CAS) mechanism
1651 * based on comparing $this->mTouched with the user_touched field.
1653 * @param Database $db
1654 * @param array $conditions WHERE conditions for use with Database::update
1655 * @return array WHERE conditions for use with Database::update
1657 protected function makeUpdateConditions( Database
$db, array $conditions ) {
1658 if ( $this->mTouched
) {
1659 // CAS check: only update if the row wasn't changed sicne it was loaded.
1660 $conditions['user_touched'] = $db->timestamp( $this->mTouched
);
1667 * Bump user_touched if it didn't change since this object was loaded
1669 * On success, the mTouched field is updated.
1670 * The user serialization cache is always cleared.
1672 * @return bool Whether user_touched was actually updated
1675 protected function checkAndSetTouched() {
1678 if ( !$this->mId
) {
1679 return false; // anon
1682 // Get a new user_touched that is higher than the old one
1683 $newTouched = $this->newTouchedTimestamp();
1685 $dbw = wfGetDB( DB_MASTER
);
1686 $dbw->update( 'user',
1687 [ 'user_touched' => $dbw->timestamp( $newTouched ) ],
1688 $this->makeUpdateConditions( $dbw, [
1689 'user_id' => $this->mId
,
1693 $success = ( $dbw->affectedRows() > 0 );
1696 $this->mTouched
= $newTouched;
1697 $this->clearSharedCache();
1699 // Clears on failure too since that is desired if the cache is stale
1700 $this->clearSharedCache( 'refresh' );
1707 * Clear various cached data stored in this object. The cache of the user table
1708 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1710 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1711 * given source. May be "name", "id", "actor", "defaults", "session", or false for no reload.
1713 public function clearInstanceCache( $reloadFrom = false ) {
1714 $this->mNewtalk
= -1;
1715 $this->mDatePreference
= null;
1716 $this->mBlockedby
= -1; # Unset
1717 $this->mHash
= false;
1718 $this->mRights
= null;
1719 $this->mEffectiveGroups
= null;
1720 $this->mImplicitGroups
= null;
1721 $this->mGroupMemberships
= null;
1722 $this->mOptions
= null;
1723 $this->mOptionsLoaded
= false;
1724 $this->mEditCount
= null;
1726 if ( $reloadFrom ) {
1727 $this->mLoadedItems
= [];
1728 $this->mFrom
= $reloadFrom;
1733 * Combine the language default options with any site-specific options
1734 * and add the default language variants.
1736 * @return array Array of String options
1738 public static function getDefaultOptions() {
1739 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1741 static $defOpt = null;
1742 static $defOptLang = null;
1744 if ( $defOpt !== null && $defOptLang === $wgContLang->getCode() ) {
1745 // $wgContLang does not change (and should not change) mid-request,
1746 // but the unit tests change it anyway, and expect this method to
1747 // return values relevant to the current $wgContLang.
1751 $defOpt = $wgDefaultUserOptions;
1752 // Default language setting
1753 $defOptLang = $wgContLang->getCode();
1754 $defOpt['language'] = $defOptLang;
1755 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1756 $defOpt[$langCode == $wgContLang->getCode() ?
'variant' : "variant-$langCode"] = $langCode;
1759 // NOTE: don't use SearchEngineConfig::getSearchableNamespaces here,
1760 // since extensions may change the set of searchable namespaces depending
1761 // on user groups/permissions.
1762 foreach ( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
1763 $defOpt['searchNs' . $nsnum] = (bool)$val;
1765 $defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1767 Hooks
::run( 'UserGetDefaultOptions', [ &$defOpt ] );
1773 * Get a given default option value.
1775 * @param string $opt Name of option to retrieve
1776 * @return string Default option value
1778 public static function getDefaultOption( $opt ) {
1779 $defOpts = self
::getDefaultOptions();
1780 if ( isset( $defOpts[$opt] ) ) {
1781 return $defOpts[$opt];
1788 * Get blocking information
1789 * @param bool $bFromSlave Whether to check the replica DB first.
1790 * To improve performance, non-critical checks are done against replica DBs.
1791 * Check when actually saving should be done against master.
1793 private function getBlockedStatus( $bFromSlave = true ) {
1794 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff, $wgSoftBlockRanges;
1796 if ( -1 != $this->mBlockedby
) {
1800 wfDebug( __METHOD__
. ": checking...\n" );
1802 // Initialize data...
1803 // Otherwise something ends up stomping on $this->mBlockedby when
1804 // things get lazy-loaded later, causing false positive block hits
1805 // due to -1 !== 0. Probably session-related... Nothing should be
1806 // overwriting mBlockedby, surely?
1809 # We only need to worry about passing the IP address to the Block generator if the
1810 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1811 # know which IP address they're actually coming from
1813 if ( !$this->isAllowed( 'ipblock-exempt' ) ) {
1814 // $wgUser->getName() only works after the end of Setup.php. Until
1815 // then, assume it's a logged-out user.
1816 $globalUserName = $wgUser->isSafeToLoad()
1817 ?
$wgUser->getName()
1818 : IP
::sanitizeIP( $wgUser->getRequest()->getIP() );
1819 if ( $this->getName() === $globalUserName ) {
1820 $ip = $this->getRequest()->getIP();
1825 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1828 if ( !$block instanceof Block
) {
1829 $block = $this->getBlockFromCookieValue( $this->getRequest()->getCookie( 'BlockID' ) );
1833 if ( !$block instanceof Block
&& $ip !== null && !in_array( $ip, $wgProxyWhitelist ) ) {
1835 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1836 $block = new Block( [
1837 'byText' => wfMessage( 'proxyblocker' )->text(),
1838 'reason' => wfMessage( 'proxyblockreason' )->plain(),
1840 'systemBlock' => 'proxy',
1842 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1843 $block = new Block( [
1844 'byText' => wfMessage( 'sorbs' )->text(),
1845 'reason' => wfMessage( 'sorbsreason' )->plain(),
1847 'systemBlock' => 'dnsbl',
1852 // (T25343) Apply IP blocks to the contents of XFF headers, if enabled
1853 if ( !$block instanceof Block
1854 && $wgApplyIpBlocksToXff
1856 && !in_array( $ip, $wgProxyWhitelist )
1858 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1859 $xff = array_map( 'trim', explode( ',', $xff ) );
1860 $xff = array_diff( $xff, [ $ip ] );
1861 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1862 $block = Block
::chooseBlock( $xffblocks, $xff );
1863 if ( $block instanceof Block
) {
1864 # Mangle the reason to alert the user that the block
1865 # originated from matching the X-Forwarded-For header.
1866 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->plain();
1870 if ( !$block instanceof Block
1873 && IP
::isInRanges( $ip, $wgSoftBlockRanges )
1875 $block = new Block( [
1877 'byText' => 'MediaWiki default',
1878 'reason' => wfMessage( 'softblockrangesreason', $ip )->plain(),
1880 'systemBlock' => 'wgSoftBlockRanges',
1884 if ( $block instanceof Block
) {
1885 wfDebug( __METHOD__
. ": Found block.\n" );
1886 $this->mBlock
= $block;
1887 $this->mBlockedby
= $block->getByName();
1888 $this->mBlockreason
= $block->mReason
;
1889 $this->mHideName
= $block->mHideName
;
1890 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1892 $this->mBlock
= null;
1893 $this->mBlockedby
= '';
1894 $this->mBlockreason
= '';
1895 $this->mHideName
= 0;
1896 $this->mAllowUsertalk
= false;
1899 // Avoid PHP 7.1 warning of passing $this by reference
1902 Hooks
::run( 'GetBlockedStatus', [ &$user ] );
1906 * Try to load a Block from an ID given in a cookie value.
1907 * @param string|null $blockCookieVal The cookie value to check.
1908 * @return Block|bool The Block object, or false if none could be loaded.
1910 protected function getBlockFromCookieValue( $blockCookieVal ) {
1911 // Make sure there's something to check. The cookie value must start with a number.
1912 if ( strlen( $blockCookieVal ) < 1 ||
!is_numeric( substr( $blockCookieVal, 0, 1 ) ) ) {
1915 // Load the Block from the ID in the cookie.
1916 $blockCookieId = Block
::getIdFromCookieValue( $blockCookieVal );
1917 if ( $blockCookieId !== null ) {
1918 // An ID was found in the cookie.
1919 $tmpBlock = Block
::newFromID( $blockCookieId );
1920 if ( $tmpBlock instanceof Block
) {
1921 $config = RequestContext
::getMain()->getConfig();
1923 switch ( $tmpBlock->getType() ) {
1924 case Block
::TYPE_USER
:
1925 $blockIsValid = !$tmpBlock->isExpired() && $tmpBlock->isAutoblocking();
1926 $useBlockCookie = ( $config->get( 'CookieSetOnAutoblock' ) === true );
1928 case Block
::TYPE_IP
:
1929 case Block
::TYPE_RANGE
:
1930 // If block is type IP or IP range, load only if user is not logged in (T152462)
1931 $blockIsValid = !$tmpBlock->isExpired() && !$this->isLoggedIn();
1932 $useBlockCookie = ( $config->get( 'CookieSetOnIpBlock' ) === true );
1935 $blockIsValid = false;
1936 $useBlockCookie = false;
1939 if ( $blockIsValid && $useBlockCookie ) {
1943 // If the block is not valid, remove the cookie.
1944 Block
::clearCookie( $this->getRequest()->response() );
1947 // If the block doesn't exist, remove the cookie.
1948 Block
::clearCookie( $this->getRequest()->response() );
1955 * Whether the given IP is in a DNS blacklist.
1957 * @param string $ip IP to check
1958 * @param bool $checkWhitelist Whether to check the whitelist first
1959 * @return bool True if blacklisted.
1961 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1962 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1964 if ( !$wgEnableDnsBlacklist ) {
1968 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1972 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1976 * Whether the given IP is in a given DNS blacklist.
1978 * @param string $ip IP to check
1979 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1980 * @return bool True if blacklisted.
1982 public function inDnsBlacklist( $ip, $bases ) {
1984 // @todo FIXME: IPv6 ??? (https://bugs.php.net/bug.php?id=33170)
1985 if ( IP
::isIPv4( $ip ) ) {
1986 // Reverse IP, T23255
1987 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1989 foreach ( (array)$bases as $base ) {
1991 // If we have an access key, use that too (ProjectHoneypot, etc.)
1993 if ( is_array( $base ) ) {
1994 if ( count( $base ) >= 2 ) {
1995 // Access key is 1, base URL is 0
1996 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1998 $host = "$ipReversed.{$base[0]}";
2000 $basename = $base[0];
2002 $host = "$ipReversed.$base";
2006 $ipList = gethostbynamel( $host );
2009 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
2013 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
2022 * Check if an IP address is in the local proxy list
2028 public static function isLocallyBlockedProxy( $ip ) {
2029 global $wgProxyList;
2031 if ( !$wgProxyList ) {
2035 if ( !is_array( $wgProxyList ) ) {
2036 // Load values from the specified file
2037 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
2040 $resultProxyList = [];
2041 $deprecatedIPEntries = [];
2043 // backward compatibility: move all ip addresses in keys to values
2044 foreach ( $wgProxyList as $key => $value ) {
2045 $keyIsIP = IP
::isIPAddress( $key );
2046 $valueIsIP = IP
::isIPAddress( $value );
2047 if ( $keyIsIP && !$valueIsIP ) {
2048 $deprecatedIPEntries[] = $key;
2049 $resultProxyList[] = $key;
2050 } elseif ( $keyIsIP && $valueIsIP ) {
2051 $deprecatedIPEntries[] = $key;
2052 $resultProxyList[] = $key;
2053 $resultProxyList[] = $value;
2055 $resultProxyList[] = $value;
2059 if ( $deprecatedIPEntries ) {
2061 'IP addresses in the keys of $wgProxyList (found the following IP addresses in keys: ' .
2062 implode( ', ', $deprecatedIPEntries ) . ', please move them to values)', '1.30' );
2065 $proxyListIPSet = new IPSet( $resultProxyList );
2066 return $proxyListIPSet->match( $ip );
2070 * Is this user subject to rate limiting?
2072 * @return bool True if rate limited
2074 public function isPingLimitable() {
2075 global $wgRateLimitsExcludedIPs;
2076 if ( IP
::isInRanges( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
2077 // No other good way currently to disable rate limits
2078 // for specific IPs. :P
2079 // But this is a crappy hack and should die.
2082 return !$this->isAllowed( 'noratelimit' );
2086 * Primitive rate limits: enforce maximum actions per time period
2087 * to put a brake on flooding.
2089 * The method generates both a generic profiling point and a per action one
2090 * (suffix being "-$action".
2092 * @note When using a shared cache like memcached, IP-address
2093 * last-hit counters will be shared across wikis.
2095 * @param string $action Action to enforce; 'edit' if unspecified
2096 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
2097 * @return bool True if a rate limiter was tripped
2099 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
2100 // Avoid PHP 7.1 warning of passing $this by reference
2102 // Call the 'PingLimiter' hook
2104 if ( !Hooks
::run( 'PingLimiter', [ &$user, $action, &$result, $incrBy ] ) ) {
2108 global $wgRateLimits;
2109 if ( !isset( $wgRateLimits[$action] ) ) {
2113 $limits = array_merge(
2114 [ '&can-bypass' => true ],
2115 $wgRateLimits[$action]
2118 // Some groups shouldn't trigger the ping limiter, ever
2119 if ( $limits['&can-bypass'] && !$this->isPingLimitable() ) {
2124 $id = $this->getId();
2126 $isNewbie = $this->isNewbie();
2127 $cache = ObjectCache
::getLocalClusterInstance();
2131 if ( isset( $limits['anon'] ) ) {
2132 $keys[$cache->makeKey( 'limiter', $action, 'anon' )] = $limits['anon'];
2135 // limits for logged-in users
2136 if ( isset( $limits['user'] ) ) {
2137 $userLimit = $limits['user'];
2139 // limits for newbie logged-in users
2140 if ( $isNewbie && isset( $limits['newbie'] ) ) {
2141 $keys[$cache->makeKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
2145 // limits for anons and for newbie logged-in users
2148 if ( isset( $limits['ip'] ) ) {
2149 $ip = $this->getRequest()->getIP();
2150 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
2152 // subnet-based limits
2153 if ( isset( $limits['subnet'] ) ) {
2154 $ip = $this->getRequest()->getIP();
2155 $subnet = IP
::getSubnet( $ip );
2156 if ( $subnet !== false ) {
2157 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
2162 // Check for group-specific permissions
2163 // If more than one group applies, use the group with the highest limit ratio (max/period)
2164 foreach ( $this->getGroups() as $group ) {
2165 if ( isset( $limits[$group] ) ) {
2166 if ( $userLimit === false
2167 ||
$limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
2169 $userLimit = $limits[$group];
2174 // Set the user limit key
2175 if ( $userLimit !== false ) {
2176 list( $max, $period ) = $userLimit;
2177 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
2178 $keys[$cache->makeKey( 'limiter', $action, 'user', $id )] = $userLimit;
2181 // ip-based limits for all ping-limitable users
2182 if ( isset( $limits['ip-all'] ) ) {
2183 $ip = $this->getRequest()->getIP();
2184 // ignore if user limit is more permissive
2185 if ( $isNewbie ||
$userLimit === false
2186 ||
$limits['ip-all'][0] / $limits['ip-all'][1] > $userLimit[0] / $userLimit[1] ) {
2187 $keys["mediawiki:limiter:$action:ip-all:$ip"] = $limits['ip-all'];
2191 // subnet-based limits for all ping-limitable users
2192 if ( isset( $limits['subnet-all'] ) ) {
2193 $ip = $this->getRequest()->getIP();
2194 $subnet = IP
::getSubnet( $ip );
2195 if ( $subnet !== false ) {
2196 // ignore if user limit is more permissive
2197 if ( $isNewbie ||
$userLimit === false
2198 ||
$limits['ip-all'][0] / $limits['ip-all'][1]
2199 > $userLimit[0] / $userLimit[1] ) {
2200 $keys["mediawiki:limiter:$action:subnet-all:$subnet"] = $limits['subnet-all'];
2206 foreach ( $keys as $key => $limit ) {
2207 list( $max, $period ) = $limit;
2208 $summary = "(limit $max in {$period}s)";
2209 $count = $cache->get( $key );
2212 if ( $count >= $max ) {
2213 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
2214 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
2217 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
2220 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
2221 if ( $incrBy > 0 ) {
2222 $cache->add( $key, 0, intval( $period ) ); // first ping
2225 if ( $incrBy > 0 ) {
2226 $cache->incr( $key, $incrBy );
2234 * Check if user is blocked
2236 * @param bool $bFromSlave Whether to check the replica DB instead of
2237 * the master. Hacked from false due to horrible probs on site.
2238 * @return bool True if blocked, false otherwise
2240 public function isBlocked( $bFromSlave = true ) {
2241 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
2245 * Get the block affecting the user, or null if the user is not blocked
2247 * @param bool $bFromSlave Whether to check the replica DB instead of the master
2248 * @return Block|null
2250 public function getBlock( $bFromSlave = true ) {
2251 $this->getBlockedStatus( $bFromSlave );
2252 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
2256 * Check if user is blocked from editing a particular article
2258 * @param Title $title Title to check
2259 * @param bool $bFromSlave Whether to check the replica DB instead of the master
2262 public function isBlockedFrom( $title, $bFromSlave = false ) {
2263 global $wgBlockAllowsUTEdit;
2265 $blocked = $this->isBlocked( $bFromSlave );
2266 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
2267 // If a user's name is suppressed, they cannot make edits anywhere
2268 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName()
2269 && $title->getNamespace() == NS_USER_TALK
) {
2271 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
2274 Hooks
::run( 'UserIsBlockedFrom', [ $this, $title, &$blocked, &$allowUsertalk ] );
2280 * If user is blocked, return the name of the user who placed the block
2281 * @return string Name of blocker
2283 public function blockedBy() {
2284 $this->getBlockedStatus();
2285 return $this->mBlockedby
;
2289 * If user is blocked, return the specified reason for the block
2290 * @return string Blocking reason
2292 public function blockedFor() {
2293 $this->getBlockedStatus();
2294 return $this->mBlockreason
;
2298 * If user is blocked, return the ID for the block
2299 * @return int Block ID
2301 public function getBlockId() {
2302 $this->getBlockedStatus();
2303 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
2307 * Check if user is blocked on all wikis.
2308 * Do not use for actual edit permission checks!
2309 * This is intended for quick UI checks.
2311 * @param string $ip IP address, uses current client if none given
2312 * @return bool True if blocked, false otherwise
2314 public function isBlockedGlobally( $ip = '' ) {
2315 return $this->getGlobalBlock( $ip ) instanceof Block
;
2319 * Check if user is blocked on all wikis.
2320 * Do not use for actual edit permission checks!
2321 * This is intended for quick UI checks.
2323 * @param string $ip IP address, uses current client if none given
2324 * @return Block|null Block object if blocked, null otherwise
2325 * @throws FatalError
2326 * @throws MWException
2328 public function getGlobalBlock( $ip = '' ) {
2329 if ( $this->mGlobalBlock
!== null ) {
2330 return $this->mGlobalBlock ?
: null;
2332 // User is already an IP?
2333 if ( IP
::isIPAddress( $this->getName() ) ) {
2334 $ip = $this->getName();
2336 $ip = $this->getRequest()->getIP();
2338 // Avoid PHP 7.1 warning of passing $this by reference
2342 Hooks
::run( 'UserIsBlockedGlobally', [ &$user, $ip, &$blocked, &$block ] );
2344 if ( $blocked && $block === null ) {
2345 // back-compat: UserIsBlockedGlobally didn't have $block param first
2346 $block = new Block( [
2348 'systemBlock' => 'global-block'
2352 $this->mGlobalBlock
= $blocked ?
$block : false;
2353 return $this->mGlobalBlock ?
: null;
2357 * Check if user account is locked
2359 * @return bool True if locked, false otherwise
2361 public function isLocked() {
2362 if ( $this->mLocked
!== null ) {
2363 return $this->mLocked
;
2365 // Avoid PHP 7.1 warning of passing $this by reference
2367 $authUser = AuthManager
::callLegacyAuthPlugin( 'getUserInstance', [ &$user ], null );
2368 $this->mLocked
= $authUser && $authUser->isLocked();
2369 Hooks
::run( 'UserIsLocked', [ $this, &$this->mLocked
] );
2370 return $this->mLocked
;
2374 * Check if user account is hidden
2376 * @return bool True if hidden, false otherwise
2378 public function isHidden() {
2379 if ( $this->mHideName
!== null ) {
2380 return $this->mHideName
;
2382 $this->getBlockedStatus();
2383 if ( !$this->mHideName
) {
2384 // Avoid PHP 7.1 warning of passing $this by reference
2386 $authUser = AuthManager
::callLegacyAuthPlugin( 'getUserInstance', [ &$user ], null );
2387 $this->mHideName
= $authUser && $authUser->isHidden();
2388 Hooks
::run( 'UserIsHidden', [ $this, &$this->mHideName
] );
2390 return $this->mHideName
;
2394 * Get the user's ID.
2395 * @return int The user's ID; 0 if the user is anonymous or nonexistent
2397 public function getId() {
2398 if ( $this->mId
=== null && $this->mName
!== null && self
::isIP( $this->mName
) ) {
2399 // Special case, we know the user is anonymous
2401 } elseif ( !$this->isItemLoaded( 'id' ) ) {
2402 // Don't load if this was initialized from an ID
2406 return (int)$this->mId
;
2410 * Set the user and reload all fields according to a given ID
2411 * @param int $v User ID to reload
2413 public function setId( $v ) {
2415 $this->clearInstanceCache( 'id' );
2419 * Get the user name, or the IP of an anonymous user
2420 * @return string User's name or IP address
2422 public function getName() {
2423 if ( $this->isItemLoaded( 'name', 'only' ) ) {
2424 // Special case optimisation
2425 return $this->mName
;
2428 if ( $this->mName
=== false ) {
2430 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
2432 return $this->mName
;
2437 * Set the user name.
2439 * This does not reload fields from the database according to the given
2440 * name. Rather, it is used to create a temporary "nonexistent user" for
2441 * later addition to the database. It can also be used to set the IP
2442 * address for an anonymous user to something other than the current
2445 * @note User::newFromName() has roughly the same function, when the named user
2447 * @param string $str New user name to set
2449 public function setName( $str ) {
2451 $this->mName
= $str;
2455 * Get the user's actor ID.
2457 * @param IDatabase|null $dbw Assign a new actor ID, using this DB handle, if none exists
2458 * @return int The actor's ID, or 0 if no actor ID exists and $dbw was null
2460 public function getActorId( IDatabase
$dbw = null ) {
2461 global $wgActorTableSchemaMigrationStage;
2463 if ( $wgActorTableSchemaMigrationStage <= MIGRATION_OLD
) {
2467 if ( !$this->isItemLoaded( 'actor' ) ) {
2471 // Currently $this->mActorId might be null if $this was loaded from a
2472 // cache entry that was written when $wgActorTableSchemaMigrationStage
2473 // was MIGRATION_OLD. Once that is no longer a possibility (i.e. when
2474 // User::VERSION is incremented after $wgActorTableSchemaMigrationStage
2475 // has been removed), that condition may be removed.
2476 if ( $this->mActorId
=== null ||
!$this->mActorId
&& $dbw ) {
2478 'actor_user' => $this->getId() ?
: null,
2479 'actor_name' => (string)$this->getName(),
2482 if ( $q['actor_user'] === null && self
::isUsableName( $q['actor_name'] ) ) {
2483 throw new CannotCreateActorException(
2484 'Cannot create an actor for a usable name that is not an existing user'
2487 if ( $q['actor_name'] === '' ) {
2488 throw new CannotCreateActorException( 'Cannot create an actor for a user with no name' );
2490 $dbw->insert( 'actor', $q, __METHOD__
, [ 'IGNORE' ] );
2491 if ( $dbw->affectedRows() ) {
2492 $this->mActorId
= (int)$dbw->insertId();
2495 list( , $options ) = DBAccessObjectUtils
::getDBOptions( $this->queryFlagsUsed
);
2496 $this->mActorId
= (int)$dbw->selectField( 'actor', 'actor_id', $q, __METHOD__
, $options );
2497 if ( !$this->mActorId
) {
2498 throw new CannotCreateActorException(
2499 "Cannot create actor ID for user_id={$this->getId()} user_name={$this->getName()}"
2503 $this->invalidateCache();
2505 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $this->queryFlagsUsed
);
2506 $db = wfGetDB( $index );
2507 $this->mActorId
= (int)$db->selectField( 'actor', 'actor_id', $q, __METHOD__
, $options );
2509 $this->setItemLoaded( 'actor' );
2512 return (int)$this->mActorId
;
2516 * Get the user's name escaped by underscores.
2517 * @return string Username escaped by underscores.
2519 public function getTitleKey() {
2520 return str_replace( ' ', '_', $this->getName() );
2524 * Check if the user has new messages.
2525 * @return bool True if the user has new messages
2527 public function getNewtalk() {
2530 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2531 if ( $this->mNewtalk
=== -1 ) {
2532 $this->mNewtalk
= false; # reset talk page status
2534 // Check memcached separately for anons, who have no
2535 // entire User object stored in there.
2536 if ( !$this->mId
) {
2537 global $wgDisableAnonTalk;
2538 if ( $wgDisableAnonTalk ) {
2539 // Anon newtalk disabled by configuration.
2540 $this->mNewtalk
= false;
2542 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
2545 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2549 return (bool)$this->mNewtalk
;
2553 * Return the data needed to construct links for new talk page message
2554 * alerts. If there are new messages, this will return an associative array
2555 * with the following data:
2556 * wiki: The database name of the wiki
2557 * link: Root-relative link to the user's talk page
2558 * rev: The last talk page revision that the user has seen or null. This
2559 * is useful for building diff links.
2560 * If there are no new messages, it returns an empty array.
2561 * @note This function was designed to accomodate multiple talk pages, but
2562 * currently only returns a single link and revision.
2565 public function getNewMessageLinks() {
2566 // Avoid PHP 7.1 warning of passing $this by reference
2569 if ( !Hooks
::run( 'UserRetrieveNewTalks', [ &$user, &$talks ] ) ) {
2571 } elseif ( !$this->getNewtalk() ) {
2574 $utp = $this->getTalkPage();
2575 $dbr = wfGetDB( DB_REPLICA
);
2576 // Get the "last viewed rev" timestamp from the oldest message notification
2577 $timestamp = $dbr->selectField( 'user_newtalk',
2578 'MIN(user_last_timestamp)',
2579 $this->isAnon() ?
[ 'user_ip' => $this->getName() ] : [ 'user_id' => $this->getId() ],
2581 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2582 return [ [ 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ] ];
2586 * Get the revision ID for the last talk page revision viewed by the talk
2588 * @return int|null Revision ID or null
2590 public function getNewMessageRevisionId() {
2591 $newMessageRevisionId = null;
2592 $newMessageLinks = $this->getNewMessageLinks();
2593 if ( $newMessageLinks ) {
2594 // Note: getNewMessageLinks() never returns more than a single link
2595 // and it is always for the same wiki, but we double-check here in
2596 // case that changes some time in the future.
2597 if ( count( $newMessageLinks ) === 1
2598 && $newMessageLinks[0]['wiki'] === wfWikiID()
2599 && $newMessageLinks[0]['rev']
2601 /** @var Revision $newMessageRevision */
2602 $newMessageRevision = $newMessageLinks[0]['rev'];
2603 $newMessageRevisionId = $newMessageRevision->getId();
2606 return $newMessageRevisionId;
2610 * Internal uncached check for new messages
2613 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2614 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2615 * @return bool True if the user has new messages
2617 protected function checkNewtalk( $field, $id ) {
2618 $dbr = wfGetDB( DB_REPLICA
);
2620 $ok = $dbr->selectField( 'user_newtalk', $field, [ $field => $id ], __METHOD__
);
2622 return $ok !== false;
2626 * Add or update the new messages flag
2627 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2628 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2629 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2630 * @return bool True if successful, false otherwise
2632 protected function updateNewtalk( $field, $id, $curRev = null ) {
2633 // Get timestamp of the talk page revision prior to the current one
2634 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2635 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2636 // Mark the user as having new messages since this revision
2637 $dbw = wfGetDB( DB_MASTER
);
2638 $dbw->insert( 'user_newtalk',
2639 [ $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ],
2642 if ( $dbw->affectedRows() ) {
2643 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2646 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2652 * Clear the new messages flag for the given user
2653 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2654 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2655 * @return bool True if successful, false otherwise
2657 protected function deleteNewtalk( $field, $id ) {
2658 $dbw = wfGetDB( DB_MASTER
);
2659 $dbw->delete( 'user_newtalk',
2662 if ( $dbw->affectedRows() ) {
2663 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2666 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2672 * Update the 'You have new messages!' status.
2673 * @param bool $val Whether the user has new messages
2674 * @param Revision $curRev New, as yet unseen revision of the user talk
2675 * page. Ignored if null or !$val.
2677 public function setNewtalk( $val, $curRev = null ) {
2678 if ( wfReadOnly() ) {
2683 $this->mNewtalk
= $val;
2685 if ( $this->isAnon() ) {
2687 $id = $this->getName();
2690 $id = $this->getId();
2694 $changed = $this->updateNewtalk( $field, $id, $curRev );
2696 $changed = $this->deleteNewtalk( $field, $id );
2700 $this->invalidateCache();
2705 * Generate a current or new-future timestamp to be stored in the
2706 * user_touched field when we update things.
2707 * @return string Timestamp in TS_MW format
2709 private function newTouchedTimestamp() {
2710 global $wgClockSkewFudge;
2712 $time = wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2713 if ( $this->mTouched
&& $time <= $this->mTouched
) {
2714 $time = wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $this->mTouched
) +
1 );
2721 * Clear user data from memcached
2723 * Use after applying updates to the database; caller's
2724 * responsibility to update user_touched if appropriate.
2726 * Called implicitly from invalidateCache() and saveSettings().
2728 * @param string $mode Use 'refresh' to clear now; otherwise before DB commit
2730 public function clearSharedCache( $mode = 'changed' ) {
2731 if ( !$this->getId() ) {
2735 $cache = ObjectCache
::getMainWANInstance();
2736 $key = $this->getCacheKey( $cache );
2737 if ( $mode === 'refresh' ) {
2738 $cache->delete( $key, 1 );
2740 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
2741 if ( $lb->hasOrMadeRecentMasterChanges() ) {
2742 $lb->getConnection( DB_MASTER
)->onTransactionPreCommitOrIdle(
2743 function () use ( $cache, $key ) {
2744 $cache->delete( $key );
2749 $cache->delete( $key );
2755 * Immediately touch the user data cache for this account
2757 * Calls touch() and removes account data from memcached
2759 public function invalidateCache() {
2761 $this->clearSharedCache();
2765 * Update the "touched" timestamp for the user
2767 * This is useful on various login/logout events when making sure that
2768 * a browser or proxy that has multiple tenants does not suffer cache
2769 * pollution where the new user sees the old users content. The value
2770 * of getTouched() is checked when determining 304 vs 200 responses.
2771 * Unlike invalidateCache(), this preserves the User object cache and
2772 * avoids database writes.
2776 public function touch() {
2777 $id = $this->getId();
2779 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
2780 $key = $cache->makeKey( 'user-quicktouched', 'id', $id );
2781 $cache->touchCheckKey( $key );
2782 $this->mQuickTouched
= null;
2787 * Validate the cache for this account.
2788 * @param string $timestamp A timestamp in TS_MW format
2791 public function validateCache( $timestamp ) {
2792 return ( $timestamp >= $this->getTouched() );
2796 * Get the user touched timestamp
2798 * Use this value only to validate caches via inequalities
2799 * such as in the case of HTTP If-Modified-Since response logic
2801 * @return string TS_MW Timestamp
2803 public function getTouched() {
2807 if ( $this->mQuickTouched
=== null ) {
2808 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
2809 $key = $cache->makeKey( 'user-quicktouched', 'id', $this->mId
);
2811 $this->mQuickTouched
= wfTimestamp( TS_MW
, $cache->getCheckKeyTime( $key ) );
2814 return max( $this->mTouched
, $this->mQuickTouched
);
2817 return $this->mTouched
;
2821 * Get the user_touched timestamp field (time of last DB updates)
2822 * @return string TS_MW Timestamp
2825 public function getDBTouched() {
2828 return $this->mTouched
;
2832 * Set the password and reset the random token.
2833 * Calls through to authentication plugin if necessary;
2834 * will have no effect if the auth plugin refuses to
2835 * pass the change through or if the legal password
2838 * As a special case, setting the password to null
2839 * wipes it, so the account cannot be logged in until
2840 * a new password is set, for instance via e-mail.
2842 * @deprecated since 1.27, use AuthManager instead
2843 * @param string $str New password to set
2844 * @throws PasswordError On failure
2847 public function setPassword( $str ) {
2848 return $this->setPasswordInternal( $str );
2852 * Set the password and reset the random token unconditionally.
2854 * @deprecated since 1.27, use AuthManager instead
2855 * @param string|null $str New password to set or null to set an invalid
2856 * password hash meaning that the user will not be able to log in
2857 * through the web interface.
2859 public function setInternalPassword( $str ) {
2860 $this->setPasswordInternal( $str );
2864 * Actually set the password and such
2865 * @since 1.27 cannot set a password for a user not in the database
2866 * @param string|null $str New password to set or null to set an invalid
2867 * password hash meaning that the user will not be able to log in
2868 * through the web interface.
2869 * @return bool Success
2871 private function setPasswordInternal( $str ) {
2872 $manager = AuthManager
::singleton();
2874 // If the user doesn't exist yet, fail
2875 if ( !$manager->userExists( $this->getName() ) ) {
2876 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2879 $status = $this->changeAuthenticationData( [
2880 'username' => $this->getName(),
2884 if ( !$status->isGood() ) {
2885 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
2886 ->info( __METHOD__
. ': Password change rejected: '
2887 . $status->getWikiText( null, null, 'en' ) );
2891 $this->setOption( 'watchlisttoken', false );
2892 SessionManager
::singleton()->invalidateSessionsForUser( $this );
2898 * Changes credentials of the user.
2900 * This is a convenience wrapper around AuthManager::changeAuthenticationData.
2901 * Note that this can return a status that isOK() but not isGood() on certain types of failures,
2902 * e.g. when no provider handled the change.
2904 * @param array $data A set of authentication data in fieldname => value format. This is the
2905 * same data you would pass the changeauthenticationdata API - 'username', 'password' etc.
2909 public function changeAuthenticationData( array $data ) {
2910 $manager = AuthManager
::singleton();
2911 $reqs = $manager->getAuthenticationRequests( AuthManager
::ACTION_CHANGE
, $this );
2912 $reqs = AuthenticationRequest
::loadRequestsFromSubmission( $reqs, $data );
2914 $status = Status
::newGood( 'ignored' );
2915 foreach ( $reqs as $req ) {
2916 $status->merge( $manager->allowsAuthenticationDataChange( $req ), true );
2918 if ( $status->getValue() === 'ignored' ) {
2919 $status->warning( 'authenticationdatachange-ignored' );
2922 if ( $status->isGood() ) {
2923 foreach ( $reqs as $req ) {
2924 $manager->changeAuthenticationData( $req );
2931 * Get the user's current token.
2932 * @param bool $forceCreation Force the generation of a new token if the
2933 * user doesn't have one (default=true for backwards compatibility).
2934 * @return string|null Token
2936 public function getToken( $forceCreation = true ) {
2937 global $wgAuthenticationTokenVersion;
2940 if ( !$this->mToken
&& $forceCreation ) {
2944 if ( !$this->mToken
) {
2945 // The user doesn't have a token, return null to indicate that.
2947 } elseif ( $this->mToken
=== self
::INVALID_TOKEN
) {
2948 // We return a random value here so existing token checks are very
2950 return MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2951 } elseif ( $wgAuthenticationTokenVersion === null ) {
2952 // $wgAuthenticationTokenVersion not in use, so return the raw secret
2953 return $this->mToken
;
2955 // $wgAuthenticationTokenVersion in use, so hmac it.
2956 $ret = MWCryptHash
::hmac( $wgAuthenticationTokenVersion, $this->mToken
, false );
2958 // The raw hash can be overly long. Shorten it up.
2959 $len = max( 32, self
::TOKEN_LENGTH
);
2960 if ( strlen( $ret ) < $len ) {
2961 // Should never happen, even md5 is 128 bits
2962 throw new \
UnexpectedValueException( 'Hmac returned less than 128 bits' );
2964 return substr( $ret, -$len );
2969 * Set the random token (used for persistent authentication)
2970 * Called from loadDefaults() among other places.
2972 * @param string|bool $token If specified, set the token to this value
2974 public function setToken( $token = false ) {
2976 if ( $this->mToken
=== self
::INVALID_TOKEN
) {
2977 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
2978 ->debug( __METHOD__
. ": Ignoring attempt to set token for system user \"$this\"" );
2979 } elseif ( !$token ) {
2980 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2982 $this->mToken
= $token;
2987 * Set the password for a password reminder or new account email
2989 * @deprecated Removed in 1.27. Use PasswordReset instead.
2990 * @param string $str New password to set or null to set an invalid
2991 * password hash meaning that the user will not be able to use it
2992 * @param bool $throttle If true, reset the throttle timestamp to the present
2994 public function setNewpassword( $str, $throttle = true ) {
2995 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2999 * Get the user's e-mail address
3000 * @return string User's email address
3002 public function getEmail() {
3004 Hooks
::run( 'UserGetEmail', [ $this, &$this->mEmail
] );
3005 return $this->mEmail
;
3009 * Get the timestamp of the user's e-mail authentication
3010 * @return string TS_MW timestamp
3012 public function getEmailAuthenticationTimestamp() {
3014 Hooks
::run( 'UserGetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
3015 return $this->mEmailAuthenticated
;
3019 * Set the user's e-mail address
3020 * @param string $str New e-mail address
3022 public function setEmail( $str ) {
3024 if ( $str == $this->mEmail
) {
3027 $this->invalidateEmail();
3028 $this->mEmail
= $str;
3029 Hooks
::run( 'UserSetEmail', [ $this, &$this->mEmail
] );
3033 * Set the user's e-mail address and a confirmation mail if needed.
3036 * @param string $str New e-mail address
3039 public function setEmailWithConfirmation( $str ) {
3040 global $wgEnableEmail, $wgEmailAuthentication;
3042 if ( !$wgEnableEmail ) {
3043 return Status
::newFatal( 'emaildisabled' );
3046 $oldaddr = $this->getEmail();
3047 if ( $str === $oldaddr ) {
3048 return Status
::newGood( true );
3051 $type = $oldaddr != '' ?
'changed' : 'set';
3052 $notificationResult = null;
3054 if ( $wgEmailAuthentication ) {
3055 // Send the user an email notifying the user of the change in registered
3056 // email address on their previous email address
3057 if ( $type == 'changed' ) {
3058 $change = $str != '' ?
'changed' : 'removed';
3059 $notificationResult = $this->sendMail(
3060 wfMessage( 'notificationemail_subject_' . $change )->text(),
3061 wfMessage( 'notificationemail_body_' . $change,
3062 $this->getRequest()->getIP(),
3069 $this->setEmail( $str );
3071 if ( $str !== '' && $wgEmailAuthentication ) {
3072 // Send a confirmation request to the new address if needed
3073 $result = $this->sendConfirmationMail( $type );
3075 if ( $notificationResult !== null ) {
3076 $result->merge( $notificationResult );
3079 if ( $result->isGood() ) {
3080 // Say to the caller that a confirmation and notification mail has been sent
3081 $result->value
= 'eauth';
3084 $result = Status
::newGood( true );
3091 * Get the user's real name
3092 * @return string User's real name
3094 public function getRealName() {
3095 if ( !$this->isItemLoaded( 'realname' ) ) {
3099 return $this->mRealName
;
3103 * Set the user's real name
3104 * @param string $str New real name
3106 public function setRealName( $str ) {
3108 $this->mRealName
= $str;
3112 * Get the user's current setting for a given option.
3114 * @param string $oname The option to check
3115 * @param string|array $defaultOverride A default value returned if the option does not exist
3116 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
3117 * @return string|array|int|null User's current value for the option
3118 * @see getBoolOption()
3119 * @see getIntOption()
3121 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
3122 global $wgHiddenPrefs;
3123 $this->loadOptions();
3125 # We want 'disabled' preferences to always behave as the default value for
3126 # users, even if they have set the option explicitly in their settings (ie they
3127 # set it, and then it was disabled removing their ability to change it). But
3128 # we don't want to erase the preferences in the database in case the preference
3129 # is re-enabled again. So don't touch $mOptions, just override the returned value
3130 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
3131 return self
::getDefaultOption( $oname );
3134 if ( array_key_exists( $oname, $this->mOptions
) ) {
3135 return $this->mOptions
[$oname];
3137 return $defaultOverride;
3142 * Get all user's options
3144 * @param int $flags Bitwise combination of:
3145 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
3146 * to the default value. (Since 1.25)
3149 public function getOptions( $flags = 0 ) {
3150 global $wgHiddenPrefs;
3151 $this->loadOptions();
3152 $options = $this->mOptions
;
3154 # We want 'disabled' preferences to always behave as the default value for
3155 # users, even if they have set the option explicitly in their settings (ie they
3156 # set it, and then it was disabled removing their ability to change it). But
3157 # we don't want to erase the preferences in the database in case the preference
3158 # is re-enabled again. So don't touch $mOptions, just override the returned value
3159 foreach ( $wgHiddenPrefs as $pref ) {
3160 $default = self
::getDefaultOption( $pref );
3161 if ( $default !== null ) {
3162 $options[$pref] = $default;
3166 if ( $flags & self
::GETOPTIONS_EXCLUDE_DEFAULTS
) {
3167 $options = array_diff_assoc( $options, self
::getDefaultOptions() );
3174 * Get the user's current setting for a given option, as a boolean value.
3176 * @param string $oname The option to check
3177 * @return bool User's current value for the option
3180 public function getBoolOption( $oname ) {
3181 return (bool)$this->getOption( $oname );
3185 * Get the user's current setting for a given option, as an integer value.
3187 * @param string $oname The option to check
3188 * @param int $defaultOverride A default value returned if the option does not exist
3189 * @return int User's current value for the option
3192 public function getIntOption( $oname, $defaultOverride = 0 ) {
3193 $val = $this->getOption( $oname );
3195 $val = $defaultOverride;
3197 return intval( $val );
3201 * Set the given option for a user.
3203 * You need to call saveSettings() to actually write to the database.
3205 * @param string $oname The option to set
3206 * @param mixed $val New value to set
3208 public function setOption( $oname, $val ) {
3209 $this->loadOptions();
3211 // Explicitly NULL values should refer to defaults
3212 if ( is_null( $val ) ) {
3213 $val = self
::getDefaultOption( $oname );
3216 $this->mOptions
[$oname] = $val;
3220 * Get a token stored in the preferences (like the watchlist one),
3221 * resetting it if it's empty (and saving changes).
3223 * @param string $oname The option name to retrieve the token from
3224 * @return string|bool User's current value for the option, or false if this option is disabled.
3225 * @see resetTokenFromOption()
3227 * @deprecated since 1.26 Applications should use the OAuth extension
3229 public function getTokenFromOption( $oname ) {
3230 global $wgHiddenPrefs;
3232 $id = $this->getId();
3233 if ( !$id ||
in_array( $oname, $wgHiddenPrefs ) ) {
3237 $token = $this->getOption( $oname );
3239 // Default to a value based on the user token to avoid space
3240 // wasted on storing tokens for all users. When this option
3241 // is set manually by the user, only then is it stored.
3242 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
3249 * Reset a token stored in the preferences (like the watchlist one).
3250 * *Does not* save user's preferences (similarly to setOption()).
3252 * @param string $oname The option name to reset the token in
3253 * @return string|bool New token value, or false if this option is disabled.
3254 * @see getTokenFromOption()
3257 public function resetTokenFromOption( $oname ) {
3258 global $wgHiddenPrefs;
3259 if ( in_array( $oname, $wgHiddenPrefs ) ) {
3263 $token = MWCryptRand
::generateHex( 40 );
3264 $this->setOption( $oname, $token );
3269 * Return a list of the types of user options currently returned by
3270 * User::getOptionKinds().
3272 * Currently, the option kinds are:
3273 * - 'registered' - preferences which are registered in core MediaWiki or
3274 * by extensions using the UserGetDefaultOptions hook.
3275 * - 'registered-multiselect' - as above, using the 'multiselect' type.
3276 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
3277 * - 'userjs' - preferences with names starting with 'userjs-', intended to
3278 * be used by user scripts.
3279 * - 'special' - "preferences" that are not accessible via User::getOptions
3280 * or User::setOptions.
3281 * - 'unused' - preferences about which MediaWiki doesn't know anything.
3282 * These are usually legacy options, removed in newer versions.
3284 * The API (and possibly others) use this function to determine the possible
3285 * option types for validation purposes, so make sure to update this when a
3286 * new option kind is added.
3288 * @see User::getOptionKinds
3289 * @return array Option kinds
3291 public static function listOptionKinds() {
3294 'registered-multiselect',
3295 'registered-checkmatrix',
3303 * Return an associative array mapping preferences keys to the kind of a preference they're
3304 * used for. Different kinds are handled differently when setting or reading preferences.
3306 * See User::listOptionKinds for the list of valid option types that can be provided.
3308 * @see User::listOptionKinds
3309 * @param IContextSource $context
3310 * @param array $options Assoc. array with options keys to check as keys.
3311 * Defaults to $this->mOptions.
3312 * @return array The key => kind mapping data
3314 public function getOptionKinds( IContextSource
$context, $options = null ) {
3315 $this->loadOptions();
3316 if ( $options === null ) {
3317 $options = $this->mOptions
;
3320 $preferencesFactory = MediaWikiServices
::getInstance()->getPreferencesFactory();
3321 $prefs = $preferencesFactory->getFormDescriptor( $this, $context );
3324 // Pull out the "special" options, so they don't get converted as
3325 // multiselect or checkmatrix.
3326 $specialOptions = array_fill_keys( $preferencesFactory->getSaveBlacklist(), true );
3327 foreach ( $specialOptions as $name => $value ) {
3328 unset( $prefs[$name] );
3331 // Multiselect and checkmatrix options are stored in the database with
3332 // one key per option, each having a boolean value. Extract those keys.
3333 $multiselectOptions = [];
3334 foreach ( $prefs as $name => $info ) {
3335 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
3336 ( isset( $info['class'] ) && $info['class'] == HTMLMultiSelectField
::class ) ) {
3337 $opts = HTMLFormField
::flattenOptions( $info['options'] );
3338 $prefix = $info['prefix'] ??
$name;
3340 foreach ( $opts as $value ) {
3341 $multiselectOptions["$prefix$value"] = true;
3344 unset( $prefs[$name] );
3347 $checkmatrixOptions = [];
3348 foreach ( $prefs as $name => $info ) {
3349 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
3350 ( isset( $info['class'] ) && $info['class'] == HTMLCheckMatrix
::class ) ) {
3351 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
3352 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
3353 $prefix = $info['prefix'] ??
$name;
3355 foreach ( $columns as $column ) {
3356 foreach ( $rows as $row ) {
3357 $checkmatrixOptions["$prefix$column-$row"] = true;
3361 unset( $prefs[$name] );
3365 // $value is ignored
3366 foreach ( $options as $key => $value ) {
3367 if ( isset( $prefs[$key] ) ) {
3368 $mapping[$key] = 'registered';
3369 } elseif ( isset( $multiselectOptions[$key] ) ) {
3370 $mapping[$key] = 'registered-multiselect';
3371 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
3372 $mapping[$key] = 'registered-checkmatrix';
3373 } elseif ( isset( $specialOptions[$key] ) ) {
3374 $mapping[$key] = 'special';
3375 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
3376 $mapping[$key] = 'userjs';
3378 $mapping[$key] = 'unused';
3386 * Reset certain (or all) options to the site defaults
3388 * The optional parameter determines which kinds of preferences will be reset.
3389 * Supported values are everything that can be reported by getOptionKinds()
3390 * and 'all', which forces a reset of *all* preferences and overrides everything else.
3392 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
3393 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
3394 * for backwards-compatibility.
3395 * @param IContextSource|null $context Context source used when $resetKinds
3396 * does not contain 'all', passed to getOptionKinds().
3397 * Defaults to RequestContext::getMain() when null.
3399 public function resetOptions(
3400 $resetKinds = [ 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ],
3401 IContextSource
$context = null
3404 $defaultOptions = self
::getDefaultOptions();
3406 if ( !is_array( $resetKinds ) ) {
3407 $resetKinds = [ $resetKinds ];
3410 if ( in_array( 'all', $resetKinds ) ) {
3411 $newOptions = $defaultOptions;
3413 if ( $context === null ) {
3414 $context = RequestContext
::getMain();
3417 $optionKinds = $this->getOptionKinds( $context );
3418 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
3421 // Use default values for the options that should be deleted, and
3422 // copy old values for the ones that shouldn't.
3423 foreach ( $this->mOptions
as $key => $value ) {
3424 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
3425 if ( array_key_exists( $key, $defaultOptions ) ) {
3426 $newOptions[$key] = $defaultOptions[$key];
3429 $newOptions[$key] = $value;
3434 Hooks
::run( 'UserResetAllOptions', [ $this, &$newOptions, $this->mOptions
, $resetKinds ] );
3436 $this->mOptions
= $newOptions;
3437 $this->mOptionsLoaded
= true;
3441 * Get the user's preferred date format.
3442 * @return string User's preferred date format
3444 public function getDatePreference() {
3445 // Important migration for old data rows
3446 if ( is_null( $this->mDatePreference
) ) {
3448 $value = $this->getOption( 'date' );
3449 $map = $wgLang->getDatePreferenceMigrationMap();
3450 if ( isset( $map[$value] ) ) {
3451 $value = $map[$value];
3453 $this->mDatePreference
= $value;
3455 return $this->mDatePreference
;
3459 * Determine based on the wiki configuration and the user's options,
3460 * whether this user must be over HTTPS no matter what.
3464 public function requiresHTTPS() {
3465 global $wgSecureLogin;
3466 if ( !$wgSecureLogin ) {
3469 $https = $this->getBoolOption( 'prefershttps' );
3470 Hooks
::run( 'UserRequiresHTTPS', [ $this, &$https ] );
3472 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
3479 * Get the user preferred stub threshold
3483 public function getStubThreshold() {
3484 global $wgMaxArticleSize; # Maximum article size, in Kb
3485 $threshold = $this->getIntOption( 'stubthreshold' );
3486 if ( $threshold > $wgMaxArticleSize * 1024 ) {
3487 // If they have set an impossible value, disable the preference
3488 // so we can use the parser cache again.
3495 * Get the permissions this user has.
3496 * @return string[] permission names
3498 public function getRights() {
3499 if ( is_null( $this->mRights
) ) {
3500 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
3501 Hooks
::run( 'UserGetRights', [ $this, &$this->mRights
] );
3503 // Deny any rights denied by the user's session, unless this
3504 // endpoint has no sessions.
3505 if ( !defined( 'MW_NO_SESSION' ) ) {
3506 $allowedRights = $this->getRequest()->getSession()->getAllowedUserRights();
3507 if ( $allowedRights !== null ) {
3508 $this->mRights
= array_intersect( $this->mRights
, $allowedRights );
3512 // Force reindexation of rights when a hook has unset one of them
3513 $this->mRights
= array_values( array_unique( $this->mRights
) );
3515 // If block disables login, we should also remove any
3516 // extra rights blocked users might have, in case the
3517 // blocked user has a pre-existing session (T129738).
3518 // This is checked here for cases where people only call
3519 // $user->isAllowed(). It is also checked in Title::checkUserBlock()
3520 // to give a better error message in the common case.
3521 $config = RequestContext
::getMain()->getConfig();
3523 $this->isLoggedIn() &&
3524 $config->get( 'BlockDisablesLogin' ) &&
3528 $this->mRights
= array_intersect( $this->mRights
, $anon->getRights() );
3531 return $this->mRights
;
3535 * Get the list of explicit group memberships this user has.
3536 * The implicit * and user groups are not included.
3537 * @return array Array of String internal group names
3539 public function getGroups() {
3541 $this->loadGroups();
3542 return array_keys( $this->mGroupMemberships
);
3546 * Get the list of explicit group memberships this user has, stored as
3547 * UserGroupMembership objects. Implicit groups are not included.
3549 * @return UserGroupMembership[] Associative array of (group name => UserGroupMembership object)
3552 public function getGroupMemberships() {
3554 $this->loadGroups();
3555 return $this->mGroupMemberships
;
3559 * Get the list of implicit group memberships this user has.
3560 * This includes all explicit groups, plus 'user' if logged in,
3561 * '*' for all accounts, and autopromoted groups
3562 * @param bool $recache Whether to avoid the cache
3563 * @return array Array of String internal group names
3565 public function getEffectiveGroups( $recache = false ) {
3566 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
3567 $this->mEffectiveGroups
= array_unique( array_merge(
3568 $this->getGroups(), // explicit groups
3569 $this->getAutomaticGroups( $recache ) // implicit groups
3571 // Avoid PHP 7.1 warning of passing $this by reference
3573 // Hook for additional groups
3574 Hooks
::run( 'UserEffectiveGroups', [ &$user, &$this->mEffectiveGroups
] );
3575 // Force reindexation of groups when a hook has unset one of them
3576 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
3578 return $this->mEffectiveGroups
;
3582 * Get the list of implicit group memberships this user has.
3583 * This includes 'user' if logged in, '*' for all accounts,
3584 * and autopromoted groups
3585 * @param bool $recache Whether to avoid the cache
3586 * @return array Array of String internal group names
3588 public function getAutomaticGroups( $recache = false ) {
3589 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
3590 $this->mImplicitGroups
= [ '*' ];
3591 if ( $this->getId() ) {
3592 $this->mImplicitGroups
[] = 'user';
3594 $this->mImplicitGroups
= array_unique( array_merge(
3595 $this->mImplicitGroups
,
3596 Autopromote
::getAutopromoteGroups( $this )
3600 // Assure data consistency with rights/groups,
3601 // as getEffectiveGroups() depends on this function
3602 $this->mEffectiveGroups
= null;
3605 return $this->mImplicitGroups
;
3609 * Returns the groups the user has belonged to.
3611 * The user may still belong to the returned groups. Compare with getGroups().
3613 * The function will not return groups the user had belonged to before MW 1.17
3615 * @return array Names of the groups the user has belonged to.
3617 public function getFormerGroups() {
3620 if ( is_null( $this->mFormerGroups
) ) {
3621 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3622 ?
wfGetDB( DB_MASTER
)
3623 : wfGetDB( DB_REPLICA
);
3624 $res = $db->select( 'user_former_groups',
3626 [ 'ufg_user' => $this->mId
],
3628 $this->mFormerGroups
= [];
3629 foreach ( $res as $row ) {
3630 $this->mFormerGroups
[] = $row->ufg_group
;
3634 return $this->mFormerGroups
;
3638 * Get the user's edit count.
3639 * @return int|null Null for anonymous users
3641 public function getEditCount() {
3642 if ( !$this->getId() ) {
3646 if ( $this->mEditCount
=== null ) {
3647 /* Populate the count, if it has not been populated yet */
3648 $dbr = wfGetDB( DB_REPLICA
);
3649 // check if the user_editcount field has been initialized
3650 $count = $dbr->selectField(
3651 'user', 'user_editcount',
3652 [ 'user_id' => $this->mId
],
3656 if ( $count === null ) {
3657 // it has not been initialized. do so.
3658 $count = $this->initEditCount();
3660 $this->mEditCount
= $count;
3662 return (int)$this->mEditCount
;
3666 * Add the user to the given group. This takes immediate effect.
3667 * If the user is already in the group, the expiry time will be updated to the new
3668 * expiry time. (If $expiry is omitted or null, the membership will be altered to
3671 * @param string $group Name of the group to add
3672 * @param string $expiry Optional expiry timestamp in any format acceptable to
3673 * wfTimestamp(), or null if the group assignment should not expire
3676 public function addGroup( $group, $expiry = null ) {
3678 $this->loadGroups();
3681 $expiry = wfTimestamp( TS_MW
, $expiry );
3684 if ( !Hooks
::run( 'UserAddGroup', [ $this, &$group, &$expiry ] ) ) {
3688 // create the new UserGroupMembership and put it in the DB
3689 $ugm = new UserGroupMembership( $this->mId
, $group, $expiry );
3690 if ( !$ugm->insert( true ) ) {
3694 $this->mGroupMemberships
[$group] = $ugm;
3696 // Refresh the groups caches, and clear the rights cache so it will be
3697 // refreshed on the next call to $this->getRights().
3698 $this->getEffectiveGroups( true );
3699 $this->mRights
= null;
3701 $this->invalidateCache();
3707 * Remove the user from the given group.
3708 * This takes immediate effect.
3709 * @param string $group Name of the group to remove
3712 public function removeGroup( $group ) {
3715 if ( !Hooks
::run( 'UserRemoveGroup', [ $this, &$group ] ) ) {
3719 $ugm = UserGroupMembership
::getMembership( $this->mId
, $group );
3720 // delete the membership entry
3721 if ( !$ugm ||
!$ugm->delete() ) {
3725 $this->loadGroups();
3726 unset( $this->mGroupMemberships
[$group] );
3728 // Refresh the groups caches, and clear the rights cache so it will be
3729 // refreshed on the next call to $this->getRights().
3730 $this->getEffectiveGroups( true );
3731 $this->mRights
= null;
3733 $this->invalidateCache();
3739 * Get whether the user is logged in
3742 public function isLoggedIn() {
3743 return $this->getId() != 0;
3747 * Get whether the user is anonymous
3750 public function isAnon() {
3751 return !$this->isLoggedIn();
3755 * @return bool Whether this user is flagged as being a bot role account
3758 public function isBot() {
3759 if ( in_array( 'bot', $this->getGroups() ) && $this->isAllowed( 'bot' ) ) {
3764 Hooks
::run( "UserIsBot", [ $this, &$isBot ] );
3770 * Check if user is allowed to access a feature / make an action
3772 * @param string $permissions,... Permissions to test
3773 * @return bool True if user is allowed to perform *any* of the given actions
3775 public function isAllowedAny() {
3776 $permissions = func_get_args();
3777 foreach ( $permissions as $permission ) {
3778 if ( $this->isAllowed( $permission ) ) {
3787 * @param string $permissions,... Permissions to test
3788 * @return bool True if the user is allowed to perform *all* of the given actions
3790 public function isAllowedAll() {
3791 $permissions = func_get_args();
3792 foreach ( $permissions as $permission ) {
3793 if ( !$this->isAllowed( $permission ) ) {
3801 * Internal mechanics of testing a permission
3802 * @param string $action
3805 public function isAllowed( $action = '' ) {
3806 if ( $action === '' ) {
3807 return true; // In the spirit of DWIM
3809 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3810 // by misconfiguration: 0 == 'foo'
3811 return in_array( $action, $this->getRights(), true );
3815 * Check whether to enable recent changes patrol features for this user
3816 * @return bool True or false
3818 public function useRCPatrol() {
3819 global $wgUseRCPatrol;
3820 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3824 * Check whether to enable new pages patrol features for this user
3825 * @return bool True or false
3827 public function useNPPatrol() {
3828 global $wgUseRCPatrol, $wgUseNPPatrol;
3830 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3831 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3836 * Check whether to enable new files patrol features for this user
3837 * @return bool True or false
3839 public function useFilePatrol() {
3840 global $wgUseRCPatrol, $wgUseFilePatrol;
3842 ( $wgUseRCPatrol ||
$wgUseFilePatrol )
3843 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3848 * Get the WebRequest object to use with this object
3850 * @return WebRequest
3852 public function getRequest() {
3853 if ( $this->mRequest
) {
3854 return $this->mRequest
;
3862 * Check the watched status of an article.
3863 * @since 1.22 $checkRights parameter added
3864 * @param Title $title Title of the article to look at
3865 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3866 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3869 public function isWatched( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3870 if ( $title->isWatchable() && ( !$checkRights ||
$this->isAllowed( 'viewmywatchlist' ) ) ) {
3871 return MediaWikiServices
::getInstance()->getWatchedItemStore()->isWatched( $this, $title );
3878 * @since 1.22 $checkRights parameter added
3879 * @param Title $title Title of the article to look at
3880 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3881 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3883 public function addWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3884 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3885 MediaWikiServices
::getInstance()->getWatchedItemStore()->addWatchBatchForUser(
3887 [ $title->getSubjectPage(), $title->getTalkPage() ]
3890 $this->invalidateCache();
3894 * Stop watching an article.
3895 * @since 1.22 $checkRights parameter added
3896 * @param Title $title Title of the article to look at
3897 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3898 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3900 public function removeWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3901 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3902 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
3903 $store->removeWatch( $this, $title->getSubjectPage() );
3904 $store->removeWatch( $this, $title->getTalkPage() );
3906 $this->invalidateCache();
3910 * Clear the user's notification timestamp for the given title.
3911 * If e-notif e-mails are on, they will receive notification mails on
3912 * the next change of the page if it's watched etc.
3913 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3914 * @param Title &$title Title of the article to look at
3915 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3917 public function clearNotification( &$title, $oldid = 0 ) {
3918 global $wgUseEnotif, $wgShowUpdatedMarker;
3920 // Do nothing if the database is locked to writes
3921 if ( wfReadOnly() ) {
3925 // Do nothing if not allowed to edit the watchlist
3926 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3930 // If we're working on user's talk page, we should update the talk page message indicator
3931 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3932 // Avoid PHP 7.1 warning of passing $this by reference
3934 if ( !Hooks
::run( 'UserClearNewTalkNotification', [ &$user, $oldid ] ) ) {
3938 // Try to update the DB post-send and only if needed...
3939 DeferredUpdates
::addCallableUpdate( function () use ( $title, $oldid ) {
3940 if ( !$this->getNewtalk() ) {
3941 return; // no notifications to clear
3944 // Delete the last notifications (they stack up)
3945 $this->setNewtalk( false );
3947 // If there is a new, unseen, revision, use its timestamp
3949 ?
$title->getNextRevisionID( $oldid, Title
::GAID_FOR_UPDATE
)
3952 $this->setNewtalk( true, Revision
::newFromId( $nextid ) );
3957 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3961 if ( $this->isAnon() ) {
3962 // Nothing else to do...
3966 // Only update the timestamp if the page is being watched.
3967 // The query to find out if it is watched is cached both in memcached and per-invocation,
3968 // and when it does have to be executed, it can be on a replica DB
3969 // If this is the user's newtalk page, we always update the timestamp
3971 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3975 MediaWikiServices
::getInstance()->getWatchedItemStore()
3976 ->resetNotificationTimestamp( $this, $title, $force, $oldid );
3980 * Resets all of the given user's page-change notification timestamps.
3981 * If e-notif e-mails are on, they will receive notification mails on
3982 * the next change of any watched page.
3983 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3985 public function clearAllNotifications() {
3986 global $wgUseEnotif, $wgShowUpdatedMarker;
3987 // Do nothing if not allowed to edit the watchlist
3988 if ( wfReadOnly() ||
!$this->isAllowed( 'editmywatchlist' ) ) {
3992 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3993 $this->setNewtalk( false );
3997 $id = $this->getId();
4002 $watchedItemStore = MediaWikiServices
::getInstance()->getWatchedItemStore();
4003 $watchedItemStore->resetAllNotificationTimestampsForUser( $this );
4005 // We also need to clear here the "you have new message" notification for the own
4006 // user_talk page; it's cleared one page view later in WikiPage::doViewUpdates().
4010 * Compute experienced level based on edit count and registration date.
4012 * @return string 'newcomer', 'learner', or 'experienced'
4014 public function getExperienceLevel() {
4015 global $wgLearnerEdits,
4016 $wgExperiencedUserEdits,
4017 $wgLearnerMemberSince,
4018 $wgExperiencedUserMemberSince;
4020 if ( $this->isAnon() ) {
4024 $editCount = $this->getEditCount();
4025 $registration = $this->getRegistration();
4027 $learnerRegistration = wfTimestamp( TS_MW
, $now - $wgLearnerMemberSince * 86400 );
4028 $experiencedRegistration = wfTimestamp( TS_MW
, $now - $wgExperiencedUserMemberSince * 86400 );
4031 $editCount < $wgLearnerEdits ||
4032 $registration > $learnerRegistration
4036 $editCount > $wgExperiencedUserEdits &&
4037 $registration <= $experiencedRegistration
4039 return 'experienced';
4046 * Persist this user's session (e.g. set cookies)
4048 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
4050 * @param bool $secure Whether to force secure/insecure cookies or use default
4051 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
4053 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
4055 if ( 0 == $this->mId
) {
4059 $session = $this->getRequest()->getSession();
4060 if ( $request && $session->getRequest() !== $request ) {
4061 $session = $session->sessionWithRequest( $request );
4063 $delay = $session->delaySave();
4065 if ( !$session->getUser()->equals( $this ) ) {
4066 if ( !$session->canSetUser() ) {
4067 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
4068 ->warning( __METHOD__
.
4069 ": Cannot save user \"$this\" to a user \"{$session->getUser()}\"'s immutable session"
4073 $session->setUser( $this );
4076 $session->setRememberUser( $rememberMe );
4077 if ( $secure !== null ) {
4078 $session->setForceHTTPS( $secure );
4081 $session->persist();
4083 ScopedCallback
::consume( $delay );
4087 * Log this user out.
4089 public function logout() {
4090 // Avoid PHP 7.1 warning of passing $this by reference
4092 if ( Hooks
::run( 'UserLogout', [ &$user ] ) ) {
4098 * Clear the user's session, and reset the instance cache.
4101 public function doLogout() {
4102 $session = $this->getRequest()->getSession();
4103 if ( !$session->canSetUser() ) {
4104 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
4105 ->warning( __METHOD__
. ": Cannot log out of an immutable session" );
4106 $error = 'immutable';
4107 } elseif ( !$session->getUser()->equals( $this ) ) {
4108 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
4109 ->warning( __METHOD__
.
4110 ": Cannot log user \"$this\" out of a user \"{$session->getUser()}\"'s session"
4112 // But we still may as well make this user object anon
4113 $this->clearInstanceCache( 'defaults' );
4114 $error = 'wronguser';
4116 $this->clearInstanceCache( 'defaults' );
4117 $delay = $session->delaySave();
4118 $session->unpersist(); // Clear cookies (T127436)
4119 $session->setLoggedOutTimestamp( time() );
4120 $session->setUser( new User
);
4121 $session->set( 'wsUserID', 0 ); // Other code expects this
4122 $session->resetAllTokens();
4123 ScopedCallback
::consume( $delay );
4126 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authevents' )->info( 'Logout', [
4127 'event' => 'logout',
4128 'successful' => $error === false,
4129 'status' => $error ?
: 'success',
4134 * Save this user's settings into the database.
4135 * @todo Only rarely do all these fields need to be set!
4137 public function saveSettings() {
4138 if ( wfReadOnly() ) {
4139 // @TODO: caller should deal with this instead!
4140 // This should really just be an exception.
4141 MWExceptionHandler
::logException( new DBExpectedError(
4143 "Could not update user with ID '{$this->mId}'; DB is read-only."
4149 if ( 0 == $this->mId
) {
4153 // Get a new user_touched that is higher than the old one.
4154 // This will be used for a CAS check as a last-resort safety
4155 // check against race conditions and replica DB lag.
4156 $newTouched = $this->newTouchedTimestamp();
4158 $dbw = wfGetDB( DB_MASTER
);
4159 $dbw->doAtomicSection( __METHOD__
, function ( $dbw, $fname ) use ( $newTouched ) {
4160 global $wgActorTableSchemaMigrationStage;
4162 $dbw->update( 'user',
4164 'user_name' => $this->mName
,
4165 'user_real_name' => $this->mRealName
,
4166 'user_email' => $this->mEmail
,
4167 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
4168 'user_touched' => $dbw->timestamp( $newTouched ),
4169 'user_token' => strval( $this->mToken
),
4170 'user_email_token' => $this->mEmailToken
,
4171 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
4172 ], $this->makeUpdateConditions( $dbw, [ /* WHERE */
4173 'user_id' => $this->mId
,
4177 if ( !$dbw->affectedRows() ) {
4178 // Maybe the problem was a missed cache update; clear it to be safe
4179 $this->clearSharedCache( 'refresh' );
4180 // User was changed in the meantime or loaded with stale data
4181 $from = ( $this->queryFlagsUsed
& self
::READ_LATEST
) ?
'master' : 'replica';
4182 throw new MWException(
4183 "CAS update failed on user_touched for user ID '{$this->mId}' (read from $from);" .
4184 " the version of the user to be saved is older than the current version."
4188 if ( $wgActorTableSchemaMigrationStage > MIGRATION_OLD
) {
4191 [ 'actor_name' => $this->mName
],
4192 [ 'actor_user' => $this->mId
],
4198 $this->mTouched
= $newTouched;
4199 $this->saveOptions();
4201 Hooks
::run( 'UserSaveSettings', [ $this ] );
4202 $this->clearSharedCache();
4203 $this->getUserPage()->invalidateCache();
4207 * If only this user's username is known, and it exists, return the user ID.
4209 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
4212 public function idForName( $flags = 0 ) {
4213 $s = trim( $this->getName() );
4218 $db = ( ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
)
4219 ?
wfGetDB( DB_MASTER
)
4220 : wfGetDB( DB_REPLICA
);
4222 $options = ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
)
4223 ?
[ 'LOCK IN SHARE MODE' ]
4226 $id = $db->selectField( 'user',
4227 'user_id', [ 'user_name' => $s ], __METHOD__
, $options );
4233 * Add a user to the database, return the user object
4235 * @param string $name Username to add
4236 * @param array $params Array of Strings Non-default parameters to save to
4237 * the database as user_* fields:
4238 * - email: The user's email address.
4239 * - email_authenticated: The email authentication timestamp.
4240 * - real_name: The user's real name.
4241 * - options: An associative array of non-default options.
4242 * - token: Random authentication token. Do not set.
4243 * - registration: Registration timestamp. Do not set.
4245 * @return User|null User object, or null if the username already exists.
4247 public static function createNew( $name, $params = [] ) {
4248 foreach ( [ 'password', 'newpassword', 'newpass_time', 'password_expires' ] as $field ) {
4249 if ( isset( $params[$field] ) ) {
4250 wfDeprecated( __METHOD__
. " with param '$field'", '1.27' );
4251 unset( $params[$field] );
4257 $user->setToken(); // init token
4258 if ( isset( $params['options'] ) ) {
4259 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
4260 unset( $params['options'] );
4262 $dbw = wfGetDB( DB_MASTER
);
4264 $noPass = PasswordFactory
::newInvalidPassword()->toString();
4267 'user_name' => $name,
4268 'user_password' => $noPass,
4269 'user_newpassword' => $noPass,
4270 'user_email' => $user->mEmail
,
4271 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
4272 'user_real_name' => $user->mRealName
,
4273 'user_token' => strval( $user->mToken
),
4274 'user_registration' => $dbw->timestamp( $user->mRegistration
),
4275 'user_editcount' => 0,
4276 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
4278 foreach ( $params as $name => $value ) {
4279 $fields["user_$name"] = $value;
4282 return $dbw->doAtomicSection( __METHOD__
, function ( $dbw, $fname ) use ( $fields ) {
4283 $dbw->insert( 'user', $fields, $fname, [ 'IGNORE' ] );
4284 if ( $dbw->affectedRows() ) {
4285 $newUser = self
::newFromId( $dbw->insertId() );
4286 // Load the user from master to avoid replica lag
4287 $newUser->load( self
::READ_LATEST
);
4288 $newUser->updateActorId( $dbw );
4297 * Add this existing user object to the database. If the user already
4298 * exists, a fatal status object is returned, and the user object is
4299 * initialised with the data from the database.
4301 * Previously, this function generated a DB error due to a key conflict
4302 * if the user already existed. Many extension callers use this function
4303 * in code along the lines of:
4305 * $user = User::newFromName( $name );
4306 * if ( !$user->isLoggedIn() ) {
4307 * $user->addToDatabase();
4309 * // do something with $user...
4311 * However, this was vulnerable to a race condition (T18020). By
4312 * initialising the user object if the user exists, we aim to support this
4313 * calling sequence as far as possible.
4315 * Note that if the user exists, this function will acquire a write lock,
4316 * so it is still advisable to make the call conditional on isLoggedIn(),
4317 * and to commit the transaction after calling.
4319 * @throws MWException
4322 public function addToDatabase() {
4324 if ( !$this->mToken
) {
4325 $this->setToken(); // init token
4328 if ( !is_string( $this->mName
) ) {
4329 throw new RuntimeException( "User name field is not set." );
4332 $this->mTouched
= $this->newTouchedTimestamp();
4334 $dbw = wfGetDB( DB_MASTER
);
4335 $status = $dbw->doAtomicSection( __METHOD__
, function ( $dbw, $fname ) {
4336 $noPass = PasswordFactory
::newInvalidPassword()->toString();
4337 $dbw->insert( 'user',
4339 'user_name' => $this->mName
,
4340 'user_password' => $noPass,
4341 'user_newpassword' => $noPass,
4342 'user_email' => $this->mEmail
,
4343 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
4344 'user_real_name' => $this->mRealName
,
4345 'user_token' => strval( $this->mToken
),
4346 'user_registration' => $dbw->timestamp( $this->mRegistration
),
4347 'user_editcount' => 0,
4348 'user_touched' => $dbw->timestamp( $this->mTouched
),
4352 if ( !$dbw->affectedRows() ) {
4353 // Use locking reads to bypass any REPEATABLE-READ snapshot.
4354 $this->mId
= $dbw->selectField(
4357 [ 'user_name' => $this->mName
],
4359 [ 'LOCK IN SHARE MODE' ]
4363 if ( $this->loadFromDatabase( self
::READ_LOCKING
) ) {
4368 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
4369 "to insert user '{$this->mName}' row, but it was not present in select!" );
4371 return Status
::newFatal( 'userexists' );
4373 $this->mId
= $dbw->insertId();
4374 self
::$idCacheByName[$this->mName
] = $this->mId
;
4375 $this->updateActorId( $dbw );
4377 return Status
::newGood();
4379 if ( !$status->isGood() ) {
4383 // Clear instance cache other than user table data and actor, which is already accurate
4384 $this->clearInstanceCache();
4386 $this->saveOptions();
4387 return Status
::newGood();
4391 * Update the actor ID after an insert
4392 * @param IDatabase $dbw Writable database handle
4394 private function updateActorId( IDatabase
$dbw ) {
4395 global $wgActorTableSchemaMigrationStage;
4397 if ( $wgActorTableSchemaMigrationStage > MIGRATION_OLD
) {
4400 [ 'actor_user' => $this->mId
, 'actor_name' => $this->mName
],
4403 $this->mActorId
= (int)$dbw->insertId();
4408 * If this user is logged-in and blocked,
4409 * block any IP address they've successfully logged in from.
4410 * @return bool A block was spread
4412 public function spreadAnyEditBlock() {
4413 if ( $this->isLoggedIn() && $this->isBlocked() ) {
4414 return $this->spreadBlock();
4421 * If this (non-anonymous) user is blocked,
4422 * block the IP address they've successfully logged in from.
4423 * @return bool A block was spread
4425 protected function spreadBlock() {
4426 wfDebug( __METHOD__
. "()\n" );
4428 if ( $this->mId
== 0 ) {
4432 $userblock = Block
::newFromTarget( $this->getName() );
4433 if ( !$userblock ) {
4437 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
4441 * Get whether the user is explicitly blocked from account creation.
4442 * @return bool|Block
4444 public function isBlockedFromCreateAccount() {
4445 $this->getBlockedStatus();
4446 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
4447 return $this->mBlock
;
4450 # T15611: if the IP address the user is trying to create an account from is
4451 # blocked with createaccount disabled, prevent new account creation there even
4452 # when the user is logged in
4453 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
4454 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
4456 return $this->mBlockedFromCreateAccount
instanceof Block
4457 && $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
4458 ?
$this->mBlockedFromCreateAccount
4463 * Get whether the user is blocked from using Special:Emailuser.
4466 public function isBlockedFromEmailuser() {
4467 $this->getBlockedStatus();
4468 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
4472 * Get whether the user is allowed to create an account.
4475 public function isAllowedToCreateAccount() {
4476 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
4480 * Get this user's personal page title.
4482 * @return Title User's personal page title
4484 public function getUserPage() {
4485 return Title
::makeTitle( NS_USER
, $this->getName() );
4489 * Get this user's talk page title.
4491 * @return Title User's talk page title
4493 public function getTalkPage() {
4494 $title = $this->getUserPage();
4495 return $title->getTalkPage();
4499 * Determine whether the user is a newbie. Newbies are either
4500 * anonymous IPs, or the most recently created accounts.
4503 public function isNewbie() {
4504 return !$this->isAllowed( 'autoconfirmed' );
4508 * Check to see if the given clear-text password is one of the accepted passwords
4509 * @deprecated since 1.27, use AuthManager instead
4510 * @param string $password User password
4511 * @return bool True if the given password is correct, otherwise False
4513 public function checkPassword( $password ) {
4514 $manager = AuthManager
::singleton();
4515 $reqs = AuthenticationRequest
::loadRequestsFromSubmission(
4516 $manager->getAuthenticationRequests( AuthManager
::ACTION_LOGIN
),
4518 'username' => $this->getName(),
4519 'password' => $password,
4522 $res = AuthManager
::singleton()->beginAuthentication( $reqs, 'null:' );
4523 switch ( $res->status
) {
4524 case AuthenticationResponse
::PASS
:
4526 case AuthenticationResponse
::FAIL
:
4527 // Hope it's not a PreAuthenticationProvider that failed...
4528 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
4529 ->info( __METHOD__
. ': Authentication failed: ' . $res->message
->plain() );
4532 throw new BadMethodCallException(
4533 'AuthManager returned a response unsupported by ' . __METHOD__
4539 * Check if the given clear-text password matches the temporary password
4540 * sent by e-mail for password reset operations.
4542 * @deprecated since 1.27, use AuthManager instead
4543 * @param string $plaintext
4544 * @return bool True if matches, false otherwise
4546 public function checkTemporaryPassword( $plaintext ) {
4547 // Can't check the temporary password individually.
4548 return $this->checkPassword( $plaintext );
4552 * Initialize (if necessary) and return a session token value
4553 * which can be used in edit forms to show that the user's
4554 * login credentials aren't being hijacked with a foreign form
4558 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4559 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4560 * @return MediaWiki\Session\Token The new edit token
4562 public function getEditTokenObject( $salt = '', $request = null ) {
4563 if ( $this->isAnon() ) {
4564 return new LoggedOutEditToken();
4568 $request = $this->getRequest();
4570 return $request->getSession()->getToken( $salt );
4574 * Initialize (if necessary) and return a session token value
4575 * which can be used in edit forms to show that the user's
4576 * login credentials aren't being hijacked with a foreign form
4579 * The $salt for 'edit' and 'csrf' tokens is the default (empty string).
4582 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4583 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4584 * @return string The new edit token
4586 public function getEditToken( $salt = '', $request = null ) {
4587 return $this->getEditTokenObject( $salt, $request )->toString();
4591 * Check given value against the token value stored in the session.
4592 * A match should confirm that the form was submitted from the
4593 * user's own login session, not a form submission from a third-party
4596 * @param string $val Input value to compare
4597 * @param string|array $salt Optional function-specific data for hashing
4598 * @param WebRequest|null $request Object to use or null to use $wgRequest
4599 * @param int $maxage Fail tokens older than this, in seconds
4600 * @return bool Whether the token matches
4602 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4603 return $this->getEditTokenObject( $salt, $request )->match( $val, $maxage );
4607 * Check given value against the token value stored in the session,
4608 * ignoring the suffix.
4610 * @param string $val Input value to compare
4611 * @param string|array $salt Optional function-specific data for hashing
4612 * @param WebRequest|null $request Object to use or null to use $wgRequest
4613 * @param int $maxage Fail tokens older than this, in seconds
4614 * @return bool Whether the token matches
4616 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4617 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . Token
::SUFFIX
;
4618 return $this->matchEditToken( $val, $salt, $request, $maxage );
4622 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4623 * mail to the user's given address.
4625 * @param string $type Message to send, either "created", "changed" or "set"
4628 public function sendConfirmationMail( $type = 'created' ) {
4630 $expiration = null; // gets passed-by-ref and defined in next line.
4631 $token = $this->confirmationToken( $expiration );
4632 $url = $this->confirmationTokenUrl( $token );
4633 $invalidateURL = $this->invalidationTokenUrl( $token );
4634 $this->saveSettings();
4636 if ( $type == 'created' ||
$type === false ) {
4637 $message = 'confirmemail_body';
4638 } elseif ( $type === true ) {
4639 $message = 'confirmemail_body_changed';
4641 // Messages: confirmemail_body_changed, confirmemail_body_set
4642 $message = 'confirmemail_body_' . $type;
4645 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4646 wfMessage( $message,
4647 $this->getRequest()->getIP(),
4650 $wgLang->userTimeAndDate( $expiration, $this ),
4652 $wgLang->userDate( $expiration, $this ),
4653 $wgLang->userTime( $expiration, $this ) )->text() );
4657 * Send an e-mail to this user's account. Does not check for
4658 * confirmed status or validity.
4660 * @param string $subject Message subject
4661 * @param string $body Message body
4662 * @param User|null $from Optional sending user; if unspecified, default
4663 * $wgPasswordSender will be used.
4664 * @param string $replyto Reply-To address
4667 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4668 global $wgPasswordSender;
4670 if ( $from instanceof User
) {
4671 $sender = MailAddress
::newFromUser( $from );
4673 $sender = new MailAddress( $wgPasswordSender,
4674 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4676 $to = MailAddress
::newFromUser( $this );
4678 return UserMailer
::send( $to, $sender, $subject, $body, [
4679 'replyTo' => $replyto,
4684 * Generate, store, and return a new e-mail confirmation code.
4685 * A hash (unsalted, since it's used as a key) is stored.
4687 * @note Call saveSettings() after calling this function to commit
4688 * this change to the database.
4690 * @param string &$expiration Accepts the expiration time
4691 * @return string New token
4693 protected function confirmationToken( &$expiration ) {
4694 global $wgUserEmailConfirmationTokenExpiry;
4696 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4697 $expiration = wfTimestamp( TS_MW
, $expires );
4699 $token = MWCryptRand
::generateHex( 32 );
4700 $hash = md5( $token );
4701 $this->mEmailToken
= $hash;
4702 $this->mEmailTokenExpires
= $expiration;
4707 * Return a URL the user can use to confirm their email address.
4708 * @param string $token Accepts the email confirmation token
4709 * @return string New token URL
4711 protected function confirmationTokenUrl( $token ) {
4712 return $this->getTokenUrl( 'ConfirmEmail', $token );
4716 * Return a URL the user can use to invalidate their email address.
4717 * @param string $token Accepts the email confirmation token
4718 * @return string New token URL
4720 protected function invalidationTokenUrl( $token ) {
4721 return $this->getTokenUrl( 'InvalidateEmail', $token );
4725 * Internal function to format the e-mail validation/invalidation URLs.
4726 * This uses a quickie hack to use the
4727 * hardcoded English names of the Special: pages, for ASCII safety.
4729 * @note Since these URLs get dropped directly into emails, using the
4730 * short English names avoids insanely long URL-encoded links, which
4731 * also sometimes can get corrupted in some browsers/mailers
4732 * (T8957 with Gmail and Internet Explorer).
4734 * @param string $page Special page
4735 * @param string $token
4736 * @return string Formatted URL
4738 protected function getTokenUrl( $page, $token ) {
4739 // Hack to bypass localization of 'Special:'
4740 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4741 return $title->getCanonicalURL();
4745 * Mark the e-mail address confirmed.
4747 * @note Call saveSettings() after calling this function to commit the change.
4751 public function confirmEmail() {
4752 // Check if it's already confirmed, so we don't touch the database
4753 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4754 if ( !$this->isEmailConfirmed() ) {
4755 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4756 Hooks
::run( 'ConfirmEmailComplete', [ $this ] );
4762 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4763 * address if it was already confirmed.
4765 * @note Call saveSettings() after calling this function to commit the change.
4766 * @return bool Returns true
4768 public function invalidateEmail() {
4770 $this->mEmailToken
= null;
4771 $this->mEmailTokenExpires
= null;
4772 $this->setEmailAuthenticationTimestamp( null );
4774 Hooks
::run( 'InvalidateEmailComplete', [ $this ] );
4779 * Set the e-mail authentication timestamp.
4780 * @param string $timestamp TS_MW timestamp
4782 public function setEmailAuthenticationTimestamp( $timestamp ) {
4784 $this->mEmailAuthenticated
= $timestamp;
4785 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
4789 * Is this user allowed to send e-mails within limits of current
4790 * site configuration?
4793 public function canSendEmail() {
4794 global $wgEnableEmail, $wgEnableUserEmail;
4795 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4798 $canSend = $this->isEmailConfirmed();
4799 // Avoid PHP 7.1 warning of passing $this by reference
4801 Hooks
::run( 'UserCanSendEmail', [ &$user, &$canSend ] );
4806 * Is this user allowed to receive e-mails within limits of current
4807 * site configuration?
4810 public function canReceiveEmail() {
4811 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4815 * Is this user's e-mail address valid-looking and confirmed within
4816 * limits of the current site configuration?
4818 * @note If $wgEmailAuthentication is on, this may require the user to have
4819 * confirmed their address by returning a code or using a password
4820 * sent to the address from the wiki.
4824 public function isEmailConfirmed() {
4825 global $wgEmailAuthentication;
4827 // Avoid PHP 7.1 warning of passing $this by reference
4830 if ( Hooks
::run( 'EmailConfirmed', [ &$user, &$confirmed ] ) ) {
4831 if ( $this->isAnon() ) {
4834 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4837 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4847 * Check whether there is an outstanding request for e-mail confirmation.
4850 public function isEmailConfirmationPending() {
4851 global $wgEmailAuthentication;
4852 return $wgEmailAuthentication &&
4853 !$this->isEmailConfirmed() &&
4854 $this->mEmailToken
&&
4855 $this->mEmailTokenExpires
> wfTimestamp();
4859 * Get the timestamp of account creation.
4861 * @return string|bool|null Timestamp of account creation, false for
4862 * non-existent/anonymous user accounts, or null if existing account
4863 * but information is not in database.
4865 public function getRegistration() {
4866 if ( $this->isAnon() ) {
4870 return $this->mRegistration
;
4874 * Get the timestamp of the first edit
4876 * @return string|bool Timestamp of first edit, or false for
4877 * non-existent/anonymous user accounts.
4879 public function getFirstEditTimestamp() {
4880 if ( $this->getId() == 0 ) {
4881 return false; // anons
4883 $dbr = wfGetDB( DB_REPLICA
);
4884 $actorWhere = ActorMigration
::newMigration()->getWhere( $dbr, 'rev_user', $this );
4885 $time = $dbr->selectField(
4886 [ 'revision' ] +
$actorWhere['tables'],
4888 [ $actorWhere['conds'] ],
4890 [ 'ORDER BY' => 'rev_timestamp ASC' ],
4891 $actorWhere['joins']
4894 return false; // no edits
4896 return wfTimestamp( TS_MW
, $time );
4900 * Get the permissions associated with a given list of groups
4902 * @param array $groups Array of Strings List of internal group names
4903 * @return array Array of Strings List of permission key names for given groups combined
4905 public static function getGroupPermissions( $groups ) {
4906 global $wgGroupPermissions, $wgRevokePermissions;
4908 // grant every granted permission first
4909 foreach ( $groups as $group ) {
4910 if ( isset( $wgGroupPermissions[$group] ) ) {
4911 $rights = array_merge( $rights,
4912 // array_filter removes empty items
4913 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4916 // now revoke the revoked permissions
4917 foreach ( $groups as $group ) {
4918 if ( isset( $wgRevokePermissions[$group] ) ) {
4919 $rights = array_diff( $rights,
4920 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4923 return array_unique( $rights );
4927 * Get all the groups who have a given permission
4929 * @param string $role Role to check
4930 * @return array Array of Strings List of internal group names with the given permission
4932 public static function getGroupsWithPermission( $role ) {
4933 global $wgGroupPermissions;
4934 $allowedGroups = [];
4935 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4936 if ( self
::groupHasPermission( $group, $role ) ) {
4937 $allowedGroups[] = $group;
4940 return $allowedGroups;
4944 * Check, if the given group has the given permission
4946 * If you're wanting to check whether all users have a permission, use
4947 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4951 * @param string $group Group to check
4952 * @param string $role Role to check
4955 public static function groupHasPermission( $group, $role ) {
4956 global $wgGroupPermissions, $wgRevokePermissions;
4957 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4958 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4962 * Check if all users may be assumed to have the given permission
4964 * We generally assume so if the right is granted to '*' and isn't revoked
4965 * on any group. It doesn't attempt to take grants or other extension
4966 * limitations on rights into account in the general case, though, as that
4967 * would require it to always return false and defeat the purpose.
4968 * Specifically, session-based rights restrictions (such as OAuth or bot
4969 * passwords) are applied based on the current session.
4972 * @param string $right Right to check
4975 public static function isEveryoneAllowed( $right ) {
4976 global $wgGroupPermissions, $wgRevokePermissions;
4979 // Use the cached results, except in unit tests which rely on
4980 // being able change the permission mid-request
4981 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4982 return $cache[$right];
4985 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4986 $cache[$right] = false;
4990 // If it's revoked anywhere, then everyone doesn't have it
4991 foreach ( $wgRevokePermissions as $rights ) {
4992 if ( isset( $rights[$right] ) && $rights[$right] ) {
4993 $cache[$right] = false;
4998 // Remove any rights that aren't allowed to the global-session user,
4999 // unless there are no sessions for this endpoint.
5000 if ( !defined( 'MW_NO_SESSION' ) ) {
5001 $allowedRights = SessionManager
::getGlobalSession()->getAllowedUserRights();
5002 if ( $allowedRights !== null && !in_array( $right, $allowedRights, true ) ) {
5003 $cache[$right] = false;
5008 // Allow extensions to say false
5009 if ( !Hooks
::run( 'UserIsEveryoneAllowed', [ $right ] ) ) {
5010 $cache[$right] = false;
5014 $cache[$right] = true;
5019 * Get the localized descriptive name for a group, if it exists
5020 * @deprecated since 1.29 Use UserGroupMembership::getGroupName instead
5022 * @param string $group Internal group name
5023 * @return string Localized descriptive group name
5025 public static function getGroupName( $group ) {
5026 wfDeprecated( __METHOD__
, '1.29' );
5027 return UserGroupMembership
::getGroupName( $group );
5031 * Get the localized descriptive name for a member of a group, if it exists
5032 * @deprecated since 1.29 Use UserGroupMembership::getGroupMemberName instead
5034 * @param string $group Internal group name
5035 * @param string $username Username for gender (since 1.19)
5036 * @return string Localized name for group member
5038 public static function getGroupMember( $group, $username = '#' ) {
5039 wfDeprecated( __METHOD__
, '1.29' );
5040 return UserGroupMembership
::getGroupMemberName( $group, $username );
5044 * Return the set of defined explicit groups.
5045 * The implicit groups (by default *, 'user' and 'autoconfirmed')
5046 * are not included, as they are defined automatically, not in the database.
5047 * @return array Array of internal group names
5049 public static function getAllGroups() {
5050 global $wgGroupPermissions, $wgRevokePermissions;
5052 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
5053 self
::getImplicitGroups()
5058 * Get a list of all available permissions.
5059 * @return string[] Array of permission names
5061 public static function getAllRights() {
5062 if ( self
::$mAllRights === false ) {
5063 global $wgAvailableRights;
5064 if ( count( $wgAvailableRights ) ) {
5065 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
5067 self
::$mAllRights = self
::$mCoreRights;
5069 Hooks
::run( 'UserGetAllRights', [ &self
::$mAllRights ] );
5071 return self
::$mAllRights;
5075 * Get a list of implicit groups
5076 * @return array Array of Strings Array of internal group names
5078 public static function getImplicitGroups() {
5079 global $wgImplicitGroups;
5081 $groups = $wgImplicitGroups;
5082 # Deprecated, use $wgImplicitGroups instead
5083 Hooks
::run( 'UserGetImplicitGroups', [ &$groups ], '1.25' );
5089 * Get the title of a page describing a particular group
5090 * @deprecated since 1.29 Use UserGroupMembership::getGroupPage instead
5092 * @param string $group Internal group name
5093 * @return Title|bool Title of the page if it exists, false otherwise
5095 public static function getGroupPage( $group ) {
5096 wfDeprecated( __METHOD__
, '1.29' );
5097 return UserGroupMembership
::getGroupPage( $group );
5101 * Create a link to the group in HTML, if available;
5102 * else return the group name.
5103 * @deprecated since 1.29 Use UserGroupMembership::getLink instead, or
5104 * make the link yourself if you need custom text
5106 * @param string $group Internal name of the group
5107 * @param string $text The text of the link
5108 * @return string HTML link to the group
5110 public static function makeGroupLinkHTML( $group, $text = '' ) {
5111 wfDeprecated( __METHOD__
, '1.29' );
5113 if ( $text == '' ) {
5114 $text = UserGroupMembership
::getGroupName( $group );
5116 $title = UserGroupMembership
::getGroupPage( $group );
5118 return MediaWikiServices
::getInstance()
5119 ->getLinkRenderer()->makeLink( $title, $text );
5121 return htmlspecialchars( $text );
5126 * Create a link to the group in Wikitext, if available;
5127 * else return the group name.
5128 * @deprecated since 1.29 Use UserGroupMembership::getLink instead, or
5129 * make the link yourself if you need custom text
5131 * @param string $group Internal name of the group
5132 * @param string $text The text of the link
5133 * @return string Wikilink to the group
5135 public static function makeGroupLinkWiki( $group, $text = '' ) {
5136 wfDeprecated( __METHOD__
, '1.29' );
5138 if ( $text == '' ) {
5139 $text = UserGroupMembership
::getGroupName( $group );
5141 $title = UserGroupMembership
::getGroupPage( $group );
5143 $page = $title->getFullText();
5144 return "[[$page|$text]]";
5151 * Returns an array of the groups that a particular group can add/remove.
5153 * @param string $group The group to check for whether it can add/remove
5154 * @return array Array( 'add' => array( addablegroups ),
5155 * 'remove' => array( removablegroups ),
5156 * 'add-self' => array( addablegroups to self),
5157 * 'remove-self' => array( removable groups from self) )
5159 public static function changeableByGroup( $group ) {
5160 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
5169 if ( empty( $wgAddGroups[$group] ) ) {
5170 // Don't add anything to $groups
5171 } elseif ( $wgAddGroups[$group] === true ) {
5172 // You get everything
5173 $groups['add'] = self
::getAllGroups();
5174 } elseif ( is_array( $wgAddGroups[$group] ) ) {
5175 $groups['add'] = $wgAddGroups[$group];
5178 // Same thing for remove
5179 if ( empty( $wgRemoveGroups[$group] ) ) {
5181 } elseif ( $wgRemoveGroups[$group] === true ) {
5182 $groups['remove'] = self
::getAllGroups();
5183 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
5184 $groups['remove'] = $wgRemoveGroups[$group];
5187 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
5188 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
5189 foreach ( $wgGroupsAddToSelf as $key => $value ) {
5190 if ( is_int( $key ) ) {
5191 $wgGroupsAddToSelf['user'][] = $value;
5196 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
5197 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
5198 if ( is_int( $key ) ) {
5199 $wgGroupsRemoveFromSelf['user'][] = $value;
5204 // Now figure out what groups the user can add to him/herself
5205 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
5207 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
5208 // No idea WHY this would be used, but it's there
5209 $groups['add-self'] = self
::getAllGroups();
5210 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
5211 $groups['add-self'] = $wgGroupsAddToSelf[$group];
5214 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
5216 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
5217 $groups['remove-self'] = self
::getAllGroups();
5218 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
5219 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
5226 * Returns an array of groups that this user can add and remove
5227 * @return array Array( 'add' => array( addablegroups ),
5228 * 'remove' => array( removablegroups ),
5229 * 'add-self' => array( addablegroups to self),
5230 * 'remove-self' => array( removable groups from self) )
5232 public function changeableGroups() {
5233 if ( $this->isAllowed( 'userrights' ) ) {
5234 // This group gives the right to modify everything (reverse-
5235 // compatibility with old "userrights lets you change
5237 // Using array_merge to make the groups reindexed
5238 $all = array_merge( self
::getAllGroups() );
5247 // Okay, it's not so simple, we will have to go through the arrays
5254 $addergroups = $this->getEffectiveGroups();
5256 foreach ( $addergroups as $addergroup ) {
5257 $groups = array_merge_recursive(
5258 $groups, $this->changeableByGroup( $addergroup )
5260 $groups['add'] = array_unique( $groups['add'] );
5261 $groups['remove'] = array_unique( $groups['remove'] );
5262 $groups['add-self'] = array_unique( $groups['add-self'] );
5263 $groups['remove-self'] = array_unique( $groups['remove-self'] );
5269 * Deferred version of incEditCountImmediate()
5271 * This function, rather than incEditCountImmediate(), should be used for
5272 * most cases as it avoids potential deadlocks caused by concurrent editing.
5274 public function incEditCount() {
5275 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle(
5277 $this->incEditCountImmediate();
5284 * Increment the user's edit-count field.
5285 * Will have no effect for anonymous users.
5288 public function incEditCountImmediate() {
5289 if ( $this->isAnon() ) {
5293 $dbw = wfGetDB( DB_MASTER
);
5294 // No rows will be "affected" if user_editcount is NULL
5297 [ 'user_editcount=user_editcount+1' ],
5298 [ 'user_id' => $this->getId(), 'user_editcount IS NOT NULL' ],
5301 // Lazy initialization check...
5302 if ( $dbw->affectedRows() == 0 ) {
5303 // Now here's a goddamn hack...
5304 $dbr = wfGetDB( DB_REPLICA
);
5305 if ( $dbr !== $dbw ) {
5306 // If we actually have a replica DB server, the count is
5307 // at least one behind because the current transaction
5308 // has not been committed and replicated.
5309 $this->mEditCount
= $this->initEditCount( 1 );
5311 // But if DB_REPLICA is selecting the master, then the
5312 // count we just read includes the revision that was
5313 // just added in the working transaction.
5314 $this->mEditCount
= $this->initEditCount();
5317 if ( $this->mEditCount
=== null ) {
5318 $this->getEditCount();
5319 $dbr = wfGetDB( DB_REPLICA
);
5320 $this->mEditCount +
= ( $dbr !== $dbw ) ?
1 : 0;
5322 $this->mEditCount++
;
5325 // Edit count in user cache too
5326 $this->invalidateCache();
5330 * Initialize user_editcount from data out of the revision table
5332 * @param int $add Edits to add to the count from the revision table
5333 * @return int Number of edits
5335 protected function initEditCount( $add = 0 ) {
5336 // Pull from a replica DB to be less cruel to servers
5337 // Accuracy isn't the point anyway here
5338 $dbr = wfGetDB( DB_REPLICA
);
5339 $actorWhere = ActorMigration
::newMigration()->getWhere( $dbr, 'rev_user', $this );
5340 $count = (int)$dbr->selectField(
5341 [ 'revision' ] +
$actorWhere['tables'],
5343 [ $actorWhere['conds'] ],
5346 $actorWhere['joins']
5348 $count = $count +
$add;
5350 $dbw = wfGetDB( DB_MASTER
);
5353 [ 'user_editcount' => $count ],
5354 [ 'user_id' => $this->getId() ],
5362 * Get the description of a given right
5365 * @param string $right Right to query
5366 * @return string Localized description of the right
5368 public static function getRightDescription( $right ) {
5369 $key = "right-$right";
5370 $msg = wfMessage( $key );
5371 return $msg->isDisabled() ?
$right : $msg->text();
5375 * Get the name of a given grant
5378 * @param string $grant Grant to query
5379 * @return string Localized name of the grant
5381 public static function getGrantName( $grant ) {
5382 $key = "grant-$grant";
5383 $msg = wfMessage( $key );
5384 return $msg->isDisabled() ?
$grant : $msg->text();
5388 * Add a newuser log entry for this user.
5389 * Before 1.19 the return value was always true.
5391 * @deprecated since 1.27, AuthManager handles logging
5392 * @param string|bool $action Account creation type.
5393 * - String, one of the following values:
5394 * - 'create' for an anonymous user creating an account for himself.
5395 * This will force the action's performer to be the created user itself,
5396 * no matter the value of $wgUser
5397 * - 'create2' for a logged in user creating an account for someone else
5398 * - 'byemail' when the created user will receive its password by e-mail
5399 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
5400 * - Boolean means whether the account was created by e-mail (deprecated):
5401 * - true will be converted to 'byemail'
5402 * - false will be converted to 'create' if this object is the same as
5403 * $wgUser and to 'create2' otherwise
5404 * @param string $reason User supplied reason
5407 public function addNewUserLogEntry( $action = false, $reason = '' ) {
5408 return true; // disabled
5412 * Add an autocreate newuser log entry for this user
5413 * Used by things like CentralAuth and perhaps other authplugins.
5414 * Consider calling addNewUserLogEntry() directly instead.
5416 * @deprecated since 1.27, AuthManager handles logging
5419 public function addNewUserLogEntryAutoCreate() {
5420 $this->addNewUserLogEntry( 'autocreate' );
5426 * Load the user options either from cache, the database or an array
5428 * @param array $data Rows for the current user out of the user_properties table
5430 protected function loadOptions( $data = null ) {
5435 if ( $this->mOptionsLoaded
) {
5439 $this->mOptions
= self
::getDefaultOptions();
5441 if ( !$this->getId() ) {
5442 // For unlogged-in users, load language/variant options from request.
5443 // There's no need to do it for logged-in users: they can set preferences,
5444 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5445 // so don't override user's choice (especially when the user chooses site default).
5446 $variant = $wgContLang->getDefaultVariant();
5447 $this->mOptions
['variant'] = $variant;
5448 $this->mOptions
['language'] = $variant;
5449 $this->mOptionsLoaded
= true;
5453 // Maybe load from the object
5454 if ( !is_null( $this->mOptionOverrides
) ) {
5455 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5456 foreach ( $this->mOptionOverrides
as $key => $value ) {
5457 $this->mOptions
[$key] = $value;
5460 if ( !is_array( $data ) ) {
5461 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5462 // Load from database
5463 $dbr = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
5464 ?
wfGetDB( DB_MASTER
)
5465 : wfGetDB( DB_REPLICA
);
5467 $res = $dbr->select(
5469 [ 'up_property', 'up_value' ],
5470 [ 'up_user' => $this->getId() ],
5474 $this->mOptionOverrides
= [];
5476 foreach ( $res as $row ) {
5477 // Convert '0' to 0. PHP's boolean conversion considers them both
5478 // false, but e.g. JavaScript considers the former as true.
5479 // @todo: T54542 Somehow determine the desired type (string/int/bool)
5480 // and convert all values here.
5481 if ( $row->up_value
=== '0' ) {
5484 $data[$row->up_property
] = $row->up_value
;
5488 // Convert the email blacklist from a new line delimited string
5489 // to an array of ids.
5490 if ( isset( $data['email-blacklist'] ) && $data['email-blacklist'] ) {
5491 $data['email-blacklist'] = array_map( 'intval', explode( "\n", $data['email-blacklist'] ) );
5494 foreach ( $data as $property => $value ) {
5495 $this->mOptionOverrides
[$property] = $value;
5496 $this->mOptions
[$property] = $value;
5500 $this->mOptionsLoaded
= true;
5502 Hooks
::run( 'UserLoadOptions', [ $this, &$this->mOptions
] );
5506 * Saves the non-default options for this user, as previously set e.g. via
5507 * setOption(), in the database's "user_properties" (preferences) table.
5508 * Usually used via saveSettings().
5510 protected function saveOptions() {
5511 $this->loadOptions();
5513 // Not using getOptions(), to keep hidden preferences in database
5514 $saveOptions = $this->mOptions
;
5516 // Convert usernames to ids.
5517 if ( isset( $this->mOptions
['email-blacklist'] ) ) {
5518 if ( $this->mOptions
['email-blacklist'] ) {
5519 $value = $this->mOptions
['email-blacklist'];
5520 // Email Blacklist may be an array of ids or a string of new line
5521 // delimnated user names.
5522 if ( is_array( $value ) ) {
5523 $ids = array_filter( $value, 'is_numeric' );
5525 $lookup = CentralIdLookup
::factory();
5526 $ids = $lookup->centralIdsFromNames( explode( "\n", $value ), $this );
5528 $this->mOptions
['email-blacklist'] = $ids;
5529 $saveOptions['email-blacklist'] = implode( "\n", $this->mOptions
['email-blacklist'] );
5531 // If the blacklist is empty, set it to null rather than an empty string.
5532 $this->mOptions
['email-blacklist'] = null;
5536 // Allow hooks to abort, for instance to save to a global profile.
5537 // Reset options to default state before saving.
5538 if ( !Hooks
::run( 'UserSaveOptions', [ $this, &$saveOptions ] ) ) {
5542 $userId = $this->getId();
5544 $insert_rows = []; // all the new preference rows
5545 foreach ( $saveOptions as $key => $value ) {
5546 // Don't bother storing default values
5547 $defaultOption = self
::getDefaultOption( $key );
5548 if ( ( $defaultOption === null && $value !== false && $value !== null )
5549 ||
$value != $defaultOption
5552 'up_user' => $userId,
5553 'up_property' => $key,
5554 'up_value' => $value,
5559 $dbw = wfGetDB( DB_MASTER
);
5561 $res = $dbw->select( 'user_properties',
5562 [ 'up_property', 'up_value' ], [ 'up_user' => $userId ], __METHOD__
);
5564 // Find prior rows that need to be removed or updated. These rows will
5565 // all be deleted (the latter so that INSERT IGNORE applies the new values).
5567 foreach ( $res as $row ) {
5568 if ( !isset( $saveOptions[$row->up_property
] )
5569 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
5571 $keysDelete[] = $row->up_property
;
5575 if ( count( $keysDelete ) ) {
5576 // Do the DELETE by PRIMARY KEY for prior rows.
5577 // In the past a very large portion of calls to this function are for setting
5578 // 'rememberpassword' for new accounts (a preference that has since been removed).
5579 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5580 // caused gap locks on [max user ID,+infinity) which caused high contention since
5581 // updates would pile up on each other as they are for higher (newer) user IDs.
5582 // It might not be necessary these days, but it shouldn't hurt either.
5583 $dbw->delete( 'user_properties',
5584 [ 'up_user' => $userId, 'up_property' => $keysDelete ], __METHOD__
);
5586 // Insert the new preference rows
5587 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, [ 'IGNORE' ] );
5591 * Return the list of user fields that should be selected to create
5592 * a new user object.
5593 * @deprecated since 1.31, use self::getQueryInfo() instead.
5596 public static function selectFields() {
5597 wfDeprecated( __METHOD__
, '1.31' );
5605 'user_email_authenticated',
5607 'user_email_token_expires',
5608 'user_registration',
5614 * Return the tables, fields, and join conditions to be selected to create
5615 * a new user object.
5617 * @return array With three keys:
5618 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
5619 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
5620 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
5622 public static function getQueryInfo() {
5623 global $wgActorTableSchemaMigrationStage;
5626 'tables' => [ 'user' ],
5634 'user_email_authenticated',
5636 'user_email_token_expires',
5637 'user_registration',
5642 if ( $wgActorTableSchemaMigrationStage > MIGRATION_OLD
) {
5643 $ret['tables']['user_actor'] = 'actor';
5644 $ret['fields'][] = 'user_actor.actor_id';
5645 $ret['joins']['user_actor'] = [
5646 $wgActorTableSchemaMigrationStage === MIGRATION_NEW ?
'JOIN' : 'LEFT JOIN',
5647 [ 'user_actor.actor_user = user_id' ]
5654 * Factory function for fatal permission-denied errors
5657 * @param string $permission User right required
5660 static function newFatalPermissionDeniedStatus( $permission ) {
5664 foreach ( self
::getGroupsWithPermission( $permission ) as $group ) {
5665 $groups[] = UserGroupMembership
::getLink( $group, RequestContext
::getMain(), 'wiki' );
5669 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5671 return Status
::newFatal( 'badaccess-group0' );
5676 * Get a new instance of this user that was loaded from the master via a locking read
5678 * Use this instead of the main context User when updating that user. This avoids races
5679 * where that user was loaded from a replica DB or even the master but without proper locks.
5681 * @return User|null Returns null if the user was not found in the DB
5684 public function getInstanceForUpdate() {
5685 if ( !$this->getId() ) {
5686 return null; // anon
5689 $user = self
::newFromId( $this->getId() );
5690 if ( !$user->loadFromId( self
::READ_EXCLUSIVE
) ) {
5698 * Checks if two user objects point to the same user.
5700 * @since 1.25 ; takes a UserIdentity instead of a User since 1.32
5701 * @param UserIdentity $user
5704 public function equals( UserIdentity
$user ) {
5705 // XXX it's not clear whether central ID providers are supposed to obey this
5706 return $this->getName() === $user->getName();