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 * Returns a User object corresponding to the given UserIdentity.
644 * @param UserIdentity $identity
648 public static function newFromIdentity( UserIdentity
$identity ) {
649 if ( $identity instanceof User
) {
653 return self
::newFromAnyId(
654 $identity->getId() === 0 ?
null : $identity->getId(),
655 $identity->getName() === '' ?
null : $identity->getName(),
656 $identity->getActorId() === 0 ?
null : $identity->getActorId()
661 * Static factory method for creation from an ID, name, and/or actor ID
663 * This does not check that the ID, name, and actor ID all correspond to
667 * @param int|null $userId User ID, if known
668 * @param string|null $userName User name, if known
669 * @param int|null $actorId Actor ID, if known
672 public static function newFromAnyId( $userId, $userName, $actorId ) {
673 global $wgActorTableSchemaMigrationStage;
676 $user->mFrom
= 'defaults';
678 if ( $wgActorTableSchemaMigrationStage > MIGRATION_OLD
&& $actorId !== null ) {
679 $user->mActorId
= (int)$actorId;
680 if ( $user->mActorId
!== 0 ) {
681 $user->mFrom
= 'actor';
683 $user->setItemLoaded( 'actor' );
686 if ( $userName !== null && $userName !== '' ) {
687 $user->mName
= $userName;
688 $user->mFrom
= 'name';
689 $user->setItemLoaded( 'name' );
692 if ( $userId !== null ) {
693 $user->mId
= (int)$userId;
694 if ( $user->mId
!== 0 ) {
697 $user->setItemLoaded( 'id' );
700 if ( $user->mFrom
=== 'defaults' ) {
701 throw new InvalidArgumentException(
702 'Cannot create a user with no name, no ID, and no actor ID'
710 * Factory method to fetch whichever user has a given email confirmation code.
711 * This code is generated when an account is created or its e-mail address
714 * If the code is invalid or has expired, returns NULL.
716 * @param string $code Confirmation code
717 * @param int $flags User::READ_* bitfield
720 public static function newFromConfirmationCode( $code, $flags = 0 ) {
721 $db = ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
722 ?
wfGetDB( DB_MASTER
)
723 : wfGetDB( DB_REPLICA
);
725 $id = $db->selectField(
729 'user_email_token' => md5( $code ),
730 'user_email_token_expires > ' . $db->addQuotes( $db->timestamp() ),
734 return $id ? self
::newFromId( $id ) : null;
738 * Create a new user object using data from session. If the login
739 * credentials are invalid, the result is an anonymous user.
741 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
744 public static function newFromSession( WebRequest
$request = null ) {
746 $user->mFrom
= 'session';
747 $user->mRequest
= $request;
752 * Create a new user object from a user row.
753 * The row should have the following fields from the user table in it:
754 * - either user_name or user_id to load further data if needed (or both)
756 * - all other fields (email, etc.)
757 * It is useless to provide the remaining fields if either user_id,
758 * user_name and user_real_name are not provided because the whole row
759 * will be loaded once more from the database when accessing them.
761 * @param stdClass $row A row from the user table
762 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
765 public static function newFromRow( $row, $data = null ) {
767 $user->loadFromRow( $row, $data );
772 * Static factory method for creation of a "system" user from username.
774 * A "system" user is an account that's used to attribute logged actions
775 * taken by MediaWiki itself, as opposed to a bot or human user. Examples
776 * might include the 'Maintenance script' or 'Conversion script' accounts
777 * used by various scripts in the maintenance/ directory or accounts such
778 * as 'MediaWiki message delivery' used by the MassMessage extension.
780 * This can optionally create the user if it doesn't exist, and "steal" the
781 * account if it does exist.
783 * "Stealing" an existing user is intended to make it impossible for normal
784 * authentication processes to use the account, effectively disabling the
785 * account for normal use:
786 * - Email is invalidated, to prevent account recovery by emailing a
787 * temporary password and to disassociate the account from the existing
789 * - The token is set to a magic invalid value, to kill existing sessions
790 * and to prevent $this->setToken() calls from resetting the token to a
792 * - SessionManager is instructed to prevent new sessions for the user, to
793 * do things like deauthorizing OAuth consumers.
794 * - AuthManager is instructed to revoke access, to invalidate or remove
795 * passwords and other credentials.
797 * @param string $name Username
798 * @param array $options Options are:
799 * - validate: As for User::getCanonicalName(), default 'valid'
800 * - create: Whether to create the user if it doesn't already exist, default true
801 * - steal: Whether to "disable" the account for normal use if it already
802 * exists, default false
806 public static function newSystemUser( $name, $options = [] ) {
808 'validate' => 'valid',
813 $name = self
::getCanonicalName( $name, $options['validate'] );
814 if ( $name === false ) {
818 $dbr = wfGetDB( DB_REPLICA
);
819 $userQuery = self
::getQueryInfo();
820 $row = $dbr->selectRow(
821 $userQuery['tables'],
822 $userQuery['fields'],
823 [ 'user_name' => $name ],
829 // Try the master database...
830 $dbw = wfGetDB( DB_MASTER
);
831 $row = $dbw->selectRow(
832 $userQuery['tables'],
833 $userQuery['fields'],
834 [ 'user_name' => $name ],
842 // No user. Create it?
843 return $options['create']
844 ? self
::createNew( $name, [ 'token' => self
::INVALID_TOKEN
] )
848 $user = self
::newFromRow( $row );
850 // A user is considered to exist as a non-system user if it can
851 // authenticate, or has an email set, or has a non-invalid token.
852 if ( $user->mEmail ||
$user->mToken
!== self
::INVALID_TOKEN ||
853 AuthManager
::singleton()->userCanAuthenticate( $name )
855 // User exists. Steal it?
856 if ( !$options['steal'] ) {
860 AuthManager
::singleton()->revokeAccessForUser( $name );
862 $user->invalidateEmail();
863 $user->mToken
= self
::INVALID_TOKEN
;
864 $user->saveSettings();
865 SessionManager
::singleton()->preventSessionsForUser( $user->getName() );
874 * Get the username corresponding to a given user ID
875 * @param int $id User ID
876 * @return string|bool The corresponding username
878 public static function whoIs( $id ) {
879 return UserCache
::singleton()->getProp( $id, 'name' );
883 * Get the real name of a user given their user ID
885 * @param int $id User ID
886 * @return string|bool The corresponding user's real name
888 public static function whoIsReal( $id ) {
889 return UserCache
::singleton()->getProp( $id, 'real_name' );
893 * Get database id given a user name
894 * @param string $name Username
895 * @param int $flags User::READ_* constant bitfield
896 * @return int|null The corresponding user's ID, or null if user is nonexistent
898 public static function idFromName( $name, $flags = self
::READ_NORMAL
) {
899 $nt = Title
::makeTitleSafe( NS_USER
, $name );
900 if ( is_null( $nt ) ) {
905 if ( !( $flags & self
::READ_LATEST
) && array_key_exists( $name, self
::$idCacheByName ) ) {
906 return self
::$idCacheByName[$name];
909 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
910 $db = wfGetDB( $index );
915 [ 'user_name' => $nt->getText() ],
920 if ( $s === false ) {
923 $result = $s->user_id
;
926 self
::$idCacheByName[$name] = $result;
928 if ( count( self
::$idCacheByName ) > 1000 ) {
929 self
::$idCacheByName = [];
936 * Reset the cache used in idFromName(). For use in tests.
938 public static function resetIdByNameCache() {
939 self
::$idCacheByName = [];
943 * Does the string match an anonymous IP address?
945 * This function exists for username validation, in order to reject
946 * usernames which are similar in form to IP addresses. Strings such
947 * as 300.300.300.300 will return true because it looks like an IP
948 * address, despite not being strictly valid.
950 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
951 * address because the usemod software would "cloak" anonymous IP
952 * addresses like this, if we allowed accounts like this to be created
953 * new users could get the old edits of these anonymous users.
955 * @param string $name Name to match
958 public static function isIP( $name ) {
959 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
960 || IP
::isIPv6( $name );
964 * Is the user an IP range?
969 public function isIPRange() {
970 return IP
::isValidRange( $this->mName
);
974 * Is the input a valid username?
976 * Checks if the input is a valid username, we don't want an empty string,
977 * an IP address, anything that contains slashes (would mess up subpages),
978 * is longer than the maximum allowed username size or doesn't begin with
981 * @param string $name Name to match
984 public static function isValidUserName( $name ) {
985 global $wgContLang, $wgMaxNameChars;
988 || self
::isIP( $name )
989 ||
strpos( $name, '/' ) !== false
990 ||
strlen( $name ) > $wgMaxNameChars
991 ||
$name != $wgContLang->ucfirst( $name )
996 // Ensure that the name can't be misresolved as a different title,
997 // such as with extra namespace keys at the start.
998 $parsed = Title
::newFromText( $name );
999 if ( is_null( $parsed )
1000 ||
$parsed->getNamespace()
1001 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
1005 // Check an additional blacklist of troublemaker characters.
1006 // Should these be merged into the title char list?
1007 $unicodeBlacklist = '/[' .
1008 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
1009 '\x{00a0}' . # non-breaking space
1010 '\x{2000}-\x{200f}' . # various whitespace
1011 '\x{2028}-\x{202f}' . # breaks and control chars
1012 '\x{3000}' . # ideographic space
1013 '\x{e000}-\x{f8ff}' . # private use
1015 if ( preg_match( $unicodeBlacklist, $name ) ) {
1023 * Usernames which fail to pass this function will be blocked
1024 * from user login and new account registrations, but may be used
1025 * internally by batch processes.
1027 * If an account already exists in this form, login will be blocked
1028 * by a failure to pass this function.
1030 * @param string $name Name to match
1033 public static function isUsableName( $name ) {
1034 global $wgReservedUsernames;
1035 // Must be a valid username, obviously ;)
1036 if ( !self
::isValidUserName( $name ) ) {
1040 static $reservedUsernames = false;
1041 if ( !$reservedUsernames ) {
1042 $reservedUsernames = $wgReservedUsernames;
1043 Hooks
::run( 'UserGetReservedNames', [ &$reservedUsernames ] );
1046 // Certain names may be reserved for batch processes.
1047 foreach ( $reservedUsernames as $reserved ) {
1048 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
1049 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
1051 if ( $reserved == $name ) {
1059 * Return the users who are members of the given group(s). In case of multiple groups,
1060 * users who are members of at least one of them are returned.
1062 * @param string|array $groups A single group name or an array of group names
1063 * @param int $limit Max number of users to return. The actual limit will never exceed 5000
1064 * records; larger values are ignored.
1065 * @param int $after ID the user to start after
1066 * @return UserArrayFromResult
1068 public static function findUsersByGroup( $groups, $limit = 5000, $after = null ) {
1069 if ( $groups === [] ) {
1070 return UserArrayFromResult
::newFromIDs( [] );
1073 $groups = array_unique( (array)$groups );
1074 $limit = min( 5000, $limit );
1076 $conds = [ 'ug_group' => $groups ];
1077 if ( $after !== null ) {
1078 $conds[] = 'ug_user > ' . (int)$after;
1081 $dbr = wfGetDB( DB_REPLICA
);
1082 $ids = $dbr->selectFieldValues(
1089 'ORDER BY' => 'ug_user',
1093 return UserArray
::newFromIDs( $ids );
1097 * Usernames which fail to pass this function will be blocked
1098 * from new account registrations, but may be used internally
1099 * either by batch processes or by user accounts which have
1100 * already been created.
1102 * Additional blacklisting may be added here rather than in
1103 * isValidUserName() to avoid disrupting existing accounts.
1105 * @param string $name String to match
1108 public static function isCreatableName( $name ) {
1109 global $wgInvalidUsernameCharacters;
1111 // Ensure that the username isn't longer than 235 bytes, so that
1112 // (at least for the builtin skins) user javascript and css files
1113 // will work. (T25080)
1114 if ( strlen( $name ) > 235 ) {
1115 wfDebugLog( 'username', __METHOD__
.
1116 ": '$name' invalid due to length" );
1120 // Preg yells if you try to give it an empty string
1121 if ( $wgInvalidUsernameCharacters !== '' ) {
1122 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
1123 wfDebugLog( 'username', __METHOD__
.
1124 ": '$name' invalid due to wgInvalidUsernameCharacters" );
1129 return self
::isUsableName( $name );
1133 * Is the input a valid password for this user?
1135 * @param string $password Desired password
1138 public function isValidPassword( $password ) {
1139 // simple boolean wrapper for getPasswordValidity
1140 return $this->getPasswordValidity( $password ) === true;
1144 * Given unvalidated password input, return error message on failure.
1146 * @param string $password Desired password
1147 * @return bool|string|array True on success, string or array of error message on failure
1149 public function getPasswordValidity( $password ) {
1150 $result = $this->checkPasswordValidity( $password );
1151 if ( $result->isGood() ) {
1155 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
1156 $messages[] = $error['message'];
1158 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
1159 $messages[] = $warning['message'];
1161 if ( count( $messages ) === 1 ) {
1162 return $messages[0];
1169 * Check if this is a valid password for this user
1171 * Create a Status object based on the password's validity.
1172 * The Status should be set to fatal if the user should not
1173 * be allowed to log in, and should have any errors that
1174 * would block changing the password.
1176 * If the return value of this is not OK, the password
1177 * should not be checked. If the return value is not Good,
1178 * the password can be checked, but the user should not be
1179 * able to set their password to this.
1181 * @param string $password Desired password
1185 public function checkPasswordValidity( $password ) {
1186 global $wgPasswordPolicy;
1188 $upp = new UserPasswordPolicy(
1189 $wgPasswordPolicy['policies'],
1190 $wgPasswordPolicy['checks']
1193 $status = Status
::newGood();
1194 $result = false; // init $result to false for the internal checks
1196 if ( !Hooks
::run( 'isValidPassword', [ $password, &$result, $this ] ) ) {
1197 $status->error( $result );
1201 if ( $result === false ) {
1202 $status->merge( $upp->checkUserPassword( $this, $password ) );
1204 } elseif ( $result === true ) {
1207 $status->error( $result );
1208 return $status; // the isValidPassword hook set a string $result and returned true
1213 * Given unvalidated user input, return a canonical username, or false if
1214 * the username is invalid.
1215 * @param string $name User input
1216 * @param string|bool $validate Type of validation to use:
1217 * - false No validation
1218 * - 'valid' Valid for batch processes
1219 * - 'usable' Valid for batch processes and login
1220 * - 'creatable' Valid for batch processes, login and account creation
1222 * @throws InvalidArgumentException
1223 * @return bool|string
1225 public static function getCanonicalName( $name, $validate = 'valid' ) {
1226 // Force usernames to capital
1228 $name = $wgContLang->ucfirst( $name );
1230 # Reject names containing '#'; these will be cleaned up
1231 # with title normalisation, but then it's too late to
1233 if ( strpos( $name, '#' ) !== false ) {
1237 // Clean up name according to title rules,
1238 // but only when validation is requested (T14654)
1239 $t = ( $validate !== false ) ?
1240 Title
::newFromText( $name, NS_USER
) : Title
::makeTitle( NS_USER
, $name );
1241 // Check for invalid titles
1242 if ( is_null( $t ) ||
$t->getNamespace() !== NS_USER ||
$t->isExternal() ) {
1246 // Reject various classes of invalid names
1247 $name = AuthManager
::callLegacyAuthPlugin(
1248 'getCanonicalName', [ $t->getText() ], $t->getText()
1251 switch ( $validate ) {
1255 if ( !self
::isValidUserName( $name ) ) {
1260 if ( !self
::isUsableName( $name ) ) {
1265 if ( !self
::isCreatableName( $name ) ) {
1270 throw new InvalidArgumentException(
1271 'Invalid parameter value for $validate in ' . __METHOD__
);
1277 * Return a random password.
1279 * @deprecated since 1.27, use PasswordFactory::generateRandomPasswordString()
1280 * @return string New random password
1282 public static function randomPassword() {
1283 global $wgMinimalPasswordLength;
1284 return PasswordFactory
::generateRandomPasswordString( $wgMinimalPasswordLength );
1288 * Set cached properties to default.
1290 * @note This no longer clears uncached lazy-initialised properties;
1291 * the constructor does that instead.
1293 * @param string|bool $name
1295 public function loadDefaults( $name = false ) {
1297 $this->mName
= $name;
1298 $this->mActorId
= null;
1299 $this->mRealName
= '';
1301 $this->mOptionOverrides
= null;
1302 $this->mOptionsLoaded
= false;
1304 $loggedOut = $this->mRequest
&& !defined( 'MW_NO_SESSION' )
1305 ?
$this->mRequest
->getSession()->getLoggedOutTimestamp() : 0;
1306 if ( $loggedOut !== 0 ) {
1307 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1309 $this->mTouched
= '1'; # Allow any pages to be cached
1312 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1313 $this->mEmailAuthenticated
= null;
1314 $this->mEmailToken
= '';
1315 $this->mEmailTokenExpires
= null;
1316 $this->mRegistration
= wfTimestamp( TS_MW
);
1317 $this->mGroupMemberships
= [];
1319 Hooks
::run( 'UserLoadDefaults', [ $this, $name ] );
1323 * Return whether an item has been loaded.
1325 * @param string $item Item to check. Current possibilities:
1329 * @param string $all 'all' to check if the whole object has been loaded
1330 * or any other string to check if only the item is available (e.g.
1334 public function isItemLoaded( $item, $all = 'all' ) {
1335 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1336 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1340 * Set that an item has been loaded
1342 * @param string $item
1344 protected function setItemLoaded( $item ) {
1345 if ( is_array( $this->mLoadedItems
) ) {
1346 $this->mLoadedItems
[$item] = true;
1351 * Load user data from the session.
1353 * @return bool True if the user is logged in, false otherwise.
1355 private function loadFromSession() {
1358 Hooks
::run( 'UserLoadFromSession', [ $this, &$result ], '1.27' );
1359 if ( $result !== null ) {
1363 // MediaWiki\Session\Session already did the necessary authentication of the user
1364 // returned here, so just use it if applicable.
1365 $session = $this->getRequest()->getSession();
1366 $user = $session->getUser();
1367 if ( $user->isLoggedIn() ) {
1368 $this->loadFromUserObject( $user );
1369 if ( $user->isBlocked() ) {
1370 // If this user is autoblocked, set a cookie to track the Block. This has to be done on
1371 // every session load, because an autoblocked editor might not edit again from the same
1372 // IP address after being blocked.
1373 $this->trackBlockWithCookie();
1376 // Other code expects these to be set in the session, so set them.
1377 $session->set( 'wsUserID', $this->getId() );
1378 $session->set( 'wsUserName', $this->getName() );
1379 $session->set( 'wsToken', $this->getToken() );
1388 * Set the 'BlockID' cookie depending on block type and user authentication status.
1390 public function trackBlockWithCookie() {
1391 $block = $this->getBlock();
1392 if ( $block && $this->getRequest()->getCookie( 'BlockID' ) === null ) {
1393 $config = RequestContext
::getMain()->getConfig();
1394 $shouldSetCookie = false;
1396 if ( $this->isAnon() && $config->get( 'CookieSetOnIpBlock' ) ) {
1397 // If user is logged-out, set a cookie to track the Block
1398 $shouldSetCookie = in_array( $block->getType(), [
1399 Block
::TYPE_IP
, Block
::TYPE_RANGE
1401 if ( $shouldSetCookie ) {
1402 $block->setCookie( $this->getRequest()->response() );
1404 // temporary measure the use of cookies on ip blocks
1405 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
1406 $stats->increment( 'block.ipblock.setCookie.success' );
1408 } elseif ( $this->isLoggedIn() && $config->get( 'CookieSetOnAutoblock' ) ) {
1409 $shouldSetCookie = $block->getType() === Block
::TYPE_USER
&& $block->isAutoblocking();
1410 if ( $shouldSetCookie ) {
1411 $block->setCookie( $this->getRequest()->response() );
1418 * Load user and user_group data from the database.
1419 * $this->mId must be set, this is how the user is identified.
1421 * @param int $flags User::READ_* constant bitfield
1422 * @return bool True if the user exists, false if the user is anonymous
1424 public function loadFromDatabase( $flags = self
::READ_LATEST
) {
1426 $this->mId
= intval( $this->mId
);
1428 if ( !$this->mId
) {
1429 // Anonymous users are not in the database
1430 $this->loadDefaults();
1434 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
1435 $db = wfGetDB( $index );
1437 $userQuery = self
::getQueryInfo();
1438 $s = $db->selectRow(
1439 $userQuery['tables'],
1440 $userQuery['fields'],
1441 [ 'user_id' => $this->mId
],
1447 $this->queryFlagsUsed
= $flags;
1448 Hooks
::run( 'UserLoadFromDatabase', [ $this, &$s ] );
1450 if ( $s !== false ) {
1451 // Initialise user table data
1452 $this->loadFromRow( $s );
1453 $this->mGroupMemberships
= null; // deferred
1454 $this->getEditCount(); // revalidation for nulls
1459 $this->loadDefaults();
1465 * Initialize this object from a row from the user table.
1467 * @param stdClass $row Row from the user table to load.
1468 * @param array $data Further user data to load into the object
1470 * user_groups Array of arrays or stdClass result rows out of the user_groups
1471 * table. Previously you were supposed to pass an array of strings
1472 * here, but we also need expiry info nowadays, so an array of
1473 * strings is ignored.
1474 * user_properties Array with properties out of the user_properties table
1476 protected function loadFromRow( $row, $data = null ) {
1477 global $wgActorTableSchemaMigrationStage;
1479 if ( !is_object( $row ) ) {
1480 throw new InvalidArgumentException( '$row must be an object' );
1485 $this->mGroupMemberships
= null; // deferred
1487 if ( $wgActorTableSchemaMigrationStage > MIGRATION_OLD
) {
1488 if ( isset( $row->actor_id
) ) {
1489 $this->mActorId
= (int)$row->actor_id
;
1490 if ( $this->mActorId
!== 0 ) {
1491 $this->mFrom
= 'actor';
1493 $this->setItemLoaded( 'actor' );
1499 if ( isset( $row->user_name
) && $row->user_name
!== '' ) {
1500 $this->mName
= $row->user_name
;
1501 $this->mFrom
= 'name';
1502 $this->setItemLoaded( 'name' );
1507 if ( isset( $row->user_real_name
) ) {
1508 $this->mRealName
= $row->user_real_name
;
1509 $this->setItemLoaded( 'realname' );
1514 if ( isset( $row->user_id
) ) {
1515 $this->mId
= intval( $row->user_id
);
1516 if ( $this->mId
!== 0 ) {
1517 $this->mFrom
= 'id';
1519 $this->setItemLoaded( 'id' );
1524 if ( isset( $row->user_id
) && isset( $row->user_name
) && $row->user_name
!== '' ) {
1525 self
::$idCacheByName[$row->user_name
] = $row->user_id
;
1528 if ( isset( $row->user_editcount
) ) {
1529 $this->mEditCount
= $row->user_editcount
;
1534 if ( isset( $row->user_touched
) ) {
1535 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1540 if ( isset( $row->user_token
) ) {
1541 // The definition for the column is binary(32), so trim the NULs
1542 // that appends. The previous definition was char(32), so trim
1544 $this->mToken
= rtrim( $row->user_token
, " \0" );
1545 if ( $this->mToken
=== '' ) {
1546 $this->mToken
= null;
1552 if ( isset( $row->user_email
) ) {
1553 $this->mEmail
= $row->user_email
;
1554 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1555 $this->mEmailToken
= $row->user_email_token
;
1556 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1557 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1563 $this->mLoadedItems
= true;
1566 if ( is_array( $data ) ) {
1567 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1568 if ( !count( $data['user_groups'] ) ) {
1569 $this->mGroupMemberships
= [];
1571 $firstGroup = reset( $data['user_groups'] );
1572 if ( is_array( $firstGroup ) ||
is_object( $firstGroup ) ) {
1573 $this->mGroupMemberships
= [];
1574 foreach ( $data['user_groups'] as $row ) {
1575 $ugm = UserGroupMembership
::newFromRow( (object)$row );
1576 $this->mGroupMemberships
[$ugm->getGroup()] = $ugm;
1581 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1582 $this->loadOptions( $data['user_properties'] );
1588 * Load the data for this user object from another user object.
1592 protected function loadFromUserObject( $user ) {
1594 foreach ( self
::$mCacheVars as $var ) {
1595 $this->$var = $user->$var;
1600 * Load the groups from the database if they aren't already loaded.
1602 private function loadGroups() {
1603 if ( is_null( $this->mGroupMemberships
) ) {
1604 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
1605 ?
wfGetDB( DB_MASTER
)
1606 : wfGetDB( DB_REPLICA
);
1607 $this->mGroupMemberships
= UserGroupMembership
::getMembershipsForUser(
1613 * Add the user to the group if he/she meets given criteria.
1615 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1616 * possible to remove manually via Special:UserRights. In such case it
1617 * will not be re-added automatically. The user will also not lose the
1618 * group if they no longer meet the criteria.
1620 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1622 * @return array Array of groups the user has been promoted to.
1624 * @see $wgAutopromoteOnce
1626 public function addAutopromoteOnceGroups( $event ) {
1627 global $wgAutopromoteOnceLogInRC;
1629 if ( wfReadOnly() ||
!$this->getId() ) {
1633 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1634 if ( !count( $toPromote ) ) {
1638 if ( !$this->checkAndSetTouched() ) {
1639 return []; // raced out (bug T48834)
1642 $oldGroups = $this->getGroups(); // previous groups
1643 $oldUGMs = $this->getGroupMemberships();
1644 foreach ( $toPromote as $group ) {
1645 $this->addGroup( $group );
1647 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1648 $newUGMs = $this->getGroupMemberships();
1650 // update groups in external authentication database
1651 Hooks
::run( 'UserGroupsChanged', [ $this, $toPromote, [], false, false, $oldUGMs, $newUGMs ] );
1652 AuthManager
::callLegacyAuthPlugin( 'updateExternalDBGroups', [ $this, $toPromote ] );
1654 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1655 $logEntry->setPerformer( $this );
1656 $logEntry->setTarget( $this->getUserPage() );
1657 $logEntry->setParameters( [
1658 '4::oldgroups' => $oldGroups,
1659 '5::newgroups' => $newGroups,
1661 $logid = $logEntry->insert();
1662 if ( $wgAutopromoteOnceLogInRC ) {
1663 $logEntry->publish( $logid );
1670 * Builds update conditions. Additional conditions may be added to $conditions to
1671 * protected against race conditions using a compare-and-set (CAS) mechanism
1672 * based on comparing $this->mTouched with the user_touched field.
1674 * @param Database $db
1675 * @param array $conditions WHERE conditions for use with Database::update
1676 * @return array WHERE conditions for use with Database::update
1678 protected function makeUpdateConditions( Database
$db, array $conditions ) {
1679 if ( $this->mTouched
) {
1680 // CAS check: only update if the row wasn't changed sicne it was loaded.
1681 $conditions['user_touched'] = $db->timestamp( $this->mTouched
);
1688 * Bump user_touched if it didn't change since this object was loaded
1690 * On success, the mTouched field is updated.
1691 * The user serialization cache is always cleared.
1693 * @return bool Whether user_touched was actually updated
1696 protected function checkAndSetTouched() {
1699 if ( !$this->mId
) {
1700 return false; // anon
1703 // Get a new user_touched that is higher than the old one
1704 $newTouched = $this->newTouchedTimestamp();
1706 $dbw = wfGetDB( DB_MASTER
);
1707 $dbw->update( 'user',
1708 [ 'user_touched' => $dbw->timestamp( $newTouched ) ],
1709 $this->makeUpdateConditions( $dbw, [
1710 'user_id' => $this->mId
,
1714 $success = ( $dbw->affectedRows() > 0 );
1717 $this->mTouched
= $newTouched;
1718 $this->clearSharedCache();
1720 // Clears on failure too since that is desired if the cache is stale
1721 $this->clearSharedCache( 'refresh' );
1728 * Clear various cached data stored in this object. The cache of the user table
1729 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1731 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1732 * given source. May be "name", "id", "actor", "defaults", "session", or false for no reload.
1734 public function clearInstanceCache( $reloadFrom = false ) {
1735 $this->mNewtalk
= -1;
1736 $this->mDatePreference
= null;
1737 $this->mBlockedby
= -1; # Unset
1738 $this->mHash
= false;
1739 $this->mRights
= null;
1740 $this->mEffectiveGroups
= null;
1741 $this->mImplicitGroups
= null;
1742 $this->mGroupMemberships
= null;
1743 $this->mOptions
= null;
1744 $this->mOptionsLoaded
= false;
1745 $this->mEditCount
= null;
1747 if ( $reloadFrom ) {
1748 $this->mLoadedItems
= [];
1749 $this->mFrom
= $reloadFrom;
1754 * Combine the language default options with any site-specific options
1755 * and add the default language variants.
1757 * @return array Array of String options
1759 public static function getDefaultOptions() {
1760 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1762 static $defOpt = null;
1763 static $defOptLang = null;
1765 if ( $defOpt !== null && $defOptLang === $wgContLang->getCode() ) {
1766 // $wgContLang does not change (and should not change) mid-request,
1767 // but the unit tests change it anyway, and expect this method to
1768 // return values relevant to the current $wgContLang.
1772 $defOpt = $wgDefaultUserOptions;
1773 // Default language setting
1774 $defOptLang = $wgContLang->getCode();
1775 $defOpt['language'] = $defOptLang;
1776 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1777 $defOpt[$langCode == $wgContLang->getCode() ?
'variant' : "variant-$langCode"] = $langCode;
1780 // NOTE: don't use SearchEngineConfig::getSearchableNamespaces here,
1781 // since extensions may change the set of searchable namespaces depending
1782 // on user groups/permissions.
1783 foreach ( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
1784 $defOpt['searchNs' . $nsnum] = (bool)$val;
1786 $defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1788 Hooks
::run( 'UserGetDefaultOptions', [ &$defOpt ] );
1794 * Get a given default option value.
1796 * @param string $opt Name of option to retrieve
1797 * @return string Default option value
1799 public static function getDefaultOption( $opt ) {
1800 $defOpts = self
::getDefaultOptions();
1801 if ( isset( $defOpts[$opt] ) ) {
1802 return $defOpts[$opt];
1809 * Get blocking information
1810 * @param bool $bFromSlave Whether to check the replica DB first.
1811 * To improve performance, non-critical checks are done against replica DBs.
1812 * Check when actually saving should be done against master.
1814 private function getBlockedStatus( $bFromSlave = true ) {
1815 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff, $wgSoftBlockRanges;
1817 if ( -1 != $this->mBlockedby
) {
1821 wfDebug( __METHOD__
. ": checking...\n" );
1823 // Initialize data...
1824 // Otherwise something ends up stomping on $this->mBlockedby when
1825 // things get lazy-loaded later, causing false positive block hits
1826 // due to -1 !== 0. Probably session-related... Nothing should be
1827 // overwriting mBlockedby, surely?
1830 # We only need to worry about passing the IP address to the Block generator if the
1831 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1832 # know which IP address they're actually coming from
1834 if ( !$this->isAllowed( 'ipblock-exempt' ) ) {
1835 // $wgUser->getName() only works after the end of Setup.php. Until
1836 // then, assume it's a logged-out user.
1837 $globalUserName = $wgUser->isSafeToLoad()
1838 ?
$wgUser->getName()
1839 : IP
::sanitizeIP( $wgUser->getRequest()->getIP() );
1840 if ( $this->getName() === $globalUserName ) {
1841 $ip = $this->getRequest()->getIP();
1846 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1849 if ( !$block instanceof Block
) {
1850 $block = $this->getBlockFromCookieValue( $this->getRequest()->getCookie( 'BlockID' ) );
1854 if ( !$block instanceof Block
&& $ip !== null && !in_array( $ip, $wgProxyWhitelist ) ) {
1856 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1857 $block = new Block( [
1858 'byText' => wfMessage( 'proxyblocker' )->text(),
1859 'reason' => wfMessage( 'proxyblockreason' )->plain(),
1861 'systemBlock' => 'proxy',
1863 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1864 $block = new Block( [
1865 'byText' => wfMessage( 'sorbs' )->text(),
1866 'reason' => wfMessage( 'sorbsreason' )->plain(),
1868 'systemBlock' => 'dnsbl',
1873 // (T25343) Apply IP blocks to the contents of XFF headers, if enabled
1874 if ( !$block instanceof Block
1875 && $wgApplyIpBlocksToXff
1877 && !in_array( $ip, $wgProxyWhitelist )
1879 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1880 $xff = array_map( 'trim', explode( ',', $xff ) );
1881 $xff = array_diff( $xff, [ $ip ] );
1882 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1883 $block = Block
::chooseBlock( $xffblocks, $xff );
1884 if ( $block instanceof Block
) {
1885 # Mangle the reason to alert the user that the block
1886 # originated from matching the X-Forwarded-For header.
1887 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->plain();
1891 if ( !$block instanceof Block
1894 && IP
::isInRanges( $ip, $wgSoftBlockRanges )
1896 $block = new Block( [
1898 'byText' => 'MediaWiki default',
1899 'reason' => wfMessage( 'softblockrangesreason', $ip )->plain(),
1901 'systemBlock' => 'wgSoftBlockRanges',
1905 if ( $block instanceof Block
) {
1906 wfDebug( __METHOD__
. ": Found block.\n" );
1907 $this->mBlock
= $block;
1908 $this->mBlockedby
= $block->getByName();
1909 $this->mBlockreason
= $block->mReason
;
1910 $this->mHideName
= $block->mHideName
;
1911 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1913 $this->mBlock
= null;
1914 $this->mBlockedby
= '';
1915 $this->mBlockreason
= '';
1916 $this->mHideName
= 0;
1917 $this->mAllowUsertalk
= false;
1920 // Avoid PHP 7.1 warning of passing $this by reference
1923 Hooks
::run( 'GetBlockedStatus', [ &$user ] );
1927 * Try to load a Block from an ID given in a cookie value.
1928 * @param string|null $blockCookieVal The cookie value to check.
1929 * @return Block|bool The Block object, or false if none could be loaded.
1931 protected function getBlockFromCookieValue( $blockCookieVal ) {
1932 // Make sure there's something to check. The cookie value must start with a number.
1933 if ( strlen( $blockCookieVal ) < 1 ||
!is_numeric( substr( $blockCookieVal, 0, 1 ) ) ) {
1936 // Load the Block from the ID in the cookie.
1937 $blockCookieId = Block
::getIdFromCookieValue( $blockCookieVal );
1938 if ( $blockCookieId !== null ) {
1939 // An ID was found in the cookie.
1940 $tmpBlock = Block
::newFromID( $blockCookieId );
1941 if ( $tmpBlock instanceof Block
) {
1942 $config = RequestContext
::getMain()->getConfig();
1944 switch ( $tmpBlock->getType() ) {
1945 case Block
::TYPE_USER
:
1946 $blockIsValid = !$tmpBlock->isExpired() && $tmpBlock->isAutoblocking();
1947 $useBlockCookie = ( $config->get( 'CookieSetOnAutoblock' ) === true );
1949 case Block
::TYPE_IP
:
1950 case Block
::TYPE_RANGE
:
1951 // If block is type IP or IP range, load only if user is not logged in (T152462)
1952 $blockIsValid = !$tmpBlock->isExpired() && !$this->isLoggedIn();
1953 $useBlockCookie = ( $config->get( 'CookieSetOnIpBlock' ) === true );
1956 $blockIsValid = false;
1957 $useBlockCookie = false;
1960 if ( $blockIsValid && $useBlockCookie ) {
1964 // If the block is not valid, remove the cookie.
1965 Block
::clearCookie( $this->getRequest()->response() );
1968 // If the block doesn't exist, remove the cookie.
1969 Block
::clearCookie( $this->getRequest()->response() );
1976 * Whether the given IP is in a DNS blacklist.
1978 * @param string $ip IP to check
1979 * @param bool $checkWhitelist Whether to check the whitelist first
1980 * @return bool True if blacklisted.
1982 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1983 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1985 if ( !$wgEnableDnsBlacklist ) {
1989 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1993 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1997 * Whether the given IP is in a given DNS blacklist.
1999 * @param string $ip IP to check
2000 * @param string|array $bases Array of Strings: URL of the DNS blacklist
2001 * @return bool True if blacklisted.
2003 public function inDnsBlacklist( $ip, $bases ) {
2005 // @todo FIXME: IPv6 ??? (https://bugs.php.net/bug.php?id=33170)
2006 if ( IP
::isIPv4( $ip ) ) {
2007 // Reverse IP, T23255
2008 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
2010 foreach ( (array)$bases as $base ) {
2012 // If we have an access key, use that too (ProjectHoneypot, etc.)
2014 if ( is_array( $base ) ) {
2015 if ( count( $base ) >= 2 ) {
2016 // Access key is 1, base URL is 0
2017 $host = "{$base[1]}.$ipReversed.{$base[0]}";
2019 $host = "$ipReversed.{$base[0]}";
2021 $basename = $base[0];
2023 $host = "$ipReversed.$base";
2027 $ipList = gethostbynamel( $host );
2030 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
2034 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
2043 * Check if an IP address is in the local proxy list
2049 public static function isLocallyBlockedProxy( $ip ) {
2050 global $wgProxyList;
2052 if ( !$wgProxyList ) {
2056 if ( !is_array( $wgProxyList ) ) {
2057 // Load values from the specified file
2058 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
2061 $resultProxyList = [];
2062 $deprecatedIPEntries = [];
2064 // backward compatibility: move all ip addresses in keys to values
2065 foreach ( $wgProxyList as $key => $value ) {
2066 $keyIsIP = IP
::isIPAddress( $key );
2067 $valueIsIP = IP
::isIPAddress( $value );
2068 if ( $keyIsIP && !$valueIsIP ) {
2069 $deprecatedIPEntries[] = $key;
2070 $resultProxyList[] = $key;
2071 } elseif ( $keyIsIP && $valueIsIP ) {
2072 $deprecatedIPEntries[] = $key;
2073 $resultProxyList[] = $key;
2074 $resultProxyList[] = $value;
2076 $resultProxyList[] = $value;
2080 if ( $deprecatedIPEntries ) {
2082 'IP addresses in the keys of $wgProxyList (found the following IP addresses in keys: ' .
2083 implode( ', ', $deprecatedIPEntries ) . ', please move them to values)', '1.30' );
2086 $proxyListIPSet = new IPSet( $resultProxyList );
2087 return $proxyListIPSet->match( $ip );
2091 * Is this user subject to rate limiting?
2093 * @return bool True if rate limited
2095 public function isPingLimitable() {
2096 global $wgRateLimitsExcludedIPs;
2097 if ( IP
::isInRanges( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
2098 // No other good way currently to disable rate limits
2099 // for specific IPs. :P
2100 // But this is a crappy hack and should die.
2103 return !$this->isAllowed( 'noratelimit' );
2107 * Primitive rate limits: enforce maximum actions per time period
2108 * to put a brake on flooding.
2110 * The method generates both a generic profiling point and a per action one
2111 * (suffix being "-$action".
2113 * @note When using a shared cache like memcached, IP-address
2114 * last-hit counters will be shared across wikis.
2116 * @param string $action Action to enforce; 'edit' if unspecified
2117 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
2118 * @return bool True if a rate limiter was tripped
2120 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
2121 // Avoid PHP 7.1 warning of passing $this by reference
2123 // Call the 'PingLimiter' hook
2125 if ( !Hooks
::run( 'PingLimiter', [ &$user, $action, &$result, $incrBy ] ) ) {
2129 global $wgRateLimits;
2130 if ( !isset( $wgRateLimits[$action] ) ) {
2134 $limits = array_merge(
2135 [ '&can-bypass' => true ],
2136 $wgRateLimits[$action]
2139 // Some groups shouldn't trigger the ping limiter, ever
2140 if ( $limits['&can-bypass'] && !$this->isPingLimitable() ) {
2145 $id = $this->getId();
2147 $isNewbie = $this->isNewbie();
2148 $cache = ObjectCache
::getLocalClusterInstance();
2152 if ( isset( $limits['anon'] ) ) {
2153 $keys[$cache->makeKey( 'limiter', $action, 'anon' )] = $limits['anon'];
2156 // limits for logged-in users
2157 if ( isset( $limits['user'] ) ) {
2158 $userLimit = $limits['user'];
2160 // limits for newbie logged-in users
2161 if ( $isNewbie && isset( $limits['newbie'] ) ) {
2162 $keys[$cache->makeKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
2166 // limits for anons and for newbie logged-in users
2169 if ( isset( $limits['ip'] ) ) {
2170 $ip = $this->getRequest()->getIP();
2171 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
2173 // subnet-based limits
2174 if ( isset( $limits['subnet'] ) ) {
2175 $ip = $this->getRequest()->getIP();
2176 $subnet = IP
::getSubnet( $ip );
2177 if ( $subnet !== false ) {
2178 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
2183 // Check for group-specific permissions
2184 // If more than one group applies, use the group with the highest limit ratio (max/period)
2185 foreach ( $this->getGroups() as $group ) {
2186 if ( isset( $limits[$group] ) ) {
2187 if ( $userLimit === false
2188 ||
$limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
2190 $userLimit = $limits[$group];
2195 // Set the user limit key
2196 if ( $userLimit !== false ) {
2197 list( $max, $period ) = $userLimit;
2198 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
2199 $keys[$cache->makeKey( 'limiter', $action, 'user', $id )] = $userLimit;
2202 // ip-based limits for all ping-limitable users
2203 if ( isset( $limits['ip-all'] ) ) {
2204 $ip = $this->getRequest()->getIP();
2205 // ignore if user limit is more permissive
2206 if ( $isNewbie ||
$userLimit === false
2207 ||
$limits['ip-all'][0] / $limits['ip-all'][1] > $userLimit[0] / $userLimit[1] ) {
2208 $keys["mediawiki:limiter:$action:ip-all:$ip"] = $limits['ip-all'];
2212 // subnet-based limits for all ping-limitable users
2213 if ( isset( $limits['subnet-all'] ) ) {
2214 $ip = $this->getRequest()->getIP();
2215 $subnet = IP
::getSubnet( $ip );
2216 if ( $subnet !== false ) {
2217 // ignore if user limit is more permissive
2218 if ( $isNewbie ||
$userLimit === false
2219 ||
$limits['ip-all'][0] / $limits['ip-all'][1]
2220 > $userLimit[0] / $userLimit[1] ) {
2221 $keys["mediawiki:limiter:$action:subnet-all:$subnet"] = $limits['subnet-all'];
2227 foreach ( $keys as $key => $limit ) {
2228 list( $max, $period ) = $limit;
2229 $summary = "(limit $max in {$period}s)";
2230 $count = $cache->get( $key );
2233 if ( $count >= $max ) {
2234 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
2235 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
2238 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
2241 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
2242 if ( $incrBy > 0 ) {
2243 $cache->add( $key, 0, intval( $period ) ); // first ping
2246 if ( $incrBy > 0 ) {
2247 $cache->incr( $key, $incrBy );
2255 * Check if user is blocked
2257 * @param bool $bFromSlave Whether to check the replica DB instead of
2258 * the master. Hacked from false due to horrible probs on site.
2259 * @return bool True if blocked, false otherwise
2261 public function isBlocked( $bFromSlave = true ) {
2262 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
2266 * Get the block affecting the user, or null if the user is not blocked
2268 * @param bool $bFromSlave Whether to check the replica DB instead of the master
2269 * @return Block|null
2271 public function getBlock( $bFromSlave = true ) {
2272 $this->getBlockedStatus( $bFromSlave );
2273 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
2277 * Check if user is blocked from editing a particular article
2279 * @param Title $title Title to check
2280 * @param bool $bFromSlave Whether to check the replica DB instead of the master
2283 public function isBlockedFrom( $title, $bFromSlave = false ) {
2284 global $wgBlockAllowsUTEdit;
2286 $blocked = $this->isBlocked( $bFromSlave );
2287 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
2288 // If a user's name is suppressed, they cannot make edits anywhere
2289 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName()
2290 && $title->getNamespace() == NS_USER_TALK
) {
2292 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
2295 Hooks
::run( 'UserIsBlockedFrom', [ $this, $title, &$blocked, &$allowUsertalk ] );
2301 * If user is blocked, return the name of the user who placed the block
2302 * @return string Name of blocker
2304 public function blockedBy() {
2305 $this->getBlockedStatus();
2306 return $this->mBlockedby
;
2310 * If user is blocked, return the specified reason for the block
2311 * @return string Blocking reason
2313 public function blockedFor() {
2314 $this->getBlockedStatus();
2315 return $this->mBlockreason
;
2319 * If user is blocked, return the ID for the block
2320 * @return int Block ID
2322 public function getBlockId() {
2323 $this->getBlockedStatus();
2324 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
2328 * Check if user is blocked on all wikis.
2329 * Do not use for actual edit permission checks!
2330 * This is intended for quick UI checks.
2332 * @param string $ip IP address, uses current client if none given
2333 * @return bool True if blocked, false otherwise
2335 public function isBlockedGlobally( $ip = '' ) {
2336 return $this->getGlobalBlock( $ip ) instanceof Block
;
2340 * Check if user is blocked on all wikis.
2341 * Do not use for actual edit permission checks!
2342 * This is intended for quick UI checks.
2344 * @param string $ip IP address, uses current client if none given
2345 * @return Block|null Block object if blocked, null otherwise
2346 * @throws FatalError
2347 * @throws MWException
2349 public function getGlobalBlock( $ip = '' ) {
2350 if ( $this->mGlobalBlock
!== null ) {
2351 return $this->mGlobalBlock ?
: null;
2353 // User is already an IP?
2354 if ( IP
::isIPAddress( $this->getName() ) ) {
2355 $ip = $this->getName();
2357 $ip = $this->getRequest()->getIP();
2359 // Avoid PHP 7.1 warning of passing $this by reference
2363 Hooks
::run( 'UserIsBlockedGlobally', [ &$user, $ip, &$blocked, &$block ] );
2365 if ( $blocked && $block === null ) {
2366 // back-compat: UserIsBlockedGlobally didn't have $block param first
2367 $block = new Block( [
2369 'systemBlock' => 'global-block'
2373 $this->mGlobalBlock
= $blocked ?
$block : false;
2374 return $this->mGlobalBlock ?
: null;
2378 * Check if user account is locked
2380 * @return bool True if locked, false otherwise
2382 public function isLocked() {
2383 if ( $this->mLocked
!== null ) {
2384 return $this->mLocked
;
2386 // Avoid PHP 7.1 warning of passing $this by reference
2388 $authUser = AuthManager
::callLegacyAuthPlugin( 'getUserInstance', [ &$user ], null );
2389 $this->mLocked
= $authUser && $authUser->isLocked();
2390 Hooks
::run( 'UserIsLocked', [ $this, &$this->mLocked
] );
2391 return $this->mLocked
;
2395 * Check if user account is hidden
2397 * @return bool True if hidden, false otherwise
2399 public function isHidden() {
2400 if ( $this->mHideName
!== null ) {
2401 return $this->mHideName
;
2403 $this->getBlockedStatus();
2404 if ( !$this->mHideName
) {
2405 // Avoid PHP 7.1 warning of passing $this by reference
2407 $authUser = AuthManager
::callLegacyAuthPlugin( 'getUserInstance', [ &$user ], null );
2408 $this->mHideName
= $authUser && $authUser->isHidden();
2409 Hooks
::run( 'UserIsHidden', [ $this, &$this->mHideName
] );
2411 return $this->mHideName
;
2415 * Get the user's ID.
2416 * @return int The user's ID; 0 if the user is anonymous or nonexistent
2418 public function getId() {
2419 if ( $this->mId
=== null && $this->mName
!== null && self
::isIP( $this->mName
) ) {
2420 // Special case, we know the user is anonymous
2422 } elseif ( !$this->isItemLoaded( 'id' ) ) {
2423 // Don't load if this was initialized from an ID
2427 return (int)$this->mId
;
2431 * Set the user and reload all fields according to a given ID
2432 * @param int $v User ID to reload
2434 public function setId( $v ) {
2436 $this->clearInstanceCache( 'id' );
2440 * Get the user name, or the IP of an anonymous user
2441 * @return string User's name or IP address
2443 public function getName() {
2444 if ( $this->isItemLoaded( 'name', 'only' ) ) {
2445 // Special case optimisation
2446 return $this->mName
;
2449 if ( $this->mName
=== false ) {
2451 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
2453 return $this->mName
;
2458 * Set the user name.
2460 * This does not reload fields from the database according to the given
2461 * name. Rather, it is used to create a temporary "nonexistent user" for
2462 * later addition to the database. It can also be used to set the IP
2463 * address for an anonymous user to something other than the current
2466 * @note User::newFromName() has roughly the same function, when the named user
2468 * @param string $str New user name to set
2470 public function setName( $str ) {
2472 $this->mName
= $str;
2476 * Get the user's actor ID.
2478 * @param IDatabase|null $dbw Assign a new actor ID, using this DB handle, if none exists
2479 * @return int The actor's ID, or 0 if no actor ID exists and $dbw was null
2481 public function getActorId( IDatabase
$dbw = null ) {
2482 global $wgActorTableSchemaMigrationStage;
2484 if ( $wgActorTableSchemaMigrationStage <= MIGRATION_OLD
) {
2488 if ( !$this->isItemLoaded( 'actor' ) ) {
2492 // Currently $this->mActorId might be null if $this was loaded from a
2493 // cache entry that was written when $wgActorTableSchemaMigrationStage
2494 // was MIGRATION_OLD. Once that is no longer a possibility (i.e. when
2495 // User::VERSION is incremented after $wgActorTableSchemaMigrationStage
2496 // has been removed), that condition may be removed.
2497 if ( $this->mActorId
=== null ||
!$this->mActorId
&& $dbw ) {
2499 'actor_user' => $this->getId() ?
: null,
2500 'actor_name' => (string)$this->getName(),
2503 if ( $q['actor_user'] === null && self
::isUsableName( $q['actor_name'] ) ) {
2504 throw new CannotCreateActorException(
2505 'Cannot create an actor for a usable name that is not an existing user'
2508 if ( $q['actor_name'] === '' ) {
2509 throw new CannotCreateActorException( 'Cannot create an actor for a user with no name' );
2511 $dbw->insert( 'actor', $q, __METHOD__
, [ 'IGNORE' ] );
2512 if ( $dbw->affectedRows() ) {
2513 $this->mActorId
= (int)$dbw->insertId();
2516 list( , $options ) = DBAccessObjectUtils
::getDBOptions( $this->queryFlagsUsed
);
2517 $this->mActorId
= (int)$dbw->selectField( 'actor', 'actor_id', $q, __METHOD__
, $options );
2518 if ( !$this->mActorId
) {
2519 throw new CannotCreateActorException(
2520 "Cannot create actor ID for user_id={$this->getId()} user_name={$this->getName()}"
2524 $this->invalidateCache();
2526 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $this->queryFlagsUsed
);
2527 $db = wfGetDB( $index );
2528 $this->mActorId
= (int)$db->selectField( 'actor', 'actor_id', $q, __METHOD__
, $options );
2530 $this->setItemLoaded( 'actor' );
2533 return (int)$this->mActorId
;
2537 * Get the user's name escaped by underscores.
2538 * @return string Username escaped by underscores.
2540 public function getTitleKey() {
2541 return str_replace( ' ', '_', $this->getName() );
2545 * Check if the user has new messages.
2546 * @return bool True if the user has new messages
2548 public function getNewtalk() {
2551 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2552 if ( $this->mNewtalk
=== -1 ) {
2553 $this->mNewtalk
= false; # reset talk page status
2555 // Check memcached separately for anons, who have no
2556 // entire User object stored in there.
2557 if ( !$this->mId
) {
2558 global $wgDisableAnonTalk;
2559 if ( $wgDisableAnonTalk ) {
2560 // Anon newtalk disabled by configuration.
2561 $this->mNewtalk
= false;
2563 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
2566 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2570 return (bool)$this->mNewtalk
;
2574 * Return the data needed to construct links for new talk page message
2575 * alerts. If there are new messages, this will return an associative array
2576 * with the following data:
2577 * wiki: The database name of the wiki
2578 * link: Root-relative link to the user's talk page
2579 * rev: The last talk page revision that the user has seen or null. This
2580 * is useful for building diff links.
2581 * If there are no new messages, it returns an empty array.
2582 * @note This function was designed to accomodate multiple talk pages, but
2583 * currently only returns a single link and revision.
2586 public function getNewMessageLinks() {
2587 // Avoid PHP 7.1 warning of passing $this by reference
2590 if ( !Hooks
::run( 'UserRetrieveNewTalks', [ &$user, &$talks ] ) ) {
2592 } elseif ( !$this->getNewtalk() ) {
2595 $utp = $this->getTalkPage();
2596 $dbr = wfGetDB( DB_REPLICA
);
2597 // Get the "last viewed rev" timestamp from the oldest message notification
2598 $timestamp = $dbr->selectField( 'user_newtalk',
2599 'MIN(user_last_timestamp)',
2600 $this->isAnon() ?
[ 'user_ip' => $this->getName() ] : [ 'user_id' => $this->getId() ],
2602 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2603 return [ [ 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ] ];
2607 * Get the revision ID for the last talk page revision viewed by the talk
2609 * @return int|null Revision ID or null
2611 public function getNewMessageRevisionId() {
2612 $newMessageRevisionId = null;
2613 $newMessageLinks = $this->getNewMessageLinks();
2614 if ( $newMessageLinks ) {
2615 // Note: getNewMessageLinks() never returns more than a single link
2616 // and it is always for the same wiki, but we double-check here in
2617 // case that changes some time in the future.
2618 if ( count( $newMessageLinks ) === 1
2619 && $newMessageLinks[0]['wiki'] === wfWikiID()
2620 && $newMessageLinks[0]['rev']
2622 /** @var Revision $newMessageRevision */
2623 $newMessageRevision = $newMessageLinks[0]['rev'];
2624 $newMessageRevisionId = $newMessageRevision->getId();
2627 return $newMessageRevisionId;
2631 * Internal uncached check for new messages
2634 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2635 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2636 * @return bool True if the user has new messages
2638 protected function checkNewtalk( $field, $id ) {
2639 $dbr = wfGetDB( DB_REPLICA
);
2641 $ok = $dbr->selectField( 'user_newtalk', $field, [ $field => $id ], __METHOD__
);
2643 return $ok !== false;
2647 * Add or update the new messages flag
2648 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2649 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2650 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2651 * @return bool True if successful, false otherwise
2653 protected function updateNewtalk( $field, $id, $curRev = null ) {
2654 // Get timestamp of the talk page revision prior to the current one
2655 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2656 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2657 // Mark the user as having new messages since this revision
2658 $dbw = wfGetDB( DB_MASTER
);
2659 $dbw->insert( 'user_newtalk',
2660 [ $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ],
2663 if ( $dbw->affectedRows() ) {
2664 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2667 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2673 * Clear the new messages flag for the given user
2674 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2675 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2676 * @return bool True if successful, false otherwise
2678 protected function deleteNewtalk( $field, $id ) {
2679 $dbw = wfGetDB( DB_MASTER
);
2680 $dbw->delete( 'user_newtalk',
2683 if ( $dbw->affectedRows() ) {
2684 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2687 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2693 * Update the 'You have new messages!' status.
2694 * @param bool $val Whether the user has new messages
2695 * @param Revision $curRev New, as yet unseen revision of the user talk
2696 * page. Ignored if null or !$val.
2698 public function setNewtalk( $val, $curRev = null ) {
2699 if ( wfReadOnly() ) {
2704 $this->mNewtalk
= $val;
2706 if ( $this->isAnon() ) {
2708 $id = $this->getName();
2711 $id = $this->getId();
2715 $changed = $this->updateNewtalk( $field, $id, $curRev );
2717 $changed = $this->deleteNewtalk( $field, $id );
2721 $this->invalidateCache();
2726 * Generate a current or new-future timestamp to be stored in the
2727 * user_touched field when we update things.
2728 * @return string Timestamp in TS_MW format
2730 private function newTouchedTimestamp() {
2731 global $wgClockSkewFudge;
2733 $time = wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2734 if ( $this->mTouched
&& $time <= $this->mTouched
) {
2735 $time = wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $this->mTouched
) +
1 );
2742 * Clear user data from memcached
2744 * Use after applying updates to the database; caller's
2745 * responsibility to update user_touched if appropriate.
2747 * Called implicitly from invalidateCache() and saveSettings().
2749 * @param string $mode Use 'refresh' to clear now; otherwise before DB commit
2751 public function clearSharedCache( $mode = 'changed' ) {
2752 if ( !$this->getId() ) {
2756 $cache = ObjectCache
::getMainWANInstance();
2757 $key = $this->getCacheKey( $cache );
2758 if ( $mode === 'refresh' ) {
2759 $cache->delete( $key, 1 );
2761 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
2762 if ( $lb->hasOrMadeRecentMasterChanges() ) {
2763 $lb->getConnection( DB_MASTER
)->onTransactionPreCommitOrIdle(
2764 function () use ( $cache, $key ) {
2765 $cache->delete( $key );
2770 $cache->delete( $key );
2776 * Immediately touch the user data cache for this account
2778 * Calls touch() and removes account data from memcached
2780 public function invalidateCache() {
2782 $this->clearSharedCache();
2786 * Update the "touched" timestamp for the user
2788 * This is useful on various login/logout events when making sure that
2789 * a browser or proxy that has multiple tenants does not suffer cache
2790 * pollution where the new user sees the old users content. The value
2791 * of getTouched() is checked when determining 304 vs 200 responses.
2792 * Unlike invalidateCache(), this preserves the User object cache and
2793 * avoids database writes.
2797 public function touch() {
2798 $id = $this->getId();
2800 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
2801 $key = $cache->makeKey( 'user-quicktouched', 'id', $id );
2802 $cache->touchCheckKey( $key );
2803 $this->mQuickTouched
= null;
2808 * Validate the cache for this account.
2809 * @param string $timestamp A timestamp in TS_MW format
2812 public function validateCache( $timestamp ) {
2813 return ( $timestamp >= $this->getTouched() );
2817 * Get the user touched timestamp
2819 * Use this value only to validate caches via inequalities
2820 * such as in the case of HTTP If-Modified-Since response logic
2822 * @return string TS_MW Timestamp
2824 public function getTouched() {
2828 if ( $this->mQuickTouched
=== null ) {
2829 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
2830 $key = $cache->makeKey( 'user-quicktouched', 'id', $this->mId
);
2832 $this->mQuickTouched
= wfTimestamp( TS_MW
, $cache->getCheckKeyTime( $key ) );
2835 return max( $this->mTouched
, $this->mQuickTouched
);
2838 return $this->mTouched
;
2842 * Get the user_touched timestamp field (time of last DB updates)
2843 * @return string TS_MW Timestamp
2846 public function getDBTouched() {
2849 return $this->mTouched
;
2853 * Set the password and reset the random token.
2854 * Calls through to authentication plugin if necessary;
2855 * will have no effect if the auth plugin refuses to
2856 * pass the change through or if the legal password
2859 * As a special case, setting the password to null
2860 * wipes it, so the account cannot be logged in until
2861 * a new password is set, for instance via e-mail.
2863 * @deprecated since 1.27, use AuthManager instead
2864 * @param string $str New password to set
2865 * @throws PasswordError On failure
2868 public function setPassword( $str ) {
2869 return $this->setPasswordInternal( $str );
2873 * Set the password and reset the random token unconditionally.
2875 * @deprecated since 1.27, use AuthManager instead
2876 * @param string|null $str New password to set or null to set an invalid
2877 * password hash meaning that the user will not be able to log in
2878 * through the web interface.
2880 public function setInternalPassword( $str ) {
2881 $this->setPasswordInternal( $str );
2885 * Actually set the password and such
2886 * @since 1.27 cannot set a password for a user not in the database
2887 * @param string|null $str New password to set or null to set an invalid
2888 * password hash meaning that the user will not be able to log in
2889 * through the web interface.
2890 * @return bool Success
2892 private function setPasswordInternal( $str ) {
2893 $manager = AuthManager
::singleton();
2895 // If the user doesn't exist yet, fail
2896 if ( !$manager->userExists( $this->getName() ) ) {
2897 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2900 $status = $this->changeAuthenticationData( [
2901 'username' => $this->getName(),
2905 if ( !$status->isGood() ) {
2906 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
2907 ->info( __METHOD__
. ': Password change rejected: '
2908 . $status->getWikiText( null, null, 'en' ) );
2912 $this->setOption( 'watchlisttoken', false );
2913 SessionManager
::singleton()->invalidateSessionsForUser( $this );
2919 * Changes credentials of the user.
2921 * This is a convenience wrapper around AuthManager::changeAuthenticationData.
2922 * Note that this can return a status that isOK() but not isGood() on certain types of failures,
2923 * e.g. when no provider handled the change.
2925 * @param array $data A set of authentication data in fieldname => value format. This is the
2926 * same data you would pass the changeauthenticationdata API - 'username', 'password' etc.
2930 public function changeAuthenticationData( array $data ) {
2931 $manager = AuthManager
::singleton();
2932 $reqs = $manager->getAuthenticationRequests( AuthManager
::ACTION_CHANGE
, $this );
2933 $reqs = AuthenticationRequest
::loadRequestsFromSubmission( $reqs, $data );
2935 $status = Status
::newGood( 'ignored' );
2936 foreach ( $reqs as $req ) {
2937 $status->merge( $manager->allowsAuthenticationDataChange( $req ), true );
2939 if ( $status->getValue() === 'ignored' ) {
2940 $status->warning( 'authenticationdatachange-ignored' );
2943 if ( $status->isGood() ) {
2944 foreach ( $reqs as $req ) {
2945 $manager->changeAuthenticationData( $req );
2952 * Get the user's current token.
2953 * @param bool $forceCreation Force the generation of a new token if the
2954 * user doesn't have one (default=true for backwards compatibility).
2955 * @return string|null Token
2957 public function getToken( $forceCreation = true ) {
2958 global $wgAuthenticationTokenVersion;
2961 if ( !$this->mToken
&& $forceCreation ) {
2965 if ( !$this->mToken
) {
2966 // The user doesn't have a token, return null to indicate that.
2968 } elseif ( $this->mToken
=== self
::INVALID_TOKEN
) {
2969 // We return a random value here so existing token checks are very
2971 return MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2972 } elseif ( $wgAuthenticationTokenVersion === null ) {
2973 // $wgAuthenticationTokenVersion not in use, so return the raw secret
2974 return $this->mToken
;
2976 // $wgAuthenticationTokenVersion in use, so hmac it.
2977 $ret = MWCryptHash
::hmac( $wgAuthenticationTokenVersion, $this->mToken
, false );
2979 // The raw hash can be overly long. Shorten it up.
2980 $len = max( 32, self
::TOKEN_LENGTH
);
2981 if ( strlen( $ret ) < $len ) {
2982 // Should never happen, even md5 is 128 bits
2983 throw new \
UnexpectedValueException( 'Hmac returned less than 128 bits' );
2985 return substr( $ret, -$len );
2990 * Set the random token (used for persistent authentication)
2991 * Called from loadDefaults() among other places.
2993 * @param string|bool $token If specified, set the token to this value
2995 public function setToken( $token = false ) {
2997 if ( $this->mToken
=== self
::INVALID_TOKEN
) {
2998 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
2999 ->debug( __METHOD__
. ": Ignoring attempt to set token for system user \"$this\"" );
3000 } elseif ( !$token ) {
3001 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
3003 $this->mToken
= $token;
3008 * Set the password for a password reminder or new account email
3010 * @deprecated Removed in 1.27. Use PasswordReset instead.
3011 * @param string $str New password to set or null to set an invalid
3012 * password hash meaning that the user will not be able to use it
3013 * @param bool $throttle If true, reset the throttle timestamp to the present
3015 public function setNewpassword( $str, $throttle = true ) {
3016 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
3020 * Get the user's e-mail address
3021 * @return string User's email address
3023 public function getEmail() {
3025 Hooks
::run( 'UserGetEmail', [ $this, &$this->mEmail
] );
3026 return $this->mEmail
;
3030 * Get the timestamp of the user's e-mail authentication
3031 * @return string TS_MW timestamp
3033 public function getEmailAuthenticationTimestamp() {
3035 Hooks
::run( 'UserGetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
3036 return $this->mEmailAuthenticated
;
3040 * Set the user's e-mail address
3041 * @param string $str New e-mail address
3043 public function setEmail( $str ) {
3045 if ( $str == $this->mEmail
) {
3048 $this->invalidateEmail();
3049 $this->mEmail
= $str;
3050 Hooks
::run( 'UserSetEmail', [ $this, &$this->mEmail
] );
3054 * Set the user's e-mail address and a confirmation mail if needed.
3057 * @param string $str New e-mail address
3060 public function setEmailWithConfirmation( $str ) {
3061 global $wgEnableEmail, $wgEmailAuthentication;
3063 if ( !$wgEnableEmail ) {
3064 return Status
::newFatal( 'emaildisabled' );
3067 $oldaddr = $this->getEmail();
3068 if ( $str === $oldaddr ) {
3069 return Status
::newGood( true );
3072 $type = $oldaddr != '' ?
'changed' : 'set';
3073 $notificationResult = null;
3075 if ( $wgEmailAuthentication ) {
3076 // Send the user an email notifying the user of the change in registered
3077 // email address on their previous email address
3078 if ( $type == 'changed' ) {
3079 $change = $str != '' ?
'changed' : 'removed';
3080 $notificationResult = $this->sendMail(
3081 wfMessage( 'notificationemail_subject_' . $change )->text(),
3082 wfMessage( 'notificationemail_body_' . $change,
3083 $this->getRequest()->getIP(),
3090 $this->setEmail( $str );
3092 if ( $str !== '' && $wgEmailAuthentication ) {
3093 // Send a confirmation request to the new address if needed
3094 $result = $this->sendConfirmationMail( $type );
3096 if ( $notificationResult !== null ) {
3097 $result->merge( $notificationResult );
3100 if ( $result->isGood() ) {
3101 // Say to the caller that a confirmation and notification mail has been sent
3102 $result->value
= 'eauth';
3105 $result = Status
::newGood( true );
3112 * Get the user's real name
3113 * @return string User's real name
3115 public function getRealName() {
3116 if ( !$this->isItemLoaded( 'realname' ) ) {
3120 return $this->mRealName
;
3124 * Set the user's real name
3125 * @param string $str New real name
3127 public function setRealName( $str ) {
3129 $this->mRealName
= $str;
3133 * Get the user's current setting for a given option.
3135 * @param string $oname The option to check
3136 * @param string|array $defaultOverride A default value returned if the option does not exist
3137 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
3138 * @return string|array|int|null User's current value for the option
3139 * @see getBoolOption()
3140 * @see getIntOption()
3142 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
3143 global $wgHiddenPrefs;
3144 $this->loadOptions();
3146 # We want 'disabled' preferences to always behave as the default value for
3147 # users, even if they have set the option explicitly in their settings (ie they
3148 # set it, and then it was disabled removing their ability to change it). But
3149 # we don't want to erase the preferences in the database in case the preference
3150 # is re-enabled again. So don't touch $mOptions, just override the returned value
3151 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
3152 return self
::getDefaultOption( $oname );
3155 if ( array_key_exists( $oname, $this->mOptions
) ) {
3156 return $this->mOptions
[$oname];
3158 return $defaultOverride;
3163 * Get all user's options
3165 * @param int $flags Bitwise combination of:
3166 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
3167 * to the default value. (Since 1.25)
3170 public function getOptions( $flags = 0 ) {
3171 global $wgHiddenPrefs;
3172 $this->loadOptions();
3173 $options = $this->mOptions
;
3175 # We want 'disabled' preferences to always behave as the default value for
3176 # users, even if they have set the option explicitly in their settings (ie they
3177 # set it, and then it was disabled removing their ability to change it). But
3178 # we don't want to erase the preferences in the database in case the preference
3179 # is re-enabled again. So don't touch $mOptions, just override the returned value
3180 foreach ( $wgHiddenPrefs as $pref ) {
3181 $default = self
::getDefaultOption( $pref );
3182 if ( $default !== null ) {
3183 $options[$pref] = $default;
3187 if ( $flags & self
::GETOPTIONS_EXCLUDE_DEFAULTS
) {
3188 $options = array_diff_assoc( $options, self
::getDefaultOptions() );
3195 * Get the user's current setting for a given option, as a boolean value.
3197 * @param string $oname The option to check
3198 * @return bool User's current value for the option
3201 public function getBoolOption( $oname ) {
3202 return (bool)$this->getOption( $oname );
3206 * Get the user's current setting for a given option, as an integer value.
3208 * @param string $oname The option to check
3209 * @param int $defaultOverride A default value returned if the option does not exist
3210 * @return int User's current value for the option
3213 public function getIntOption( $oname, $defaultOverride = 0 ) {
3214 $val = $this->getOption( $oname );
3216 $val = $defaultOverride;
3218 return intval( $val );
3222 * Set the given option for a user.
3224 * You need to call saveSettings() to actually write to the database.
3226 * @param string $oname The option to set
3227 * @param mixed $val New value to set
3229 public function setOption( $oname, $val ) {
3230 $this->loadOptions();
3232 // Explicitly NULL values should refer to defaults
3233 if ( is_null( $val ) ) {
3234 $val = self
::getDefaultOption( $oname );
3237 $this->mOptions
[$oname] = $val;
3241 * Get a token stored in the preferences (like the watchlist one),
3242 * resetting it if it's empty (and saving changes).
3244 * @param string $oname The option name to retrieve the token from
3245 * @return string|bool User's current value for the option, or false if this option is disabled.
3246 * @see resetTokenFromOption()
3248 * @deprecated since 1.26 Applications should use the OAuth extension
3250 public function getTokenFromOption( $oname ) {
3251 global $wgHiddenPrefs;
3253 $id = $this->getId();
3254 if ( !$id ||
in_array( $oname, $wgHiddenPrefs ) ) {
3258 $token = $this->getOption( $oname );
3260 // Default to a value based on the user token to avoid space
3261 // wasted on storing tokens for all users. When this option
3262 // is set manually by the user, only then is it stored.
3263 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
3270 * Reset a token stored in the preferences (like the watchlist one).
3271 * *Does not* save user's preferences (similarly to setOption()).
3273 * @param string $oname The option name to reset the token in
3274 * @return string|bool New token value, or false if this option is disabled.
3275 * @see getTokenFromOption()
3278 public function resetTokenFromOption( $oname ) {
3279 global $wgHiddenPrefs;
3280 if ( in_array( $oname, $wgHiddenPrefs ) ) {
3284 $token = MWCryptRand
::generateHex( 40 );
3285 $this->setOption( $oname, $token );
3290 * Return a list of the types of user options currently returned by
3291 * User::getOptionKinds().
3293 * Currently, the option kinds are:
3294 * - 'registered' - preferences which are registered in core MediaWiki or
3295 * by extensions using the UserGetDefaultOptions hook.
3296 * - 'registered-multiselect' - as above, using the 'multiselect' type.
3297 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
3298 * - 'userjs' - preferences with names starting with 'userjs-', intended to
3299 * be used by user scripts.
3300 * - 'special' - "preferences" that are not accessible via User::getOptions
3301 * or User::setOptions.
3302 * - 'unused' - preferences about which MediaWiki doesn't know anything.
3303 * These are usually legacy options, removed in newer versions.
3305 * The API (and possibly others) use this function to determine the possible
3306 * option types for validation purposes, so make sure to update this when a
3307 * new option kind is added.
3309 * @see User::getOptionKinds
3310 * @return array Option kinds
3312 public static function listOptionKinds() {
3315 'registered-multiselect',
3316 'registered-checkmatrix',
3324 * Return an associative array mapping preferences keys to the kind of a preference they're
3325 * used for. Different kinds are handled differently when setting or reading preferences.
3327 * See User::listOptionKinds for the list of valid option types that can be provided.
3329 * @see User::listOptionKinds
3330 * @param IContextSource $context
3331 * @param array $options Assoc. array with options keys to check as keys.
3332 * Defaults to $this->mOptions.
3333 * @return array The key => kind mapping data
3335 public function getOptionKinds( IContextSource
$context, $options = null ) {
3336 $this->loadOptions();
3337 if ( $options === null ) {
3338 $options = $this->mOptions
;
3341 $preferencesFactory = MediaWikiServices
::getInstance()->getPreferencesFactory();
3342 $prefs = $preferencesFactory->getFormDescriptor( $this, $context );
3345 // Pull out the "special" options, so they don't get converted as
3346 // multiselect or checkmatrix.
3347 $specialOptions = array_fill_keys( $preferencesFactory->getSaveBlacklist(), true );
3348 foreach ( $specialOptions as $name => $value ) {
3349 unset( $prefs[$name] );
3352 // Multiselect and checkmatrix options are stored in the database with
3353 // one key per option, each having a boolean value. Extract those keys.
3354 $multiselectOptions = [];
3355 foreach ( $prefs as $name => $info ) {
3356 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
3357 ( isset( $info['class'] ) && $info['class'] == HTMLMultiSelectField
::class ) ) {
3358 $opts = HTMLFormField
::flattenOptions( $info['options'] );
3359 $prefix = $info['prefix'] ??
$name;
3361 foreach ( $opts as $value ) {
3362 $multiselectOptions["$prefix$value"] = true;
3365 unset( $prefs[$name] );
3368 $checkmatrixOptions = [];
3369 foreach ( $prefs as $name => $info ) {
3370 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
3371 ( isset( $info['class'] ) && $info['class'] == HTMLCheckMatrix
::class ) ) {
3372 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
3373 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
3374 $prefix = $info['prefix'] ??
$name;
3376 foreach ( $columns as $column ) {
3377 foreach ( $rows as $row ) {
3378 $checkmatrixOptions["$prefix$column-$row"] = true;
3382 unset( $prefs[$name] );
3386 // $value is ignored
3387 foreach ( $options as $key => $value ) {
3388 if ( isset( $prefs[$key] ) ) {
3389 $mapping[$key] = 'registered';
3390 } elseif ( isset( $multiselectOptions[$key] ) ) {
3391 $mapping[$key] = 'registered-multiselect';
3392 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
3393 $mapping[$key] = 'registered-checkmatrix';
3394 } elseif ( isset( $specialOptions[$key] ) ) {
3395 $mapping[$key] = 'special';
3396 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
3397 $mapping[$key] = 'userjs';
3399 $mapping[$key] = 'unused';
3407 * Reset certain (or all) options to the site defaults
3409 * The optional parameter determines which kinds of preferences will be reset.
3410 * Supported values are everything that can be reported by getOptionKinds()
3411 * and 'all', which forces a reset of *all* preferences and overrides everything else.
3413 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
3414 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
3415 * for backwards-compatibility.
3416 * @param IContextSource|null $context Context source used when $resetKinds
3417 * does not contain 'all', passed to getOptionKinds().
3418 * Defaults to RequestContext::getMain() when null.
3420 public function resetOptions(
3421 $resetKinds = [ 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ],
3422 IContextSource
$context = null
3425 $defaultOptions = self
::getDefaultOptions();
3427 if ( !is_array( $resetKinds ) ) {
3428 $resetKinds = [ $resetKinds ];
3431 if ( in_array( 'all', $resetKinds ) ) {
3432 $newOptions = $defaultOptions;
3434 if ( $context === null ) {
3435 $context = RequestContext
::getMain();
3438 $optionKinds = $this->getOptionKinds( $context );
3439 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
3442 // Use default values for the options that should be deleted, and
3443 // copy old values for the ones that shouldn't.
3444 foreach ( $this->mOptions
as $key => $value ) {
3445 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
3446 if ( array_key_exists( $key, $defaultOptions ) ) {
3447 $newOptions[$key] = $defaultOptions[$key];
3450 $newOptions[$key] = $value;
3455 Hooks
::run( 'UserResetAllOptions', [ $this, &$newOptions, $this->mOptions
, $resetKinds ] );
3457 $this->mOptions
= $newOptions;
3458 $this->mOptionsLoaded
= true;
3462 * Get the user's preferred date format.
3463 * @return string User's preferred date format
3465 public function getDatePreference() {
3466 // Important migration for old data rows
3467 if ( is_null( $this->mDatePreference
) ) {
3469 $value = $this->getOption( 'date' );
3470 $map = $wgLang->getDatePreferenceMigrationMap();
3471 if ( isset( $map[$value] ) ) {
3472 $value = $map[$value];
3474 $this->mDatePreference
= $value;
3476 return $this->mDatePreference
;
3480 * Determine based on the wiki configuration and the user's options,
3481 * whether this user must be over HTTPS no matter what.
3485 public function requiresHTTPS() {
3486 global $wgSecureLogin;
3487 if ( !$wgSecureLogin ) {
3490 $https = $this->getBoolOption( 'prefershttps' );
3491 Hooks
::run( 'UserRequiresHTTPS', [ $this, &$https ] );
3493 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
3500 * Get the user preferred stub threshold
3504 public function getStubThreshold() {
3505 global $wgMaxArticleSize; # Maximum article size, in Kb
3506 $threshold = $this->getIntOption( 'stubthreshold' );
3507 if ( $threshold > $wgMaxArticleSize * 1024 ) {
3508 // If they have set an impossible value, disable the preference
3509 // so we can use the parser cache again.
3516 * Get the permissions this user has.
3517 * @return string[] permission names
3519 public function getRights() {
3520 if ( is_null( $this->mRights
) ) {
3521 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
3522 Hooks
::run( 'UserGetRights', [ $this, &$this->mRights
] );
3524 // Deny any rights denied by the user's session, unless this
3525 // endpoint has no sessions.
3526 if ( !defined( 'MW_NO_SESSION' ) ) {
3527 $allowedRights = $this->getRequest()->getSession()->getAllowedUserRights();
3528 if ( $allowedRights !== null ) {
3529 $this->mRights
= array_intersect( $this->mRights
, $allowedRights );
3533 // Force reindexation of rights when a hook has unset one of them
3534 $this->mRights
= array_values( array_unique( $this->mRights
) );
3536 // If block disables login, we should also remove any
3537 // extra rights blocked users might have, in case the
3538 // blocked user has a pre-existing session (T129738).
3539 // This is checked here for cases where people only call
3540 // $user->isAllowed(). It is also checked in Title::checkUserBlock()
3541 // to give a better error message in the common case.
3542 $config = RequestContext
::getMain()->getConfig();
3544 $this->isLoggedIn() &&
3545 $config->get( 'BlockDisablesLogin' ) &&
3549 $this->mRights
= array_intersect( $this->mRights
, $anon->getRights() );
3552 return $this->mRights
;
3556 * Get the list of explicit group memberships this user has.
3557 * The implicit * and user groups are not included.
3558 * @return array Array of String internal group names
3560 public function getGroups() {
3562 $this->loadGroups();
3563 return array_keys( $this->mGroupMemberships
);
3567 * Get the list of explicit group memberships this user has, stored as
3568 * UserGroupMembership objects. Implicit groups are not included.
3570 * @return UserGroupMembership[] Associative array of (group name => UserGroupMembership object)
3573 public function getGroupMemberships() {
3575 $this->loadGroups();
3576 return $this->mGroupMemberships
;
3580 * Get the list of implicit group memberships this user has.
3581 * This includes all explicit groups, plus 'user' if logged in,
3582 * '*' for all accounts, and autopromoted groups
3583 * @param bool $recache Whether to avoid the cache
3584 * @return array Array of String internal group names
3586 public function getEffectiveGroups( $recache = false ) {
3587 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
3588 $this->mEffectiveGroups
= array_unique( array_merge(
3589 $this->getGroups(), // explicit groups
3590 $this->getAutomaticGroups( $recache ) // implicit groups
3592 // Avoid PHP 7.1 warning of passing $this by reference
3594 // Hook for additional groups
3595 Hooks
::run( 'UserEffectiveGroups', [ &$user, &$this->mEffectiveGroups
] );
3596 // Force reindexation of groups when a hook has unset one of them
3597 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
3599 return $this->mEffectiveGroups
;
3603 * Get the list of implicit group memberships this user has.
3604 * This includes 'user' if logged in, '*' for all accounts,
3605 * and autopromoted groups
3606 * @param bool $recache Whether to avoid the cache
3607 * @return array Array of String internal group names
3609 public function getAutomaticGroups( $recache = false ) {
3610 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
3611 $this->mImplicitGroups
= [ '*' ];
3612 if ( $this->getId() ) {
3613 $this->mImplicitGroups
[] = 'user';
3615 $this->mImplicitGroups
= array_unique( array_merge(
3616 $this->mImplicitGroups
,
3617 Autopromote
::getAutopromoteGroups( $this )
3621 // Assure data consistency with rights/groups,
3622 // as getEffectiveGroups() depends on this function
3623 $this->mEffectiveGroups
= null;
3626 return $this->mImplicitGroups
;
3630 * Returns the groups the user has belonged to.
3632 * The user may still belong to the returned groups. Compare with getGroups().
3634 * The function will not return groups the user had belonged to before MW 1.17
3636 * @return array Names of the groups the user has belonged to.
3638 public function getFormerGroups() {
3641 if ( is_null( $this->mFormerGroups
) ) {
3642 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3643 ?
wfGetDB( DB_MASTER
)
3644 : wfGetDB( DB_REPLICA
);
3645 $res = $db->select( 'user_former_groups',
3647 [ 'ufg_user' => $this->mId
],
3649 $this->mFormerGroups
= [];
3650 foreach ( $res as $row ) {
3651 $this->mFormerGroups
[] = $row->ufg_group
;
3655 return $this->mFormerGroups
;
3659 * Get the user's edit count.
3660 * @return int|null Null for anonymous users
3662 public function getEditCount() {
3663 if ( !$this->getId() ) {
3667 if ( $this->mEditCount
=== null ) {
3668 /* Populate the count, if it has not been populated yet */
3669 $dbr = wfGetDB( DB_REPLICA
);
3670 // check if the user_editcount field has been initialized
3671 $count = $dbr->selectField(
3672 'user', 'user_editcount',
3673 [ 'user_id' => $this->mId
],
3677 if ( $count === null ) {
3678 // it has not been initialized. do so.
3679 $count = $this->initEditCount();
3681 $this->mEditCount
= $count;
3683 return (int)$this->mEditCount
;
3687 * Add the user to the given group. This takes immediate effect.
3688 * If the user is already in the group, the expiry time will be updated to the new
3689 * expiry time. (If $expiry is omitted or null, the membership will be altered to
3692 * @param string $group Name of the group to add
3693 * @param string $expiry Optional expiry timestamp in any format acceptable to
3694 * wfTimestamp(), or null if the group assignment should not expire
3697 public function addGroup( $group, $expiry = null ) {
3699 $this->loadGroups();
3702 $expiry = wfTimestamp( TS_MW
, $expiry );
3705 if ( !Hooks
::run( 'UserAddGroup', [ $this, &$group, &$expiry ] ) ) {
3709 // create the new UserGroupMembership and put it in the DB
3710 $ugm = new UserGroupMembership( $this->mId
, $group, $expiry );
3711 if ( !$ugm->insert( true ) ) {
3715 $this->mGroupMemberships
[$group] = $ugm;
3717 // Refresh the groups caches, and clear the rights cache so it will be
3718 // refreshed on the next call to $this->getRights().
3719 $this->getEffectiveGroups( true );
3720 $this->mRights
= null;
3722 $this->invalidateCache();
3728 * Remove the user from the given group.
3729 * This takes immediate effect.
3730 * @param string $group Name of the group to remove
3733 public function removeGroup( $group ) {
3736 if ( !Hooks
::run( 'UserRemoveGroup', [ $this, &$group ] ) ) {
3740 $ugm = UserGroupMembership
::getMembership( $this->mId
, $group );
3741 // delete the membership entry
3742 if ( !$ugm ||
!$ugm->delete() ) {
3746 $this->loadGroups();
3747 unset( $this->mGroupMemberships
[$group] );
3749 // Refresh the groups caches, and clear the rights cache so it will be
3750 // refreshed on the next call to $this->getRights().
3751 $this->getEffectiveGroups( true );
3752 $this->mRights
= null;
3754 $this->invalidateCache();
3760 * Get whether the user is logged in
3763 public function isLoggedIn() {
3764 return $this->getId() != 0;
3768 * Get whether the user is anonymous
3771 public function isAnon() {
3772 return !$this->isLoggedIn();
3776 * @return bool Whether this user is flagged as being a bot role account
3779 public function isBot() {
3780 if ( in_array( 'bot', $this->getGroups() ) && $this->isAllowed( 'bot' ) ) {
3785 Hooks
::run( "UserIsBot", [ $this, &$isBot ] );
3791 * Check if user is allowed to access a feature / make an action
3793 * @param string $permissions,... Permissions to test
3794 * @return bool True if user is allowed to perform *any* of the given actions
3796 public function isAllowedAny() {
3797 $permissions = func_get_args();
3798 foreach ( $permissions as $permission ) {
3799 if ( $this->isAllowed( $permission ) ) {
3808 * @param string $permissions,... Permissions to test
3809 * @return bool True if the user is allowed to perform *all* of the given actions
3811 public function isAllowedAll() {
3812 $permissions = func_get_args();
3813 foreach ( $permissions as $permission ) {
3814 if ( !$this->isAllowed( $permission ) ) {
3822 * Internal mechanics of testing a permission
3823 * @param string $action
3826 public function isAllowed( $action = '' ) {
3827 if ( $action === '' ) {
3828 return true; // In the spirit of DWIM
3830 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3831 // by misconfiguration: 0 == 'foo'
3832 return in_array( $action, $this->getRights(), true );
3836 * Check whether to enable recent changes patrol features for this user
3837 * @return bool True or false
3839 public function useRCPatrol() {
3840 global $wgUseRCPatrol;
3841 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3845 * Check whether to enable new pages patrol features for this user
3846 * @return bool True or false
3848 public function useNPPatrol() {
3849 global $wgUseRCPatrol, $wgUseNPPatrol;
3851 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3852 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3857 * Check whether to enable new files patrol features for this user
3858 * @return bool True or false
3860 public function useFilePatrol() {
3861 global $wgUseRCPatrol, $wgUseFilePatrol;
3863 ( $wgUseRCPatrol ||
$wgUseFilePatrol )
3864 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3869 * Get the WebRequest object to use with this object
3871 * @return WebRequest
3873 public function getRequest() {
3874 if ( $this->mRequest
) {
3875 return $this->mRequest
;
3883 * Check the watched status of an article.
3884 * @since 1.22 $checkRights parameter added
3885 * @param Title $title Title of the article to look at
3886 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3887 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3890 public function isWatched( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3891 if ( $title->isWatchable() && ( !$checkRights ||
$this->isAllowed( 'viewmywatchlist' ) ) ) {
3892 return MediaWikiServices
::getInstance()->getWatchedItemStore()->isWatched( $this, $title );
3899 * @since 1.22 $checkRights parameter added
3900 * @param Title $title Title of the article to look at
3901 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3902 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3904 public function addWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3905 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3906 MediaWikiServices
::getInstance()->getWatchedItemStore()->addWatchBatchForUser(
3908 [ $title->getSubjectPage(), $title->getTalkPage() ]
3911 $this->invalidateCache();
3915 * Stop watching an article.
3916 * @since 1.22 $checkRights parameter added
3917 * @param Title $title Title of the article to look at
3918 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3919 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3921 public function removeWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3922 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3923 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
3924 $store->removeWatch( $this, $title->getSubjectPage() );
3925 $store->removeWatch( $this, $title->getTalkPage() );
3927 $this->invalidateCache();
3931 * Clear the user's notification timestamp for the given title.
3932 * If e-notif e-mails are on, they will receive notification mails on
3933 * the next change of the page if it's watched etc.
3934 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3935 * @param Title &$title Title of the article to look at
3936 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3938 public function clearNotification( &$title, $oldid = 0 ) {
3939 global $wgUseEnotif, $wgShowUpdatedMarker;
3941 // Do nothing if the database is locked to writes
3942 if ( wfReadOnly() ) {
3946 // Do nothing if not allowed to edit the watchlist
3947 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3951 // If we're working on user's talk page, we should update the talk page message indicator
3952 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3953 // Avoid PHP 7.1 warning of passing $this by reference
3955 if ( !Hooks
::run( 'UserClearNewTalkNotification', [ &$user, $oldid ] ) ) {
3959 // Try to update the DB post-send and only if needed...
3960 DeferredUpdates
::addCallableUpdate( function () use ( $title, $oldid ) {
3961 if ( !$this->getNewtalk() ) {
3962 return; // no notifications to clear
3965 // Delete the last notifications (they stack up)
3966 $this->setNewtalk( false );
3968 // If there is a new, unseen, revision, use its timestamp
3970 ?
$title->getNextRevisionID( $oldid, Title
::GAID_FOR_UPDATE
)
3973 $this->setNewtalk( true, Revision
::newFromId( $nextid ) );
3978 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3982 if ( $this->isAnon() ) {
3983 // Nothing else to do...
3987 // Only update the timestamp if the page is being watched.
3988 // The query to find out if it is watched is cached both in memcached and per-invocation,
3989 // and when it does have to be executed, it can be on a replica DB
3990 // If this is the user's newtalk page, we always update the timestamp
3992 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3996 MediaWikiServices
::getInstance()->getWatchedItemStore()
3997 ->resetNotificationTimestamp( $this, $title, $force, $oldid );
4001 * Resets all of the given user's page-change notification timestamps.
4002 * If e-notif e-mails are on, they will receive notification mails on
4003 * the next change of any watched page.
4004 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
4006 public function clearAllNotifications() {
4007 global $wgUseEnotif, $wgShowUpdatedMarker;
4008 // Do nothing if not allowed to edit the watchlist
4009 if ( wfReadOnly() ||
!$this->isAllowed( 'editmywatchlist' ) ) {
4013 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
4014 $this->setNewtalk( false );
4018 $id = $this->getId();
4023 $watchedItemStore = MediaWikiServices
::getInstance()->getWatchedItemStore();
4024 $watchedItemStore->resetAllNotificationTimestampsForUser( $this );
4026 // We also need to clear here the "you have new message" notification for the own
4027 // user_talk page; it's cleared one page view later in WikiPage::doViewUpdates().
4031 * Compute experienced level based on edit count and registration date.
4033 * @return string 'newcomer', 'learner', or 'experienced'
4035 public function getExperienceLevel() {
4036 global $wgLearnerEdits,
4037 $wgExperiencedUserEdits,
4038 $wgLearnerMemberSince,
4039 $wgExperiencedUserMemberSince;
4041 if ( $this->isAnon() ) {
4045 $editCount = $this->getEditCount();
4046 $registration = $this->getRegistration();
4048 $learnerRegistration = wfTimestamp( TS_MW
, $now - $wgLearnerMemberSince * 86400 );
4049 $experiencedRegistration = wfTimestamp( TS_MW
, $now - $wgExperiencedUserMemberSince * 86400 );
4052 $editCount < $wgLearnerEdits ||
4053 $registration > $learnerRegistration
4057 $editCount > $wgExperiencedUserEdits &&
4058 $registration <= $experiencedRegistration
4060 return 'experienced';
4067 * Persist this user's session (e.g. set cookies)
4069 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
4071 * @param bool $secure Whether to force secure/insecure cookies or use default
4072 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
4074 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
4076 if ( 0 == $this->mId
) {
4080 $session = $this->getRequest()->getSession();
4081 if ( $request && $session->getRequest() !== $request ) {
4082 $session = $session->sessionWithRequest( $request );
4084 $delay = $session->delaySave();
4086 if ( !$session->getUser()->equals( $this ) ) {
4087 if ( !$session->canSetUser() ) {
4088 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
4089 ->warning( __METHOD__
.
4090 ": Cannot save user \"$this\" to a user \"{$session->getUser()}\"'s immutable session"
4094 $session->setUser( $this );
4097 $session->setRememberUser( $rememberMe );
4098 if ( $secure !== null ) {
4099 $session->setForceHTTPS( $secure );
4102 $session->persist();
4104 ScopedCallback
::consume( $delay );
4108 * Log this user out.
4110 public function logout() {
4111 // Avoid PHP 7.1 warning of passing $this by reference
4113 if ( Hooks
::run( 'UserLogout', [ &$user ] ) ) {
4119 * Clear the user's session, and reset the instance cache.
4122 public function doLogout() {
4123 $session = $this->getRequest()->getSession();
4124 if ( !$session->canSetUser() ) {
4125 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
4126 ->warning( __METHOD__
. ": Cannot log out of an immutable session" );
4127 $error = 'immutable';
4128 } elseif ( !$session->getUser()->equals( $this ) ) {
4129 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
4130 ->warning( __METHOD__
.
4131 ": Cannot log user \"$this\" out of a user \"{$session->getUser()}\"'s session"
4133 // But we still may as well make this user object anon
4134 $this->clearInstanceCache( 'defaults' );
4135 $error = 'wronguser';
4137 $this->clearInstanceCache( 'defaults' );
4138 $delay = $session->delaySave();
4139 $session->unpersist(); // Clear cookies (T127436)
4140 $session->setLoggedOutTimestamp( time() );
4141 $session->setUser( new User
);
4142 $session->set( 'wsUserID', 0 ); // Other code expects this
4143 $session->resetAllTokens();
4144 ScopedCallback
::consume( $delay );
4147 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authevents' )->info( 'Logout', [
4148 'event' => 'logout',
4149 'successful' => $error === false,
4150 'status' => $error ?
: 'success',
4155 * Save this user's settings into the database.
4156 * @todo Only rarely do all these fields need to be set!
4158 public function saveSettings() {
4159 if ( wfReadOnly() ) {
4160 // @TODO: caller should deal with this instead!
4161 // This should really just be an exception.
4162 MWExceptionHandler
::logException( new DBExpectedError(
4164 "Could not update user with ID '{$this->mId}'; DB is read-only."
4170 if ( 0 == $this->mId
) {
4174 // Get a new user_touched that is higher than the old one.
4175 // This will be used for a CAS check as a last-resort safety
4176 // check against race conditions and replica DB lag.
4177 $newTouched = $this->newTouchedTimestamp();
4179 $dbw = wfGetDB( DB_MASTER
);
4180 $dbw->doAtomicSection( __METHOD__
, function ( $dbw, $fname ) use ( $newTouched ) {
4181 global $wgActorTableSchemaMigrationStage;
4183 $dbw->update( 'user',
4185 'user_name' => $this->mName
,
4186 'user_real_name' => $this->mRealName
,
4187 'user_email' => $this->mEmail
,
4188 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
4189 'user_touched' => $dbw->timestamp( $newTouched ),
4190 'user_token' => strval( $this->mToken
),
4191 'user_email_token' => $this->mEmailToken
,
4192 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
4193 ], $this->makeUpdateConditions( $dbw, [ /* WHERE */
4194 'user_id' => $this->mId
,
4198 if ( !$dbw->affectedRows() ) {
4199 // Maybe the problem was a missed cache update; clear it to be safe
4200 $this->clearSharedCache( 'refresh' );
4201 // User was changed in the meantime or loaded with stale data
4202 $from = ( $this->queryFlagsUsed
& self
::READ_LATEST
) ?
'master' : 'replica';
4203 throw new MWException(
4204 "CAS update failed on user_touched for user ID '{$this->mId}' (read from $from);" .
4205 " the version of the user to be saved is older than the current version."
4209 if ( $wgActorTableSchemaMigrationStage > MIGRATION_OLD
) {
4212 [ 'actor_name' => $this->mName
],
4213 [ 'actor_user' => $this->mId
],
4219 $this->mTouched
= $newTouched;
4220 $this->saveOptions();
4222 Hooks
::run( 'UserSaveSettings', [ $this ] );
4223 $this->clearSharedCache();
4224 $this->getUserPage()->invalidateCache();
4228 * If only this user's username is known, and it exists, return the user ID.
4230 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
4233 public function idForName( $flags = 0 ) {
4234 $s = trim( $this->getName() );
4239 $db = ( ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
)
4240 ?
wfGetDB( DB_MASTER
)
4241 : wfGetDB( DB_REPLICA
);
4243 $options = ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
)
4244 ?
[ 'LOCK IN SHARE MODE' ]
4247 $id = $db->selectField( 'user',
4248 'user_id', [ 'user_name' => $s ], __METHOD__
, $options );
4254 * Add a user to the database, return the user object
4256 * @param string $name Username to add
4257 * @param array $params Array of Strings Non-default parameters to save to
4258 * the database as user_* fields:
4259 * - email: The user's email address.
4260 * - email_authenticated: The email authentication timestamp.
4261 * - real_name: The user's real name.
4262 * - options: An associative array of non-default options.
4263 * - token: Random authentication token. Do not set.
4264 * - registration: Registration timestamp. Do not set.
4266 * @return User|null User object, or null if the username already exists.
4268 public static function createNew( $name, $params = [] ) {
4269 foreach ( [ 'password', 'newpassword', 'newpass_time', 'password_expires' ] as $field ) {
4270 if ( isset( $params[$field] ) ) {
4271 wfDeprecated( __METHOD__
. " with param '$field'", '1.27' );
4272 unset( $params[$field] );
4278 $user->setToken(); // init token
4279 if ( isset( $params['options'] ) ) {
4280 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
4281 unset( $params['options'] );
4283 $dbw = wfGetDB( DB_MASTER
);
4285 $noPass = PasswordFactory
::newInvalidPassword()->toString();
4288 'user_name' => $name,
4289 'user_password' => $noPass,
4290 'user_newpassword' => $noPass,
4291 'user_email' => $user->mEmail
,
4292 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
4293 'user_real_name' => $user->mRealName
,
4294 'user_token' => strval( $user->mToken
),
4295 'user_registration' => $dbw->timestamp( $user->mRegistration
),
4296 'user_editcount' => 0,
4297 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
4299 foreach ( $params as $name => $value ) {
4300 $fields["user_$name"] = $value;
4303 return $dbw->doAtomicSection( __METHOD__
, function ( $dbw, $fname ) use ( $fields ) {
4304 $dbw->insert( 'user', $fields, $fname, [ 'IGNORE' ] );
4305 if ( $dbw->affectedRows() ) {
4306 $newUser = self
::newFromId( $dbw->insertId() );
4307 // Load the user from master to avoid replica lag
4308 $newUser->load( self
::READ_LATEST
);
4309 $newUser->updateActorId( $dbw );
4318 * Add this existing user object to the database. If the user already
4319 * exists, a fatal status object is returned, and the user object is
4320 * initialised with the data from the database.
4322 * Previously, this function generated a DB error due to a key conflict
4323 * if the user already existed. Many extension callers use this function
4324 * in code along the lines of:
4326 * $user = User::newFromName( $name );
4327 * if ( !$user->isLoggedIn() ) {
4328 * $user->addToDatabase();
4330 * // do something with $user...
4332 * However, this was vulnerable to a race condition (T18020). By
4333 * initialising the user object if the user exists, we aim to support this
4334 * calling sequence as far as possible.
4336 * Note that if the user exists, this function will acquire a write lock,
4337 * so it is still advisable to make the call conditional on isLoggedIn(),
4338 * and to commit the transaction after calling.
4340 * @throws MWException
4343 public function addToDatabase() {
4345 if ( !$this->mToken
) {
4346 $this->setToken(); // init token
4349 if ( !is_string( $this->mName
) ) {
4350 throw new RuntimeException( "User name field is not set." );
4353 $this->mTouched
= $this->newTouchedTimestamp();
4355 $dbw = wfGetDB( DB_MASTER
);
4356 $status = $dbw->doAtomicSection( __METHOD__
, function ( $dbw, $fname ) {
4357 $noPass = PasswordFactory
::newInvalidPassword()->toString();
4358 $dbw->insert( 'user',
4360 'user_name' => $this->mName
,
4361 'user_password' => $noPass,
4362 'user_newpassword' => $noPass,
4363 'user_email' => $this->mEmail
,
4364 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
4365 'user_real_name' => $this->mRealName
,
4366 'user_token' => strval( $this->mToken
),
4367 'user_registration' => $dbw->timestamp( $this->mRegistration
),
4368 'user_editcount' => 0,
4369 'user_touched' => $dbw->timestamp( $this->mTouched
),
4373 if ( !$dbw->affectedRows() ) {
4374 // Use locking reads to bypass any REPEATABLE-READ snapshot.
4375 $this->mId
= $dbw->selectField(
4378 [ 'user_name' => $this->mName
],
4380 [ 'LOCK IN SHARE MODE' ]
4384 if ( $this->loadFromDatabase( self
::READ_LOCKING
) ) {
4389 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
4390 "to insert user '{$this->mName}' row, but it was not present in select!" );
4392 return Status
::newFatal( 'userexists' );
4394 $this->mId
= $dbw->insertId();
4395 self
::$idCacheByName[$this->mName
] = $this->mId
;
4396 $this->updateActorId( $dbw );
4398 return Status
::newGood();
4400 if ( !$status->isGood() ) {
4404 // Clear instance cache other than user table data and actor, which is already accurate
4405 $this->clearInstanceCache();
4407 $this->saveOptions();
4408 return Status
::newGood();
4412 * Update the actor ID after an insert
4413 * @param IDatabase $dbw Writable database handle
4415 private function updateActorId( IDatabase
$dbw ) {
4416 global $wgActorTableSchemaMigrationStage;
4418 if ( $wgActorTableSchemaMigrationStage > MIGRATION_OLD
) {
4421 [ 'actor_user' => $this->mId
, 'actor_name' => $this->mName
],
4424 $this->mActorId
= (int)$dbw->insertId();
4429 * If this user is logged-in and blocked,
4430 * block any IP address they've successfully logged in from.
4431 * @return bool A block was spread
4433 public function spreadAnyEditBlock() {
4434 if ( $this->isLoggedIn() && $this->isBlocked() ) {
4435 return $this->spreadBlock();
4442 * If this (non-anonymous) user is blocked,
4443 * block the IP address they've successfully logged in from.
4444 * @return bool A block was spread
4446 protected function spreadBlock() {
4447 wfDebug( __METHOD__
. "()\n" );
4449 if ( $this->mId
== 0 ) {
4453 $userblock = Block
::newFromTarget( $this->getName() );
4454 if ( !$userblock ) {
4458 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
4462 * Get whether the user is explicitly blocked from account creation.
4463 * @return bool|Block
4465 public function isBlockedFromCreateAccount() {
4466 $this->getBlockedStatus();
4467 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
4468 return $this->mBlock
;
4471 # T15611: if the IP address the user is trying to create an account from is
4472 # blocked with createaccount disabled, prevent new account creation there even
4473 # when the user is logged in
4474 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
4475 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
4477 return $this->mBlockedFromCreateAccount
instanceof Block
4478 && $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
4479 ?
$this->mBlockedFromCreateAccount
4484 * Get whether the user is blocked from using Special:Emailuser.
4487 public function isBlockedFromEmailuser() {
4488 $this->getBlockedStatus();
4489 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
4493 * Get whether the user is allowed to create an account.
4496 public function isAllowedToCreateAccount() {
4497 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
4501 * Get this user's personal page title.
4503 * @return Title User's personal page title
4505 public function getUserPage() {
4506 return Title
::makeTitle( NS_USER
, $this->getName() );
4510 * Get this user's talk page title.
4512 * @return Title User's talk page title
4514 public function getTalkPage() {
4515 $title = $this->getUserPage();
4516 return $title->getTalkPage();
4520 * Determine whether the user is a newbie. Newbies are either
4521 * anonymous IPs, or the most recently created accounts.
4524 public function isNewbie() {
4525 return !$this->isAllowed( 'autoconfirmed' );
4529 * Check to see if the given clear-text password is one of the accepted passwords
4530 * @deprecated since 1.27, use AuthManager instead
4531 * @param string $password User password
4532 * @return bool True if the given password is correct, otherwise False
4534 public function checkPassword( $password ) {
4535 $manager = AuthManager
::singleton();
4536 $reqs = AuthenticationRequest
::loadRequestsFromSubmission(
4537 $manager->getAuthenticationRequests( AuthManager
::ACTION_LOGIN
),
4539 'username' => $this->getName(),
4540 'password' => $password,
4543 $res = AuthManager
::singleton()->beginAuthentication( $reqs, 'null:' );
4544 switch ( $res->status
) {
4545 case AuthenticationResponse
::PASS
:
4547 case AuthenticationResponse
::FAIL
:
4548 // Hope it's not a PreAuthenticationProvider that failed...
4549 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
4550 ->info( __METHOD__
. ': Authentication failed: ' . $res->message
->plain() );
4553 throw new BadMethodCallException(
4554 'AuthManager returned a response unsupported by ' . __METHOD__
4560 * Check if the given clear-text password matches the temporary password
4561 * sent by e-mail for password reset operations.
4563 * @deprecated since 1.27, use AuthManager instead
4564 * @param string $plaintext
4565 * @return bool True if matches, false otherwise
4567 public function checkTemporaryPassword( $plaintext ) {
4568 // Can't check the temporary password individually.
4569 return $this->checkPassword( $plaintext );
4573 * Initialize (if necessary) and return a session token value
4574 * which can be used in edit forms to show that the user's
4575 * login credentials aren't being hijacked with a foreign form
4579 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4580 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4581 * @return MediaWiki\Session\Token The new edit token
4583 public function getEditTokenObject( $salt = '', $request = null ) {
4584 if ( $this->isAnon() ) {
4585 return new LoggedOutEditToken();
4589 $request = $this->getRequest();
4591 return $request->getSession()->getToken( $salt );
4595 * Initialize (if necessary) and return a session token value
4596 * which can be used in edit forms to show that the user's
4597 * login credentials aren't being hijacked with a foreign form
4600 * The $salt for 'edit' and 'csrf' tokens is the default (empty string).
4603 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4604 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4605 * @return string The new edit token
4607 public function getEditToken( $salt = '', $request = null ) {
4608 return $this->getEditTokenObject( $salt, $request )->toString();
4612 * Check given value against the token value stored in the session.
4613 * A match should confirm that the form was submitted from the
4614 * user's own login session, not a form submission from a third-party
4617 * @param string $val Input value to compare
4618 * @param string|array $salt Optional function-specific data for hashing
4619 * @param WebRequest|null $request Object to use or null to use $wgRequest
4620 * @param int $maxage Fail tokens older than this, in seconds
4621 * @return bool Whether the token matches
4623 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4624 return $this->getEditTokenObject( $salt, $request )->match( $val, $maxage );
4628 * Check given value against the token value stored in the session,
4629 * ignoring the suffix.
4631 * @param string $val Input value to compare
4632 * @param string|array $salt Optional function-specific data for hashing
4633 * @param WebRequest|null $request Object to use or null to use $wgRequest
4634 * @param int $maxage Fail tokens older than this, in seconds
4635 * @return bool Whether the token matches
4637 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4638 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . Token
::SUFFIX
;
4639 return $this->matchEditToken( $val, $salt, $request, $maxage );
4643 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4644 * mail to the user's given address.
4646 * @param string $type Message to send, either "created", "changed" or "set"
4649 public function sendConfirmationMail( $type = 'created' ) {
4651 $expiration = null; // gets passed-by-ref and defined in next line.
4652 $token = $this->confirmationToken( $expiration );
4653 $url = $this->confirmationTokenUrl( $token );
4654 $invalidateURL = $this->invalidationTokenUrl( $token );
4655 $this->saveSettings();
4657 if ( $type == 'created' ||
$type === false ) {
4658 $message = 'confirmemail_body';
4659 } elseif ( $type === true ) {
4660 $message = 'confirmemail_body_changed';
4662 // Messages: confirmemail_body_changed, confirmemail_body_set
4663 $message = 'confirmemail_body_' . $type;
4666 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4667 wfMessage( $message,
4668 $this->getRequest()->getIP(),
4671 $wgLang->userTimeAndDate( $expiration, $this ),
4673 $wgLang->userDate( $expiration, $this ),
4674 $wgLang->userTime( $expiration, $this ) )->text() );
4678 * Send an e-mail to this user's account. Does not check for
4679 * confirmed status or validity.
4681 * @param string $subject Message subject
4682 * @param string $body Message body
4683 * @param User|null $from Optional sending user; if unspecified, default
4684 * $wgPasswordSender will be used.
4685 * @param string $replyto Reply-To address
4688 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4689 global $wgPasswordSender;
4691 if ( $from instanceof User
) {
4692 $sender = MailAddress
::newFromUser( $from );
4694 $sender = new MailAddress( $wgPasswordSender,
4695 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4697 $to = MailAddress
::newFromUser( $this );
4699 return UserMailer
::send( $to, $sender, $subject, $body, [
4700 'replyTo' => $replyto,
4705 * Generate, store, and return a new e-mail confirmation code.
4706 * A hash (unsalted, since it's used as a key) is stored.
4708 * @note Call saveSettings() after calling this function to commit
4709 * this change to the database.
4711 * @param string &$expiration Accepts the expiration time
4712 * @return string New token
4714 protected function confirmationToken( &$expiration ) {
4715 global $wgUserEmailConfirmationTokenExpiry;
4717 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4718 $expiration = wfTimestamp( TS_MW
, $expires );
4720 $token = MWCryptRand
::generateHex( 32 );
4721 $hash = md5( $token );
4722 $this->mEmailToken
= $hash;
4723 $this->mEmailTokenExpires
= $expiration;
4728 * Return a URL the user can use to confirm their email address.
4729 * @param string $token Accepts the email confirmation token
4730 * @return string New token URL
4732 protected function confirmationTokenUrl( $token ) {
4733 return $this->getTokenUrl( 'ConfirmEmail', $token );
4737 * Return a URL the user can use to invalidate their email address.
4738 * @param string $token Accepts the email confirmation token
4739 * @return string New token URL
4741 protected function invalidationTokenUrl( $token ) {
4742 return $this->getTokenUrl( 'InvalidateEmail', $token );
4746 * Internal function to format the e-mail validation/invalidation URLs.
4747 * This uses a quickie hack to use the
4748 * hardcoded English names of the Special: pages, for ASCII safety.
4750 * @note Since these URLs get dropped directly into emails, using the
4751 * short English names avoids insanely long URL-encoded links, which
4752 * also sometimes can get corrupted in some browsers/mailers
4753 * (T8957 with Gmail and Internet Explorer).
4755 * @param string $page Special page
4756 * @param string $token
4757 * @return string Formatted URL
4759 protected function getTokenUrl( $page, $token ) {
4760 // Hack to bypass localization of 'Special:'
4761 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4762 return $title->getCanonicalURL();
4766 * Mark the e-mail address confirmed.
4768 * @note Call saveSettings() after calling this function to commit the change.
4772 public function confirmEmail() {
4773 // Check if it's already confirmed, so we don't touch the database
4774 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4775 if ( !$this->isEmailConfirmed() ) {
4776 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4777 Hooks
::run( 'ConfirmEmailComplete', [ $this ] );
4783 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4784 * address if it was already confirmed.
4786 * @note Call saveSettings() after calling this function to commit the change.
4787 * @return bool Returns true
4789 public function invalidateEmail() {
4791 $this->mEmailToken
= null;
4792 $this->mEmailTokenExpires
= null;
4793 $this->setEmailAuthenticationTimestamp( null );
4795 Hooks
::run( 'InvalidateEmailComplete', [ $this ] );
4800 * Set the e-mail authentication timestamp.
4801 * @param string $timestamp TS_MW timestamp
4803 public function setEmailAuthenticationTimestamp( $timestamp ) {
4805 $this->mEmailAuthenticated
= $timestamp;
4806 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
4810 * Is this user allowed to send e-mails within limits of current
4811 * site configuration?
4814 public function canSendEmail() {
4815 global $wgEnableEmail, $wgEnableUserEmail;
4816 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4819 $canSend = $this->isEmailConfirmed();
4820 // Avoid PHP 7.1 warning of passing $this by reference
4822 Hooks
::run( 'UserCanSendEmail', [ &$user, &$canSend ] );
4827 * Is this user allowed to receive e-mails within limits of current
4828 * site configuration?
4831 public function canReceiveEmail() {
4832 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4836 * Is this user's e-mail address valid-looking and confirmed within
4837 * limits of the current site configuration?
4839 * @note If $wgEmailAuthentication is on, this may require the user to have
4840 * confirmed their address by returning a code or using a password
4841 * sent to the address from the wiki.
4845 public function isEmailConfirmed() {
4846 global $wgEmailAuthentication;
4848 // Avoid PHP 7.1 warning of passing $this by reference
4851 if ( Hooks
::run( 'EmailConfirmed', [ &$user, &$confirmed ] ) ) {
4852 if ( $this->isAnon() ) {
4855 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4858 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4868 * Check whether there is an outstanding request for e-mail confirmation.
4871 public function isEmailConfirmationPending() {
4872 global $wgEmailAuthentication;
4873 return $wgEmailAuthentication &&
4874 !$this->isEmailConfirmed() &&
4875 $this->mEmailToken
&&
4876 $this->mEmailTokenExpires
> wfTimestamp();
4880 * Get the timestamp of account creation.
4882 * @return string|bool|null Timestamp of account creation, false for
4883 * non-existent/anonymous user accounts, or null if existing account
4884 * but information is not in database.
4886 public function getRegistration() {
4887 if ( $this->isAnon() ) {
4891 return $this->mRegistration
;
4895 * Get the timestamp of the first edit
4897 * @return string|bool Timestamp of first edit, or false for
4898 * non-existent/anonymous user accounts.
4900 public function getFirstEditTimestamp() {
4901 if ( $this->getId() == 0 ) {
4902 return false; // anons
4904 $dbr = wfGetDB( DB_REPLICA
);
4905 $actorWhere = ActorMigration
::newMigration()->getWhere( $dbr, 'rev_user', $this );
4906 $time = $dbr->selectField(
4907 [ 'revision' ] +
$actorWhere['tables'],
4909 [ $actorWhere['conds'] ],
4911 [ 'ORDER BY' => 'rev_timestamp ASC' ],
4912 $actorWhere['joins']
4915 return false; // no edits
4917 return wfTimestamp( TS_MW
, $time );
4921 * Get the permissions associated with a given list of groups
4923 * @param array $groups Array of Strings List of internal group names
4924 * @return array Array of Strings List of permission key names for given groups combined
4926 public static function getGroupPermissions( $groups ) {
4927 global $wgGroupPermissions, $wgRevokePermissions;
4929 // grant every granted permission first
4930 foreach ( $groups as $group ) {
4931 if ( isset( $wgGroupPermissions[$group] ) ) {
4932 $rights = array_merge( $rights,
4933 // array_filter removes empty items
4934 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4937 // now revoke the revoked permissions
4938 foreach ( $groups as $group ) {
4939 if ( isset( $wgRevokePermissions[$group] ) ) {
4940 $rights = array_diff( $rights,
4941 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4944 return array_unique( $rights );
4948 * Get all the groups who have a given permission
4950 * @param string $role Role to check
4951 * @return array Array of Strings List of internal group names with the given permission
4953 public static function getGroupsWithPermission( $role ) {
4954 global $wgGroupPermissions;
4955 $allowedGroups = [];
4956 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4957 if ( self
::groupHasPermission( $group, $role ) ) {
4958 $allowedGroups[] = $group;
4961 return $allowedGroups;
4965 * Check, if the given group has the given permission
4967 * If you're wanting to check whether all users have a permission, use
4968 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4972 * @param string $group Group to check
4973 * @param string $role Role to check
4976 public static function groupHasPermission( $group, $role ) {
4977 global $wgGroupPermissions, $wgRevokePermissions;
4978 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4979 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4983 * Check if all users may be assumed to have the given permission
4985 * We generally assume so if the right is granted to '*' and isn't revoked
4986 * on any group. It doesn't attempt to take grants or other extension
4987 * limitations on rights into account in the general case, though, as that
4988 * would require it to always return false and defeat the purpose.
4989 * Specifically, session-based rights restrictions (such as OAuth or bot
4990 * passwords) are applied based on the current session.
4993 * @param string $right Right to check
4996 public static function isEveryoneAllowed( $right ) {
4997 global $wgGroupPermissions, $wgRevokePermissions;
5000 // Use the cached results, except in unit tests which rely on
5001 // being able change the permission mid-request
5002 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
5003 return $cache[$right];
5006 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
5007 $cache[$right] = false;
5011 // If it's revoked anywhere, then everyone doesn't have it
5012 foreach ( $wgRevokePermissions as $rights ) {
5013 if ( isset( $rights[$right] ) && $rights[$right] ) {
5014 $cache[$right] = false;
5019 // Remove any rights that aren't allowed to the global-session user,
5020 // unless there are no sessions for this endpoint.
5021 if ( !defined( 'MW_NO_SESSION' ) ) {
5022 $allowedRights = SessionManager
::getGlobalSession()->getAllowedUserRights();
5023 if ( $allowedRights !== null && !in_array( $right, $allowedRights, true ) ) {
5024 $cache[$right] = false;
5029 // Allow extensions to say false
5030 if ( !Hooks
::run( 'UserIsEveryoneAllowed', [ $right ] ) ) {
5031 $cache[$right] = false;
5035 $cache[$right] = true;
5040 * Get the localized descriptive name for a group, if it exists
5041 * @deprecated since 1.29 Use UserGroupMembership::getGroupName instead
5043 * @param string $group Internal group name
5044 * @return string Localized descriptive group name
5046 public static function getGroupName( $group ) {
5047 wfDeprecated( __METHOD__
, '1.29' );
5048 return UserGroupMembership
::getGroupName( $group );
5052 * Get the localized descriptive name for a member of a group, if it exists
5053 * @deprecated since 1.29 Use UserGroupMembership::getGroupMemberName instead
5055 * @param string $group Internal group name
5056 * @param string $username Username for gender (since 1.19)
5057 * @return string Localized name for group member
5059 public static function getGroupMember( $group, $username = '#' ) {
5060 wfDeprecated( __METHOD__
, '1.29' );
5061 return UserGroupMembership
::getGroupMemberName( $group, $username );
5065 * Return the set of defined explicit groups.
5066 * The implicit groups (by default *, 'user' and 'autoconfirmed')
5067 * are not included, as they are defined automatically, not in the database.
5068 * @return array Array of internal group names
5070 public static function getAllGroups() {
5071 global $wgGroupPermissions, $wgRevokePermissions;
5073 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
5074 self
::getImplicitGroups()
5079 * Get a list of all available permissions.
5080 * @return string[] Array of permission names
5082 public static function getAllRights() {
5083 if ( self
::$mAllRights === false ) {
5084 global $wgAvailableRights;
5085 if ( count( $wgAvailableRights ) ) {
5086 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
5088 self
::$mAllRights = self
::$mCoreRights;
5090 Hooks
::run( 'UserGetAllRights', [ &self
::$mAllRights ] );
5092 return self
::$mAllRights;
5096 * Get a list of implicit groups
5097 * @return array Array of Strings Array of internal group names
5099 public static function getImplicitGroups() {
5100 global $wgImplicitGroups;
5102 $groups = $wgImplicitGroups;
5103 # Deprecated, use $wgImplicitGroups instead
5104 Hooks
::run( 'UserGetImplicitGroups', [ &$groups ], '1.25' );
5110 * Get the title of a page describing a particular group
5111 * @deprecated since 1.29 Use UserGroupMembership::getGroupPage instead
5113 * @param string $group Internal group name
5114 * @return Title|bool Title of the page if it exists, false otherwise
5116 public static function getGroupPage( $group ) {
5117 wfDeprecated( __METHOD__
, '1.29' );
5118 return UserGroupMembership
::getGroupPage( $group );
5122 * Create a link to the group in HTML, if available;
5123 * else return the group name.
5124 * @deprecated since 1.29 Use UserGroupMembership::getLink instead, or
5125 * make the link yourself if you need custom text
5127 * @param string $group Internal name of the group
5128 * @param string $text The text of the link
5129 * @return string HTML link to the group
5131 public static function makeGroupLinkHTML( $group, $text = '' ) {
5132 wfDeprecated( __METHOD__
, '1.29' );
5134 if ( $text == '' ) {
5135 $text = UserGroupMembership
::getGroupName( $group );
5137 $title = UserGroupMembership
::getGroupPage( $group );
5139 return MediaWikiServices
::getInstance()
5140 ->getLinkRenderer()->makeLink( $title, $text );
5142 return htmlspecialchars( $text );
5147 * Create a link to the group in Wikitext, if available;
5148 * else return the group name.
5149 * @deprecated since 1.29 Use UserGroupMembership::getLink instead, or
5150 * make the link yourself if you need custom text
5152 * @param string $group Internal name of the group
5153 * @param string $text The text of the link
5154 * @return string Wikilink to the group
5156 public static function makeGroupLinkWiki( $group, $text = '' ) {
5157 wfDeprecated( __METHOD__
, '1.29' );
5159 if ( $text == '' ) {
5160 $text = UserGroupMembership
::getGroupName( $group );
5162 $title = UserGroupMembership
::getGroupPage( $group );
5164 $page = $title->getFullText();
5165 return "[[$page|$text]]";
5172 * Returns an array of the groups that a particular group can add/remove.
5174 * @param string $group The group to check for whether it can add/remove
5175 * @return array Array( 'add' => array( addablegroups ),
5176 * 'remove' => array( removablegroups ),
5177 * 'add-self' => array( addablegroups to self),
5178 * 'remove-self' => array( removable groups from self) )
5180 public static function changeableByGroup( $group ) {
5181 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
5190 if ( empty( $wgAddGroups[$group] ) ) {
5191 // Don't add anything to $groups
5192 } elseif ( $wgAddGroups[$group] === true ) {
5193 // You get everything
5194 $groups['add'] = self
::getAllGroups();
5195 } elseif ( is_array( $wgAddGroups[$group] ) ) {
5196 $groups['add'] = $wgAddGroups[$group];
5199 // Same thing for remove
5200 if ( empty( $wgRemoveGroups[$group] ) ) {
5202 } elseif ( $wgRemoveGroups[$group] === true ) {
5203 $groups['remove'] = self
::getAllGroups();
5204 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
5205 $groups['remove'] = $wgRemoveGroups[$group];
5208 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
5209 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
5210 foreach ( $wgGroupsAddToSelf as $key => $value ) {
5211 if ( is_int( $key ) ) {
5212 $wgGroupsAddToSelf['user'][] = $value;
5217 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
5218 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
5219 if ( is_int( $key ) ) {
5220 $wgGroupsRemoveFromSelf['user'][] = $value;
5225 // Now figure out what groups the user can add to him/herself
5226 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
5228 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
5229 // No idea WHY this would be used, but it's there
5230 $groups['add-self'] = self
::getAllGroups();
5231 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
5232 $groups['add-self'] = $wgGroupsAddToSelf[$group];
5235 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
5237 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
5238 $groups['remove-self'] = self
::getAllGroups();
5239 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
5240 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
5247 * Returns an array of groups that this user can add and remove
5248 * @return array Array( 'add' => array( addablegroups ),
5249 * 'remove' => array( removablegroups ),
5250 * 'add-self' => array( addablegroups to self),
5251 * 'remove-self' => array( removable groups from self) )
5253 public function changeableGroups() {
5254 if ( $this->isAllowed( 'userrights' ) ) {
5255 // This group gives the right to modify everything (reverse-
5256 // compatibility with old "userrights lets you change
5258 // Using array_merge to make the groups reindexed
5259 $all = array_merge( self
::getAllGroups() );
5268 // Okay, it's not so simple, we will have to go through the arrays
5275 $addergroups = $this->getEffectiveGroups();
5277 foreach ( $addergroups as $addergroup ) {
5278 $groups = array_merge_recursive(
5279 $groups, $this->changeableByGroup( $addergroup )
5281 $groups['add'] = array_unique( $groups['add'] );
5282 $groups['remove'] = array_unique( $groups['remove'] );
5283 $groups['add-self'] = array_unique( $groups['add-self'] );
5284 $groups['remove-self'] = array_unique( $groups['remove-self'] );
5290 * Deferred version of incEditCountImmediate()
5292 * This function, rather than incEditCountImmediate(), should be used for
5293 * most cases as it avoids potential deadlocks caused by concurrent editing.
5295 public function incEditCount() {
5296 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle(
5298 $this->incEditCountImmediate();
5305 * Increment the user's edit-count field.
5306 * Will have no effect for anonymous users.
5309 public function incEditCountImmediate() {
5310 if ( $this->isAnon() ) {
5314 $dbw = wfGetDB( DB_MASTER
);
5315 // No rows will be "affected" if user_editcount is NULL
5318 [ 'user_editcount=user_editcount+1' ],
5319 [ 'user_id' => $this->getId(), 'user_editcount IS NOT NULL' ],
5322 // Lazy initialization check...
5323 if ( $dbw->affectedRows() == 0 ) {
5324 // Now here's a goddamn hack...
5325 $dbr = wfGetDB( DB_REPLICA
);
5326 if ( $dbr !== $dbw ) {
5327 // If we actually have a replica DB server, the count is
5328 // at least one behind because the current transaction
5329 // has not been committed and replicated.
5330 $this->mEditCount
= $this->initEditCount( 1 );
5332 // But if DB_REPLICA is selecting the master, then the
5333 // count we just read includes the revision that was
5334 // just added in the working transaction.
5335 $this->mEditCount
= $this->initEditCount();
5338 if ( $this->mEditCount
=== null ) {
5339 $this->getEditCount();
5340 $dbr = wfGetDB( DB_REPLICA
);
5341 $this->mEditCount +
= ( $dbr !== $dbw ) ?
1 : 0;
5343 $this->mEditCount++
;
5346 // Edit count in user cache too
5347 $this->invalidateCache();
5351 * Initialize user_editcount from data out of the revision table
5353 * @param int $add Edits to add to the count from the revision table
5354 * @return int Number of edits
5356 protected function initEditCount( $add = 0 ) {
5357 // Pull from a replica DB to be less cruel to servers
5358 // Accuracy isn't the point anyway here
5359 $dbr = wfGetDB( DB_REPLICA
);
5360 $actorWhere = ActorMigration
::newMigration()->getWhere( $dbr, 'rev_user', $this );
5361 $count = (int)$dbr->selectField(
5362 [ 'revision' ] +
$actorWhere['tables'],
5364 [ $actorWhere['conds'] ],
5367 $actorWhere['joins']
5369 $count = $count +
$add;
5371 $dbw = wfGetDB( DB_MASTER
);
5374 [ 'user_editcount' => $count ],
5375 [ 'user_id' => $this->getId() ],
5383 * Get the description of a given right
5386 * @param string $right Right to query
5387 * @return string Localized description of the right
5389 public static function getRightDescription( $right ) {
5390 $key = "right-$right";
5391 $msg = wfMessage( $key );
5392 return $msg->isDisabled() ?
$right : $msg->text();
5396 * Get the name of a given grant
5399 * @param string $grant Grant to query
5400 * @return string Localized name of the grant
5402 public static function getGrantName( $grant ) {
5403 $key = "grant-$grant";
5404 $msg = wfMessage( $key );
5405 return $msg->isDisabled() ?
$grant : $msg->text();
5409 * Add a newuser log entry for this user.
5410 * Before 1.19 the return value was always true.
5412 * @deprecated since 1.27, AuthManager handles logging
5413 * @param string|bool $action Account creation type.
5414 * - String, one of the following values:
5415 * - 'create' for an anonymous user creating an account for himself.
5416 * This will force the action's performer to be the created user itself,
5417 * no matter the value of $wgUser
5418 * - 'create2' for a logged in user creating an account for someone else
5419 * - 'byemail' when the created user will receive its password by e-mail
5420 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
5421 * - Boolean means whether the account was created by e-mail (deprecated):
5422 * - true will be converted to 'byemail'
5423 * - false will be converted to 'create' if this object is the same as
5424 * $wgUser and to 'create2' otherwise
5425 * @param string $reason User supplied reason
5428 public function addNewUserLogEntry( $action = false, $reason = '' ) {
5429 return true; // disabled
5433 * Add an autocreate newuser log entry for this user
5434 * Used by things like CentralAuth and perhaps other authplugins.
5435 * Consider calling addNewUserLogEntry() directly instead.
5437 * @deprecated since 1.27, AuthManager handles logging
5440 public function addNewUserLogEntryAutoCreate() {
5441 $this->addNewUserLogEntry( 'autocreate' );
5447 * Load the user options either from cache, the database or an array
5449 * @param array $data Rows for the current user out of the user_properties table
5451 protected function loadOptions( $data = null ) {
5456 if ( $this->mOptionsLoaded
) {
5460 $this->mOptions
= self
::getDefaultOptions();
5462 if ( !$this->getId() ) {
5463 // For unlogged-in users, load language/variant options from request.
5464 // There's no need to do it for logged-in users: they can set preferences,
5465 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5466 // so don't override user's choice (especially when the user chooses site default).
5467 $variant = $wgContLang->getDefaultVariant();
5468 $this->mOptions
['variant'] = $variant;
5469 $this->mOptions
['language'] = $variant;
5470 $this->mOptionsLoaded
= true;
5474 // Maybe load from the object
5475 if ( !is_null( $this->mOptionOverrides
) ) {
5476 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5477 foreach ( $this->mOptionOverrides
as $key => $value ) {
5478 $this->mOptions
[$key] = $value;
5481 if ( !is_array( $data ) ) {
5482 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5483 // Load from database
5484 $dbr = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
5485 ?
wfGetDB( DB_MASTER
)
5486 : wfGetDB( DB_REPLICA
);
5488 $res = $dbr->select(
5490 [ 'up_property', 'up_value' ],
5491 [ 'up_user' => $this->getId() ],
5495 $this->mOptionOverrides
= [];
5497 foreach ( $res as $row ) {
5498 // Convert '0' to 0. PHP's boolean conversion considers them both
5499 // false, but e.g. JavaScript considers the former as true.
5500 // @todo: T54542 Somehow determine the desired type (string/int/bool)
5501 // and convert all values here.
5502 if ( $row->up_value
=== '0' ) {
5505 $data[$row->up_property
] = $row->up_value
;
5509 // Convert the email blacklist from a new line delimited string
5510 // to an array of ids.
5511 if ( isset( $data['email-blacklist'] ) && $data['email-blacklist'] ) {
5512 $data['email-blacklist'] = array_map( 'intval', explode( "\n", $data['email-blacklist'] ) );
5515 foreach ( $data as $property => $value ) {
5516 $this->mOptionOverrides
[$property] = $value;
5517 $this->mOptions
[$property] = $value;
5521 $this->mOptionsLoaded
= true;
5523 Hooks
::run( 'UserLoadOptions', [ $this, &$this->mOptions
] );
5527 * Saves the non-default options for this user, as previously set e.g. via
5528 * setOption(), in the database's "user_properties" (preferences) table.
5529 * Usually used via saveSettings().
5531 protected function saveOptions() {
5532 $this->loadOptions();
5534 // Not using getOptions(), to keep hidden preferences in database
5535 $saveOptions = $this->mOptions
;
5537 // Convert usernames to ids.
5538 if ( isset( $this->mOptions
['email-blacklist'] ) ) {
5539 if ( $this->mOptions
['email-blacklist'] ) {
5540 $value = $this->mOptions
['email-blacklist'];
5541 // Email Blacklist may be an array of ids or a string of new line
5542 // delimnated user names.
5543 if ( is_array( $value ) ) {
5544 $ids = array_filter( $value, 'is_numeric' );
5546 $lookup = CentralIdLookup
::factory();
5547 $ids = $lookup->centralIdsFromNames( explode( "\n", $value ), $this );
5549 $this->mOptions
['email-blacklist'] = $ids;
5550 $saveOptions['email-blacklist'] = implode( "\n", $this->mOptions
['email-blacklist'] );
5552 // If the blacklist is empty, set it to null rather than an empty string.
5553 $this->mOptions
['email-blacklist'] = null;
5557 // Allow hooks to abort, for instance to save to a global profile.
5558 // Reset options to default state before saving.
5559 if ( !Hooks
::run( 'UserSaveOptions', [ $this, &$saveOptions ] ) ) {
5563 $userId = $this->getId();
5565 $insert_rows = []; // all the new preference rows
5566 foreach ( $saveOptions as $key => $value ) {
5567 // Don't bother storing default values
5568 $defaultOption = self
::getDefaultOption( $key );
5569 if ( ( $defaultOption === null && $value !== false && $value !== null )
5570 ||
$value != $defaultOption
5573 'up_user' => $userId,
5574 'up_property' => $key,
5575 'up_value' => $value,
5580 $dbw = wfGetDB( DB_MASTER
);
5582 $res = $dbw->select( 'user_properties',
5583 [ 'up_property', 'up_value' ], [ 'up_user' => $userId ], __METHOD__
);
5585 // Find prior rows that need to be removed or updated. These rows will
5586 // all be deleted (the latter so that INSERT IGNORE applies the new values).
5588 foreach ( $res as $row ) {
5589 if ( !isset( $saveOptions[$row->up_property
] )
5590 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
5592 $keysDelete[] = $row->up_property
;
5596 if ( count( $keysDelete ) ) {
5597 // Do the DELETE by PRIMARY KEY for prior rows.
5598 // In the past a very large portion of calls to this function are for setting
5599 // 'rememberpassword' for new accounts (a preference that has since been removed).
5600 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5601 // caused gap locks on [max user ID,+infinity) which caused high contention since
5602 // updates would pile up on each other as they are for higher (newer) user IDs.
5603 // It might not be necessary these days, but it shouldn't hurt either.
5604 $dbw->delete( 'user_properties',
5605 [ 'up_user' => $userId, 'up_property' => $keysDelete ], __METHOD__
);
5607 // Insert the new preference rows
5608 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, [ 'IGNORE' ] );
5612 * Return the list of user fields that should be selected to create
5613 * a new user object.
5614 * @deprecated since 1.31, use self::getQueryInfo() instead.
5617 public static function selectFields() {
5618 wfDeprecated( __METHOD__
, '1.31' );
5626 'user_email_authenticated',
5628 'user_email_token_expires',
5629 'user_registration',
5635 * Return the tables, fields, and join conditions to be selected to create
5636 * a new user object.
5638 * @return array With three keys:
5639 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
5640 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
5641 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
5643 public static function getQueryInfo() {
5644 global $wgActorTableSchemaMigrationStage;
5647 'tables' => [ 'user' ],
5655 'user_email_authenticated',
5657 'user_email_token_expires',
5658 'user_registration',
5663 if ( $wgActorTableSchemaMigrationStage > MIGRATION_OLD
) {
5664 $ret['tables']['user_actor'] = 'actor';
5665 $ret['fields'][] = 'user_actor.actor_id';
5666 $ret['joins']['user_actor'] = [
5667 $wgActorTableSchemaMigrationStage === MIGRATION_NEW ?
'JOIN' : 'LEFT JOIN',
5668 [ 'user_actor.actor_user = user_id' ]
5675 * Factory function for fatal permission-denied errors
5678 * @param string $permission User right required
5681 static function newFatalPermissionDeniedStatus( $permission ) {
5685 foreach ( self
::getGroupsWithPermission( $permission ) as $group ) {
5686 $groups[] = UserGroupMembership
::getLink( $group, RequestContext
::getMain(), 'wiki' );
5690 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5692 return Status
::newFatal( 'badaccess-group0' );
5697 * Get a new instance of this user that was loaded from the master via a locking read
5699 * Use this instead of the main context User when updating that user. This avoids races
5700 * where that user was loaded from a replica DB or even the master but without proper locks.
5702 * @return User|null Returns null if the user was not found in the DB
5705 public function getInstanceForUpdate() {
5706 if ( !$this->getId() ) {
5707 return null; // anon
5710 $user = self
::newFromId( $this->getId() );
5711 if ( !$user->loadFromId( self
::READ_EXCLUSIVE
) ) {
5719 * Checks if two user objects point to the same user.
5721 * @since 1.25 ; takes a UserIdentity instead of a User since 1.32
5722 * @param UserIdentity $user
5725 public function equals( UserIdentity
$user ) {
5726 // XXX it's not clear whether central ID providers are supposed to obey this
5727 return $this->getName() === $user->getName();