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|null $data Further data to load into the object
763 * (see User::loadFromRow for valid keys)
766 public static function newFromRow( $row, $data = null ) {
768 $user->loadFromRow( $row, $data );
773 * Static factory method for creation of a "system" user from username.
775 * A "system" user is an account that's used to attribute logged actions
776 * taken by MediaWiki itself, as opposed to a bot or human user. Examples
777 * might include the 'Maintenance script' or 'Conversion script' accounts
778 * used by various scripts in the maintenance/ directory or accounts such
779 * as 'MediaWiki message delivery' used by the MassMessage extension.
781 * This can optionally create the user if it doesn't exist, and "steal" the
782 * account if it does exist.
784 * "Stealing" an existing user is intended to make it impossible for normal
785 * authentication processes to use the account, effectively disabling the
786 * account for normal use:
787 * - Email is invalidated, to prevent account recovery by emailing a
788 * temporary password and to disassociate the account from the existing
790 * - The token is set to a magic invalid value, to kill existing sessions
791 * and to prevent $this->setToken() calls from resetting the token to a
793 * - SessionManager is instructed to prevent new sessions for the user, to
794 * do things like deauthorizing OAuth consumers.
795 * - AuthManager is instructed to revoke access, to invalidate or remove
796 * passwords and other credentials.
798 * @param string $name Username
799 * @param array $options Options are:
800 * - validate: As for User::getCanonicalName(), default 'valid'
801 * - create: Whether to create the user if it doesn't already exist, default true
802 * - steal: Whether to "disable" the account for normal use if it already
803 * exists, default false
807 public static function newSystemUser( $name, $options = [] ) {
809 'validate' => 'valid',
814 $name = self
::getCanonicalName( $name, $options['validate'] );
815 if ( $name === false ) {
819 $dbr = wfGetDB( DB_REPLICA
);
820 $userQuery = self
::getQueryInfo();
821 $row = $dbr->selectRow(
822 $userQuery['tables'],
823 $userQuery['fields'],
824 [ 'user_name' => $name ],
830 // Try the master database...
831 $dbw = wfGetDB( DB_MASTER
);
832 $row = $dbw->selectRow(
833 $userQuery['tables'],
834 $userQuery['fields'],
835 [ 'user_name' => $name ],
843 // No user. Create it?
844 return $options['create']
845 ? self
::createNew( $name, [ 'token' => self
::INVALID_TOKEN
] )
849 $user = self
::newFromRow( $row );
851 // A user is considered to exist as a non-system user if it can
852 // authenticate, or has an email set, or has a non-invalid token.
853 if ( $user->mEmail ||
$user->mToken
!== self
::INVALID_TOKEN ||
854 AuthManager
::singleton()->userCanAuthenticate( $name )
856 // User exists. Steal it?
857 if ( !$options['steal'] ) {
861 AuthManager
::singleton()->revokeAccessForUser( $name );
863 $user->invalidateEmail();
864 $user->mToken
= self
::INVALID_TOKEN
;
865 $user->saveSettings();
866 SessionManager
::singleton()->preventSessionsForUser( $user->getName() );
875 * Get the username corresponding to a given user ID
876 * @param int $id User ID
877 * @return string|bool The corresponding username
879 public static function whoIs( $id ) {
880 return UserCache
::singleton()->getProp( $id, 'name' );
884 * Get the real name of a user given their user ID
886 * @param int $id User ID
887 * @return string|bool The corresponding user's real name
889 public static function whoIsReal( $id ) {
890 return UserCache
::singleton()->getProp( $id, 'real_name' );
894 * Get database id given a user name
895 * @param string $name Username
896 * @param int $flags User::READ_* constant bitfield
897 * @return int|null The corresponding user's ID, or null if user is nonexistent
899 public static function idFromName( $name, $flags = self
::READ_NORMAL
) {
900 $nt = Title
::makeTitleSafe( NS_USER
, $name );
901 if ( is_null( $nt ) ) {
906 if ( !( $flags & self
::READ_LATEST
) && array_key_exists( $name, self
::$idCacheByName ) ) {
907 return self
::$idCacheByName[$name];
910 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
911 $db = wfGetDB( $index );
916 [ 'user_name' => $nt->getText() ],
921 if ( $s === false ) {
924 $result = $s->user_id
;
927 self
::$idCacheByName[$name] = $result;
929 if ( count( self
::$idCacheByName ) > 1000 ) {
930 self
::$idCacheByName = [];
937 * Reset the cache used in idFromName(). For use in tests.
939 public static function resetIdByNameCache() {
940 self
::$idCacheByName = [];
944 * Does the string match an anonymous IP address?
946 * This function exists for username validation, in order to reject
947 * usernames which are similar in form to IP addresses. Strings such
948 * as 300.300.300.300 will return true because it looks like an IP
949 * address, despite not being strictly valid.
951 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
952 * address because the usemod software would "cloak" anonymous IP
953 * addresses like this, if we allowed accounts like this to be created
954 * new users could get the old edits of these anonymous users.
956 * @param string $name Name to match
959 public static function isIP( $name ) {
960 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
961 || IP
::isIPv6( $name );
965 * Is the user an IP range?
970 public function isIPRange() {
971 return IP
::isValidRange( $this->mName
);
975 * Is the input a valid username?
977 * Checks if the input is a valid username, we don't want an empty string,
978 * an IP address, anything that contains slashes (would mess up subpages),
979 * is longer than the maximum allowed username size or doesn't begin with
982 * @param string $name Name to match
985 public static function isValidUserName( $name ) {
986 global $wgContLang, $wgMaxNameChars;
989 || self
::isIP( $name )
990 ||
strpos( $name, '/' ) !== false
991 ||
strlen( $name ) > $wgMaxNameChars
992 ||
$name != $wgContLang->ucfirst( $name )
997 // Ensure that the name can't be misresolved as a different title,
998 // such as with extra namespace keys at the start.
999 $parsed = Title
::newFromText( $name );
1000 if ( is_null( $parsed )
1001 ||
$parsed->getNamespace()
1002 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
1006 // Check an additional blacklist of troublemaker characters.
1007 // Should these be merged into the title char list?
1008 $unicodeBlacklist = '/[' .
1009 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
1010 '\x{00a0}' . # non-breaking space
1011 '\x{2000}-\x{200f}' . # various whitespace
1012 '\x{2028}-\x{202f}' . # breaks and control chars
1013 '\x{3000}' . # ideographic space
1014 '\x{e000}-\x{f8ff}' . # private use
1016 if ( preg_match( $unicodeBlacklist, $name ) ) {
1024 * Usernames which fail to pass this function will be blocked
1025 * from user login and new account registrations, but may be used
1026 * internally by batch processes.
1028 * If an account already exists in this form, login will be blocked
1029 * by a failure to pass this function.
1031 * @param string $name Name to match
1034 public static function isUsableName( $name ) {
1035 global $wgReservedUsernames;
1036 // Must be a valid username, obviously ;)
1037 if ( !self
::isValidUserName( $name ) ) {
1041 static $reservedUsernames = false;
1042 if ( !$reservedUsernames ) {
1043 $reservedUsernames = $wgReservedUsernames;
1044 Hooks
::run( 'UserGetReservedNames', [ &$reservedUsernames ] );
1047 // Certain names may be reserved for batch processes.
1048 foreach ( $reservedUsernames as $reserved ) {
1049 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
1050 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
1052 if ( $reserved == $name ) {
1060 * Return the users who are members of the given group(s). In case of multiple groups,
1061 * users who are members of at least one of them are returned.
1063 * @param string|array $groups A single group name or an array of group names
1064 * @param int $limit Max number of users to return. The actual limit will never exceed 5000
1065 * records; larger values are ignored.
1066 * @param int|null $after ID the user to start after
1067 * @return UserArrayFromResult
1069 public static function findUsersByGroup( $groups, $limit = 5000, $after = null ) {
1070 if ( $groups === [] ) {
1071 return UserArrayFromResult
::newFromIDs( [] );
1074 $groups = array_unique( (array)$groups );
1075 $limit = min( 5000, $limit );
1077 $conds = [ 'ug_group' => $groups ];
1078 if ( $after !== null ) {
1079 $conds[] = 'ug_user > ' . (int)$after;
1082 $dbr = wfGetDB( DB_REPLICA
);
1083 $ids = $dbr->selectFieldValues(
1090 'ORDER BY' => 'ug_user',
1094 return UserArray
::newFromIDs( $ids );
1098 * Usernames which fail to pass this function will be blocked
1099 * from new account registrations, but may be used internally
1100 * either by batch processes or by user accounts which have
1101 * already been created.
1103 * Additional blacklisting may be added here rather than in
1104 * isValidUserName() to avoid disrupting existing accounts.
1106 * @param string $name String to match
1109 public static function isCreatableName( $name ) {
1110 global $wgInvalidUsernameCharacters;
1112 // Ensure that the username isn't longer than 235 bytes, so that
1113 // (at least for the builtin skins) user javascript and css files
1114 // will work. (T25080)
1115 if ( strlen( $name ) > 235 ) {
1116 wfDebugLog( 'username', __METHOD__
.
1117 ": '$name' invalid due to length" );
1121 // Preg yells if you try to give it an empty string
1122 if ( $wgInvalidUsernameCharacters !== '' ) {
1123 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
1124 wfDebugLog( 'username', __METHOD__
.
1125 ": '$name' invalid due to wgInvalidUsernameCharacters" );
1130 return self
::isUsableName( $name );
1134 * Is the input a valid password for this user?
1136 * @param string $password Desired password
1139 public function isValidPassword( $password ) {
1140 // simple boolean wrapper for getPasswordValidity
1141 return $this->getPasswordValidity( $password ) === true;
1145 * Given unvalidated password input, return error message on failure.
1147 * @param string $password Desired password
1148 * @return bool|string|array True on success, string or array of error message on failure
1150 public function getPasswordValidity( $password ) {
1151 $result = $this->checkPasswordValidity( $password );
1152 if ( $result->isGood() ) {
1156 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
1157 $messages[] = $error['message'];
1159 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
1160 $messages[] = $warning['message'];
1162 if ( count( $messages ) === 1 ) {
1163 return $messages[0];
1170 * Check if this is a valid password for this user
1172 * Create a Status object based on the password's validity.
1173 * The Status should be set to fatal if the user should not
1174 * be allowed to log in, and should have any errors that
1175 * would block changing the password.
1177 * If the return value of this is not OK, the password
1178 * should not be checked. If the return value is not Good,
1179 * the password can be checked, but the user should not be
1180 * able to set their password to this.
1182 * @param string $password Desired password
1186 public function checkPasswordValidity( $password ) {
1187 global $wgPasswordPolicy;
1189 $upp = new UserPasswordPolicy(
1190 $wgPasswordPolicy['policies'],
1191 $wgPasswordPolicy['checks']
1194 $status = Status
::newGood();
1195 $result = false; // init $result to false for the internal checks
1197 if ( !Hooks
::run( 'isValidPassword', [ $password, &$result, $this ] ) ) {
1198 $status->error( $result );
1202 if ( $result === false ) {
1203 $status->merge( $upp->checkUserPassword( $this, $password ) );
1205 } elseif ( $result === true ) {
1208 $status->error( $result );
1209 return $status; // the isValidPassword hook set a string $result and returned true
1214 * Given unvalidated user input, return a canonical username, or false if
1215 * the username is invalid.
1216 * @param string $name User input
1217 * @param string|bool $validate Type of validation to use:
1218 * - false No validation
1219 * - 'valid' Valid for batch processes
1220 * - 'usable' Valid for batch processes and login
1221 * - 'creatable' Valid for batch processes, login and account creation
1223 * @throws InvalidArgumentException
1224 * @return bool|string
1226 public static function getCanonicalName( $name, $validate = 'valid' ) {
1227 // Force usernames to capital
1229 $name = $wgContLang->ucfirst( $name );
1231 # Reject names containing '#'; these will be cleaned up
1232 # with title normalisation, but then it's too late to
1234 if ( strpos( $name, '#' ) !== false ) {
1238 // Clean up name according to title rules,
1239 // but only when validation is requested (T14654)
1240 $t = ( $validate !== false ) ?
1241 Title
::newFromText( $name, NS_USER
) : Title
::makeTitle( NS_USER
, $name );
1242 // Check for invalid titles
1243 if ( is_null( $t ) ||
$t->getNamespace() !== NS_USER ||
$t->isExternal() ) {
1247 // Reject various classes of invalid names
1248 $name = AuthManager
::callLegacyAuthPlugin(
1249 'getCanonicalName', [ $t->getText() ], $t->getText()
1252 switch ( $validate ) {
1256 if ( !self
::isValidUserName( $name ) ) {
1261 if ( !self
::isUsableName( $name ) ) {
1266 if ( !self
::isCreatableName( $name ) ) {
1271 throw new InvalidArgumentException(
1272 'Invalid parameter value for $validate in ' . __METHOD__
);
1278 * Return a random password.
1280 * @deprecated since 1.27, use PasswordFactory::generateRandomPasswordString()
1281 * @return string New random password
1283 public static function randomPassword() {
1284 global $wgMinimalPasswordLength;
1285 return PasswordFactory
::generateRandomPasswordString( $wgMinimalPasswordLength );
1289 * Set cached properties to default.
1291 * @note This no longer clears uncached lazy-initialised properties;
1292 * the constructor does that instead.
1294 * @param string|bool $name
1296 public function loadDefaults( $name = false ) {
1298 $this->mName
= $name;
1299 $this->mActorId
= null;
1300 $this->mRealName
= '';
1302 $this->mOptionOverrides
= null;
1303 $this->mOptionsLoaded
= false;
1305 $loggedOut = $this->mRequest
&& !defined( 'MW_NO_SESSION' )
1306 ?
$this->mRequest
->getSession()->getLoggedOutTimestamp() : 0;
1307 if ( $loggedOut !== 0 ) {
1308 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1310 $this->mTouched
= '1'; # Allow any pages to be cached
1313 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1314 $this->mEmailAuthenticated
= null;
1315 $this->mEmailToken
= '';
1316 $this->mEmailTokenExpires
= null;
1317 $this->mRegistration
= wfTimestamp( TS_MW
);
1318 $this->mGroupMemberships
= [];
1320 Hooks
::run( 'UserLoadDefaults', [ $this, $name ] );
1324 * Return whether an item has been loaded.
1326 * @param string $item Item to check. Current possibilities:
1330 * @param string $all 'all' to check if the whole object has been loaded
1331 * or any other string to check if only the item is available (e.g.
1335 public function isItemLoaded( $item, $all = 'all' ) {
1336 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1337 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1341 * Set that an item has been loaded
1343 * @param string $item
1345 protected function setItemLoaded( $item ) {
1346 if ( is_array( $this->mLoadedItems
) ) {
1347 $this->mLoadedItems
[$item] = true;
1352 * Load user data from the session.
1354 * @return bool True if the user is logged in, false otherwise.
1356 private function loadFromSession() {
1359 Hooks
::run( 'UserLoadFromSession', [ $this, &$result ], '1.27' );
1360 if ( $result !== null ) {
1364 // MediaWiki\Session\Session already did the necessary authentication of the user
1365 // returned here, so just use it if applicable.
1366 $session = $this->getRequest()->getSession();
1367 $user = $session->getUser();
1368 if ( $user->isLoggedIn() ) {
1369 $this->loadFromUserObject( $user );
1370 if ( $user->isBlocked() ) {
1371 // If this user is autoblocked, set a cookie to track the Block. This has to be done on
1372 // every session load, because an autoblocked editor might not edit again from the same
1373 // IP address after being blocked.
1374 $this->trackBlockWithCookie();
1377 // Other code expects these to be set in the session, so set them.
1378 $session->set( 'wsUserID', $this->getId() );
1379 $session->set( 'wsUserName', $this->getName() );
1380 $session->set( 'wsToken', $this->getToken() );
1389 * Set the 'BlockID' cookie depending on block type and user authentication status.
1391 public function trackBlockWithCookie() {
1392 $block = $this->getBlock();
1393 if ( $block && $this->getRequest()->getCookie( 'BlockID' ) === null ) {
1394 $config = RequestContext
::getMain()->getConfig();
1395 $shouldSetCookie = false;
1397 if ( $this->isAnon() && $config->get( 'CookieSetOnIpBlock' ) ) {
1398 // If user is logged-out, set a cookie to track the Block
1399 $shouldSetCookie = in_array( $block->getType(), [
1400 Block
::TYPE_IP
, Block
::TYPE_RANGE
1402 if ( $shouldSetCookie ) {
1403 $block->setCookie( $this->getRequest()->response() );
1405 // temporary measure the use of cookies on ip blocks
1406 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
1407 $stats->increment( 'block.ipblock.setCookie.success' );
1409 } elseif ( $this->isLoggedIn() && $config->get( 'CookieSetOnAutoblock' ) ) {
1410 $shouldSetCookie = $block->getType() === Block
::TYPE_USER
&& $block->isAutoblocking();
1411 if ( $shouldSetCookie ) {
1412 $block->setCookie( $this->getRequest()->response() );
1419 * Load user and user_group data from the database.
1420 * $this->mId must be set, this is how the user is identified.
1422 * @param int $flags User::READ_* constant bitfield
1423 * @return bool True if the user exists, false if the user is anonymous
1425 public function loadFromDatabase( $flags = self
::READ_LATEST
) {
1427 $this->mId
= intval( $this->mId
);
1429 if ( !$this->mId
) {
1430 // Anonymous users are not in the database
1431 $this->loadDefaults();
1435 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
1436 $db = wfGetDB( $index );
1438 $userQuery = self
::getQueryInfo();
1439 $s = $db->selectRow(
1440 $userQuery['tables'],
1441 $userQuery['fields'],
1442 [ 'user_id' => $this->mId
],
1448 $this->queryFlagsUsed
= $flags;
1449 Hooks
::run( 'UserLoadFromDatabase', [ $this, &$s ] );
1451 if ( $s !== false ) {
1452 // Initialise user table data
1453 $this->loadFromRow( $s );
1454 $this->mGroupMemberships
= null; // deferred
1455 $this->getEditCount(); // revalidation for nulls
1460 $this->loadDefaults();
1466 * Initialize this object from a row from the user table.
1468 * @param stdClass $row Row from the user table to load.
1469 * @param array|null $data Further user data to load into the object
1471 * user_groups Array of arrays or stdClass result rows out of the user_groups
1472 * table. Previously you were supposed to pass an array of strings
1473 * here, but we also need expiry info nowadays, so an array of
1474 * strings is ignored.
1475 * user_properties Array with properties out of the user_properties table
1477 protected function loadFromRow( $row, $data = null ) {
1478 global $wgActorTableSchemaMigrationStage;
1480 if ( !is_object( $row ) ) {
1481 throw new InvalidArgumentException( '$row must be an object' );
1486 $this->mGroupMemberships
= null; // deferred
1488 if ( $wgActorTableSchemaMigrationStage > MIGRATION_OLD
) {
1489 if ( isset( $row->actor_id
) ) {
1490 $this->mActorId
= (int)$row->actor_id
;
1491 if ( $this->mActorId
!== 0 ) {
1492 $this->mFrom
= 'actor';
1494 $this->setItemLoaded( 'actor' );
1500 if ( isset( $row->user_name
) && $row->user_name
!== '' ) {
1501 $this->mName
= $row->user_name
;
1502 $this->mFrom
= 'name';
1503 $this->setItemLoaded( 'name' );
1508 if ( isset( $row->user_real_name
) ) {
1509 $this->mRealName
= $row->user_real_name
;
1510 $this->setItemLoaded( 'realname' );
1515 if ( isset( $row->user_id
) ) {
1516 $this->mId
= intval( $row->user_id
);
1517 if ( $this->mId
!== 0 ) {
1518 $this->mFrom
= 'id';
1520 $this->setItemLoaded( 'id' );
1525 if ( isset( $row->user_id
) && isset( $row->user_name
) && $row->user_name
!== '' ) {
1526 self
::$idCacheByName[$row->user_name
] = $row->user_id
;
1529 if ( isset( $row->user_editcount
) ) {
1530 $this->mEditCount
= $row->user_editcount
;
1535 if ( isset( $row->user_touched
) ) {
1536 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1541 if ( isset( $row->user_token
) ) {
1542 // The definition for the column is binary(32), so trim the NULs
1543 // that appends. The previous definition was char(32), so trim
1545 $this->mToken
= rtrim( $row->user_token
, " \0" );
1546 if ( $this->mToken
=== '' ) {
1547 $this->mToken
= null;
1553 if ( isset( $row->user_email
) ) {
1554 $this->mEmail
= $row->user_email
;
1555 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1556 $this->mEmailToken
= $row->user_email_token
;
1557 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1558 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1564 $this->mLoadedItems
= true;
1567 if ( is_array( $data ) ) {
1568 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1569 if ( !count( $data['user_groups'] ) ) {
1570 $this->mGroupMemberships
= [];
1572 $firstGroup = reset( $data['user_groups'] );
1573 if ( is_array( $firstGroup ) ||
is_object( $firstGroup ) ) {
1574 $this->mGroupMemberships
= [];
1575 foreach ( $data['user_groups'] as $row ) {
1576 $ugm = UserGroupMembership
::newFromRow( (object)$row );
1577 $this->mGroupMemberships
[$ugm->getGroup()] = $ugm;
1582 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1583 $this->loadOptions( $data['user_properties'] );
1589 * Load the data for this user object from another user object.
1593 protected function loadFromUserObject( $user ) {
1595 foreach ( self
::$mCacheVars as $var ) {
1596 $this->$var = $user->$var;
1601 * Load the groups from the database if they aren't already loaded.
1603 private function loadGroups() {
1604 if ( is_null( $this->mGroupMemberships
) ) {
1605 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
1606 ?
wfGetDB( DB_MASTER
)
1607 : wfGetDB( DB_REPLICA
);
1608 $this->mGroupMemberships
= UserGroupMembership
::getMembershipsForUser(
1614 * Add the user to the group if he/she meets given criteria.
1616 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1617 * possible to remove manually via Special:UserRights. In such case it
1618 * will not be re-added automatically. The user will also not lose the
1619 * group if they no longer meet the criteria.
1621 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1623 * @return array Array of groups the user has been promoted to.
1625 * @see $wgAutopromoteOnce
1627 public function addAutopromoteOnceGroups( $event ) {
1628 global $wgAutopromoteOnceLogInRC;
1630 if ( wfReadOnly() ||
!$this->getId() ) {
1634 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1635 if ( !count( $toPromote ) ) {
1639 if ( !$this->checkAndSetTouched() ) {
1640 return []; // raced out (bug T48834)
1643 $oldGroups = $this->getGroups(); // previous groups
1644 $oldUGMs = $this->getGroupMemberships();
1645 foreach ( $toPromote as $group ) {
1646 $this->addGroup( $group );
1648 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1649 $newUGMs = $this->getGroupMemberships();
1651 // update groups in external authentication database
1652 Hooks
::run( 'UserGroupsChanged', [ $this, $toPromote, [], false, false, $oldUGMs, $newUGMs ] );
1653 AuthManager
::callLegacyAuthPlugin( 'updateExternalDBGroups', [ $this, $toPromote ] );
1655 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1656 $logEntry->setPerformer( $this );
1657 $logEntry->setTarget( $this->getUserPage() );
1658 $logEntry->setParameters( [
1659 '4::oldgroups' => $oldGroups,
1660 '5::newgroups' => $newGroups,
1662 $logid = $logEntry->insert();
1663 if ( $wgAutopromoteOnceLogInRC ) {
1664 $logEntry->publish( $logid );
1671 * Builds update conditions. Additional conditions may be added to $conditions to
1672 * protected against race conditions using a compare-and-set (CAS) mechanism
1673 * based on comparing $this->mTouched with the user_touched field.
1675 * @param Database $db
1676 * @param array $conditions WHERE conditions for use with Database::update
1677 * @return array WHERE conditions for use with Database::update
1679 protected function makeUpdateConditions( Database
$db, array $conditions ) {
1680 if ( $this->mTouched
) {
1681 // CAS check: only update if the row wasn't changed sicne it was loaded.
1682 $conditions['user_touched'] = $db->timestamp( $this->mTouched
);
1689 * Bump user_touched if it didn't change since this object was loaded
1691 * On success, the mTouched field is updated.
1692 * The user serialization cache is always cleared.
1694 * @return bool Whether user_touched was actually updated
1697 protected function checkAndSetTouched() {
1700 if ( !$this->mId
) {
1701 return false; // anon
1704 // Get a new user_touched that is higher than the old one
1705 $newTouched = $this->newTouchedTimestamp();
1707 $dbw = wfGetDB( DB_MASTER
);
1708 $dbw->update( 'user',
1709 [ 'user_touched' => $dbw->timestamp( $newTouched ) ],
1710 $this->makeUpdateConditions( $dbw, [
1711 'user_id' => $this->mId
,
1715 $success = ( $dbw->affectedRows() > 0 );
1718 $this->mTouched
= $newTouched;
1719 $this->clearSharedCache();
1721 // Clears on failure too since that is desired if the cache is stale
1722 $this->clearSharedCache( 'refresh' );
1729 * Clear various cached data stored in this object. The cache of the user table
1730 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1732 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1733 * given source. May be "name", "id", "actor", "defaults", "session", or false for no reload.
1735 public function clearInstanceCache( $reloadFrom = false ) {
1736 $this->mNewtalk
= -1;
1737 $this->mDatePreference
= null;
1738 $this->mBlockedby
= -1; # Unset
1739 $this->mHash
= false;
1740 $this->mRights
= null;
1741 $this->mEffectiveGroups
= null;
1742 $this->mImplicitGroups
= null;
1743 $this->mGroupMemberships
= null;
1744 $this->mOptions
= null;
1745 $this->mOptionsLoaded
= false;
1746 $this->mEditCount
= null;
1748 if ( $reloadFrom ) {
1749 $this->mLoadedItems
= [];
1750 $this->mFrom
= $reloadFrom;
1755 * Combine the language default options with any site-specific options
1756 * and add the default language variants.
1758 * @return array Array of String options
1760 public static function getDefaultOptions() {
1761 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1763 static $defOpt = null;
1764 static $defOptLang = null;
1766 if ( $defOpt !== null && $defOptLang === $wgContLang->getCode() ) {
1767 // $wgContLang does not change (and should not change) mid-request,
1768 // but the unit tests change it anyway, and expect this method to
1769 // return values relevant to the current $wgContLang.
1773 $defOpt = $wgDefaultUserOptions;
1774 // Default language setting
1775 $defOptLang = $wgContLang->getCode();
1776 $defOpt['language'] = $defOptLang;
1777 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1778 $defOpt[$langCode == $wgContLang->getCode() ?
'variant' : "variant-$langCode"] = $langCode;
1781 // NOTE: don't use SearchEngineConfig::getSearchableNamespaces here,
1782 // since extensions may change the set of searchable namespaces depending
1783 // on user groups/permissions.
1784 foreach ( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
1785 $defOpt['searchNs' . $nsnum] = (bool)$val;
1787 $defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1789 Hooks
::run( 'UserGetDefaultOptions', [ &$defOpt ] );
1795 * Get a given default option value.
1797 * @param string $opt Name of option to retrieve
1798 * @return string Default option value
1800 public static function getDefaultOption( $opt ) {
1801 $defOpts = self
::getDefaultOptions();
1802 if ( isset( $defOpts[$opt] ) ) {
1803 return $defOpts[$opt];
1810 * Get blocking information
1811 * @param bool $bFromSlave Whether to check the replica DB first.
1812 * To improve performance, non-critical checks are done against replica DBs.
1813 * Check when actually saving should be done against master.
1815 private function getBlockedStatus( $bFromSlave = true ) {
1816 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff, $wgSoftBlockRanges;
1818 if ( -1 != $this->mBlockedby
) {
1822 wfDebug( __METHOD__
. ": checking...\n" );
1824 // Initialize data...
1825 // Otherwise something ends up stomping on $this->mBlockedby when
1826 // things get lazy-loaded later, causing false positive block hits
1827 // due to -1 !== 0. Probably session-related... Nothing should be
1828 // overwriting mBlockedby, surely?
1831 # We only need to worry about passing the IP address to the Block generator if the
1832 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1833 # know which IP address they're actually coming from
1835 if ( !$this->isAllowed( 'ipblock-exempt' ) ) {
1836 // $wgUser->getName() only works after the end of Setup.php. Until
1837 // then, assume it's a logged-out user.
1838 $globalUserName = $wgUser->isSafeToLoad()
1839 ?
$wgUser->getName()
1840 : IP
::sanitizeIP( $wgUser->getRequest()->getIP() );
1841 if ( $this->getName() === $globalUserName ) {
1842 $ip = $this->getRequest()->getIP();
1847 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1850 if ( !$block instanceof Block
) {
1851 $block = $this->getBlockFromCookieValue( $this->getRequest()->getCookie( 'BlockID' ) );
1855 if ( !$block instanceof Block
&& $ip !== null && !in_array( $ip, $wgProxyWhitelist ) ) {
1857 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1858 $block = new Block( [
1859 'byText' => wfMessage( 'proxyblocker' )->text(),
1860 'reason' => wfMessage( 'proxyblockreason' )->plain(),
1862 'systemBlock' => 'proxy',
1864 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1865 $block = new Block( [
1866 'byText' => wfMessage( 'sorbs' )->text(),
1867 'reason' => wfMessage( 'sorbsreason' )->plain(),
1869 'systemBlock' => 'dnsbl',
1874 // (T25343) Apply IP blocks to the contents of XFF headers, if enabled
1875 if ( !$block instanceof Block
1876 && $wgApplyIpBlocksToXff
1878 && !in_array( $ip, $wgProxyWhitelist )
1880 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1881 $xff = array_map( 'trim', explode( ',', $xff ) );
1882 $xff = array_diff( $xff, [ $ip ] );
1883 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1884 $block = Block
::chooseBlock( $xffblocks, $xff );
1885 if ( $block instanceof Block
) {
1886 # Mangle the reason to alert the user that the block
1887 # originated from matching the X-Forwarded-For header.
1888 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->plain();
1892 if ( !$block instanceof Block
1895 && IP
::isInRanges( $ip, $wgSoftBlockRanges )
1897 $block = new Block( [
1899 'byText' => 'MediaWiki default',
1900 'reason' => wfMessage( 'softblockrangesreason', $ip )->plain(),
1902 'systemBlock' => 'wgSoftBlockRanges',
1906 if ( $block instanceof Block
) {
1907 wfDebug( __METHOD__
. ": Found block.\n" );
1908 $this->mBlock
= $block;
1909 $this->mBlockedby
= $block->getByName();
1910 $this->mBlockreason
= $block->mReason
;
1911 $this->mHideName
= $block->mHideName
;
1912 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1914 $this->mBlock
= null;
1915 $this->mBlockedby
= '';
1916 $this->mBlockreason
= '';
1917 $this->mHideName
= 0;
1918 $this->mAllowUsertalk
= false;
1921 // Avoid PHP 7.1 warning of passing $this by reference
1924 Hooks
::run( 'GetBlockedStatus', [ &$user ] );
1928 * Try to load a Block from an ID given in a cookie value.
1929 * @param string|null $blockCookieVal The cookie value to check.
1930 * @return Block|bool The Block object, or false if none could be loaded.
1932 protected function getBlockFromCookieValue( $blockCookieVal ) {
1933 // Make sure there's something to check. The cookie value must start with a number.
1934 if ( strlen( $blockCookieVal ) < 1 ||
!is_numeric( substr( $blockCookieVal, 0, 1 ) ) ) {
1937 // Load the Block from the ID in the cookie.
1938 $blockCookieId = Block
::getIdFromCookieValue( $blockCookieVal );
1939 if ( $blockCookieId !== null ) {
1940 // An ID was found in the cookie.
1941 $tmpBlock = Block
::newFromID( $blockCookieId );
1942 if ( $tmpBlock instanceof Block
) {
1943 $config = RequestContext
::getMain()->getConfig();
1945 switch ( $tmpBlock->getType() ) {
1946 case Block
::TYPE_USER
:
1947 $blockIsValid = !$tmpBlock->isExpired() && $tmpBlock->isAutoblocking();
1948 $useBlockCookie = ( $config->get( 'CookieSetOnAutoblock' ) === true );
1950 case Block
::TYPE_IP
:
1951 case Block
::TYPE_RANGE
:
1952 // If block is type IP or IP range, load only if user is not logged in (T152462)
1953 $blockIsValid = !$tmpBlock->isExpired() && !$this->isLoggedIn();
1954 $useBlockCookie = ( $config->get( 'CookieSetOnIpBlock' ) === true );
1957 $blockIsValid = false;
1958 $useBlockCookie = false;
1961 if ( $blockIsValid && $useBlockCookie ) {
1965 // If the block is not valid, remove the cookie.
1966 Block
::clearCookie( $this->getRequest()->response() );
1969 // If the block doesn't exist, remove the cookie.
1970 Block
::clearCookie( $this->getRequest()->response() );
1977 * Whether the given IP is in a DNS blacklist.
1979 * @param string $ip IP to check
1980 * @param bool $checkWhitelist Whether to check the whitelist first
1981 * @return bool True if blacklisted.
1983 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1984 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1986 if ( !$wgEnableDnsBlacklist ) {
1990 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1994 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1998 * Whether the given IP is in a given DNS blacklist.
2000 * @param string $ip IP to check
2001 * @param string|array $bases Array of Strings: URL of the DNS blacklist
2002 * @return bool True if blacklisted.
2004 public function inDnsBlacklist( $ip, $bases ) {
2006 // @todo FIXME: IPv6 ??? (https://bugs.php.net/bug.php?id=33170)
2007 if ( IP
::isIPv4( $ip ) ) {
2008 // Reverse IP, T23255
2009 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
2011 foreach ( (array)$bases as $base ) {
2013 // If we have an access key, use that too (ProjectHoneypot, etc.)
2015 if ( is_array( $base ) ) {
2016 if ( count( $base ) >= 2 ) {
2017 // Access key is 1, base URL is 0
2018 $host = "{$base[1]}.$ipReversed.{$base[0]}";
2020 $host = "$ipReversed.{$base[0]}";
2022 $basename = $base[0];
2024 $host = "$ipReversed.$base";
2028 $ipList = gethostbynamel( $host );
2031 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
2035 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
2044 * Check if an IP address is in the local proxy list
2050 public static function isLocallyBlockedProxy( $ip ) {
2051 global $wgProxyList;
2053 if ( !$wgProxyList ) {
2057 if ( !is_array( $wgProxyList ) ) {
2058 // Load values from the specified file
2059 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
2062 $resultProxyList = [];
2063 $deprecatedIPEntries = [];
2065 // backward compatibility: move all ip addresses in keys to values
2066 foreach ( $wgProxyList as $key => $value ) {
2067 $keyIsIP = IP
::isIPAddress( $key );
2068 $valueIsIP = IP
::isIPAddress( $value );
2069 if ( $keyIsIP && !$valueIsIP ) {
2070 $deprecatedIPEntries[] = $key;
2071 $resultProxyList[] = $key;
2072 } elseif ( $keyIsIP && $valueIsIP ) {
2073 $deprecatedIPEntries[] = $key;
2074 $resultProxyList[] = $key;
2075 $resultProxyList[] = $value;
2077 $resultProxyList[] = $value;
2081 if ( $deprecatedIPEntries ) {
2083 'IP addresses in the keys of $wgProxyList (found the following IP addresses in keys: ' .
2084 implode( ', ', $deprecatedIPEntries ) . ', please move them to values)', '1.30' );
2087 $proxyListIPSet = new IPSet( $resultProxyList );
2088 return $proxyListIPSet->match( $ip );
2092 * Is this user subject to rate limiting?
2094 * @return bool True if rate limited
2096 public function isPingLimitable() {
2097 global $wgRateLimitsExcludedIPs;
2098 if ( IP
::isInRanges( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
2099 // No other good way currently to disable rate limits
2100 // for specific IPs. :P
2101 // But this is a crappy hack and should die.
2104 return !$this->isAllowed( 'noratelimit' );
2108 * Primitive rate limits: enforce maximum actions per time period
2109 * to put a brake on flooding.
2111 * The method generates both a generic profiling point and a per action one
2112 * (suffix being "-$action".
2114 * @note When using a shared cache like memcached, IP-address
2115 * last-hit counters will be shared across wikis.
2117 * @param string $action Action to enforce; 'edit' if unspecified
2118 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
2119 * @return bool True if a rate limiter was tripped
2121 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
2122 // Avoid PHP 7.1 warning of passing $this by reference
2124 // Call the 'PingLimiter' hook
2126 if ( !Hooks
::run( 'PingLimiter', [ &$user, $action, &$result, $incrBy ] ) ) {
2130 global $wgRateLimits;
2131 if ( !isset( $wgRateLimits[$action] ) ) {
2135 $limits = array_merge(
2136 [ '&can-bypass' => true ],
2137 $wgRateLimits[$action]
2140 // Some groups shouldn't trigger the ping limiter, ever
2141 if ( $limits['&can-bypass'] && !$this->isPingLimitable() ) {
2146 $id = $this->getId();
2148 $isNewbie = $this->isNewbie();
2149 $cache = ObjectCache
::getLocalClusterInstance();
2153 if ( isset( $limits['anon'] ) ) {
2154 $keys[$cache->makeKey( 'limiter', $action, 'anon' )] = $limits['anon'];
2157 // limits for logged-in users
2158 if ( isset( $limits['user'] ) ) {
2159 $userLimit = $limits['user'];
2161 // limits for newbie logged-in users
2162 if ( $isNewbie && isset( $limits['newbie'] ) ) {
2163 $keys[$cache->makeKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
2167 // limits for anons and for newbie logged-in users
2170 if ( isset( $limits['ip'] ) ) {
2171 $ip = $this->getRequest()->getIP();
2172 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
2174 // subnet-based limits
2175 if ( isset( $limits['subnet'] ) ) {
2176 $ip = $this->getRequest()->getIP();
2177 $subnet = IP
::getSubnet( $ip );
2178 if ( $subnet !== false ) {
2179 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
2184 // Check for group-specific permissions
2185 // If more than one group applies, use the group with the highest limit ratio (max/period)
2186 foreach ( $this->getGroups() as $group ) {
2187 if ( isset( $limits[$group] ) ) {
2188 if ( $userLimit === false
2189 ||
$limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
2191 $userLimit = $limits[$group];
2196 // Set the user limit key
2197 if ( $userLimit !== false ) {
2198 list( $max, $period ) = $userLimit;
2199 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
2200 $keys[$cache->makeKey( 'limiter', $action, 'user', $id )] = $userLimit;
2203 // ip-based limits for all ping-limitable users
2204 if ( isset( $limits['ip-all'] ) ) {
2205 $ip = $this->getRequest()->getIP();
2206 // ignore if user limit is more permissive
2207 if ( $isNewbie ||
$userLimit === false
2208 ||
$limits['ip-all'][0] / $limits['ip-all'][1] > $userLimit[0] / $userLimit[1] ) {
2209 $keys["mediawiki:limiter:$action:ip-all:$ip"] = $limits['ip-all'];
2213 // subnet-based limits for all ping-limitable users
2214 if ( isset( $limits['subnet-all'] ) ) {
2215 $ip = $this->getRequest()->getIP();
2216 $subnet = IP
::getSubnet( $ip );
2217 if ( $subnet !== false ) {
2218 // ignore if user limit is more permissive
2219 if ( $isNewbie ||
$userLimit === false
2220 ||
$limits['ip-all'][0] / $limits['ip-all'][1]
2221 > $userLimit[0] / $userLimit[1] ) {
2222 $keys["mediawiki:limiter:$action:subnet-all:$subnet"] = $limits['subnet-all'];
2228 foreach ( $keys as $key => $limit ) {
2229 list( $max, $period ) = $limit;
2230 $summary = "(limit $max in {$period}s)";
2231 $count = $cache->get( $key );
2234 if ( $count >= $max ) {
2235 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
2236 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
2239 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
2242 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
2243 if ( $incrBy > 0 ) {
2244 $cache->add( $key, 0, intval( $period ) ); // first ping
2247 if ( $incrBy > 0 ) {
2248 $cache->incr( $key, $incrBy );
2256 * Check if user is blocked
2258 * @param bool $bFromSlave Whether to check the replica DB instead of
2259 * the master. Hacked from false due to horrible probs on site.
2260 * @return bool True if blocked, false otherwise
2262 public function isBlocked( $bFromSlave = true ) {
2263 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
2267 * Get the block affecting the user, or null if the user is not blocked
2269 * @param bool $bFromSlave Whether to check the replica DB instead of the master
2270 * @return Block|null
2272 public function getBlock( $bFromSlave = true ) {
2273 $this->getBlockedStatus( $bFromSlave );
2274 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
2278 * Check if user is blocked from editing a particular article
2280 * @param Title $title Title to check
2281 * @param bool $bFromSlave Whether to check the replica DB instead of the master
2284 public function isBlockedFrom( $title, $bFromSlave = false ) {
2285 global $wgBlockAllowsUTEdit;
2287 $blocked = $this->isBlocked( $bFromSlave );
2288 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
2289 // If a user's name is suppressed, they cannot make edits anywhere
2290 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName()
2291 && $title->getNamespace() == NS_USER_TALK
) {
2293 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
2296 Hooks
::run( 'UserIsBlockedFrom', [ $this, $title, &$blocked, &$allowUsertalk ] );
2302 * If user is blocked, return the name of the user who placed the block
2303 * @return string Name of blocker
2305 public function blockedBy() {
2306 $this->getBlockedStatus();
2307 return $this->mBlockedby
;
2311 * If user is blocked, return the specified reason for the block
2312 * @return string Blocking reason
2314 public function blockedFor() {
2315 $this->getBlockedStatus();
2316 return $this->mBlockreason
;
2320 * If user is blocked, return the ID for the block
2321 * @return int Block ID
2323 public function getBlockId() {
2324 $this->getBlockedStatus();
2325 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
2329 * Check if user is blocked on all wikis.
2330 * Do not use for actual edit permission checks!
2331 * This is intended for quick UI checks.
2333 * @param string $ip IP address, uses current client if none given
2334 * @return bool True if blocked, false otherwise
2336 public function isBlockedGlobally( $ip = '' ) {
2337 return $this->getGlobalBlock( $ip ) instanceof Block
;
2341 * Check if user is blocked on all wikis.
2342 * Do not use for actual edit permission checks!
2343 * This is intended for quick UI checks.
2345 * @param string $ip IP address, uses current client if none given
2346 * @return Block|null Block object if blocked, null otherwise
2347 * @throws FatalError
2348 * @throws MWException
2350 public function getGlobalBlock( $ip = '' ) {
2351 if ( $this->mGlobalBlock
!== null ) {
2352 return $this->mGlobalBlock ?
: null;
2354 // User is already an IP?
2355 if ( IP
::isIPAddress( $this->getName() ) ) {
2356 $ip = $this->getName();
2358 $ip = $this->getRequest()->getIP();
2360 // Avoid PHP 7.1 warning of passing $this by reference
2364 Hooks
::run( 'UserIsBlockedGlobally', [ &$user, $ip, &$blocked, &$block ] );
2366 if ( $blocked && $block === null ) {
2367 // back-compat: UserIsBlockedGlobally didn't have $block param first
2368 $block = new Block( [
2370 'systemBlock' => 'global-block'
2374 $this->mGlobalBlock
= $blocked ?
$block : false;
2375 return $this->mGlobalBlock ?
: null;
2379 * Check if user account is locked
2381 * @return bool True if locked, false otherwise
2383 public function isLocked() {
2384 if ( $this->mLocked
!== null ) {
2385 return $this->mLocked
;
2387 // Avoid PHP 7.1 warning of passing $this by reference
2389 $authUser = AuthManager
::callLegacyAuthPlugin( 'getUserInstance', [ &$user ], null );
2390 $this->mLocked
= $authUser && $authUser->isLocked();
2391 Hooks
::run( 'UserIsLocked', [ $this, &$this->mLocked
] );
2392 return $this->mLocked
;
2396 * Check if user account is hidden
2398 * @return bool True if hidden, false otherwise
2400 public function isHidden() {
2401 if ( $this->mHideName
!== null ) {
2402 return $this->mHideName
;
2404 $this->getBlockedStatus();
2405 if ( !$this->mHideName
) {
2406 // Avoid PHP 7.1 warning of passing $this by reference
2408 $authUser = AuthManager
::callLegacyAuthPlugin( 'getUserInstance', [ &$user ], null );
2409 $this->mHideName
= $authUser && $authUser->isHidden();
2410 Hooks
::run( 'UserIsHidden', [ $this, &$this->mHideName
] );
2412 return $this->mHideName
;
2416 * Get the user's ID.
2417 * @return int The user's ID; 0 if the user is anonymous or nonexistent
2419 public function getId() {
2420 if ( $this->mId
=== null && $this->mName
!== null && self
::isIP( $this->mName
) ) {
2421 // Special case, we know the user is anonymous
2423 } elseif ( !$this->isItemLoaded( 'id' ) ) {
2424 // Don't load if this was initialized from an ID
2428 return (int)$this->mId
;
2432 * Set the user and reload all fields according to a given ID
2433 * @param int $v User ID to reload
2435 public function setId( $v ) {
2437 $this->clearInstanceCache( 'id' );
2441 * Get the user name, or the IP of an anonymous user
2442 * @return string User's name or IP address
2444 public function getName() {
2445 if ( $this->isItemLoaded( 'name', 'only' ) ) {
2446 // Special case optimisation
2447 return $this->mName
;
2450 if ( $this->mName
=== false ) {
2452 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
2454 return $this->mName
;
2459 * Set the user name.
2461 * This does not reload fields from the database according to the given
2462 * name. Rather, it is used to create a temporary "nonexistent user" for
2463 * later addition to the database. It can also be used to set the IP
2464 * address for an anonymous user to something other than the current
2467 * @note User::newFromName() has roughly the same function, when the named user
2469 * @param string $str New user name to set
2471 public function setName( $str ) {
2473 $this->mName
= $str;
2477 * Get the user's actor ID.
2479 * @param IDatabase|null $dbw Assign a new actor ID, using this DB handle, if none exists
2480 * @return int The actor's ID, or 0 if no actor ID exists and $dbw was null
2482 public function getActorId( IDatabase
$dbw = null ) {
2483 global $wgActorTableSchemaMigrationStage;
2485 if ( $wgActorTableSchemaMigrationStage <= MIGRATION_OLD
) {
2489 if ( !$this->isItemLoaded( 'actor' ) ) {
2493 // Currently $this->mActorId might be null if $this was loaded from a
2494 // cache entry that was written when $wgActorTableSchemaMigrationStage
2495 // was MIGRATION_OLD. Once that is no longer a possibility (i.e. when
2496 // User::VERSION is incremented after $wgActorTableSchemaMigrationStage
2497 // has been removed), that condition may be removed.
2498 if ( $this->mActorId
=== null ||
!$this->mActorId
&& $dbw ) {
2500 'actor_user' => $this->getId() ?
: null,
2501 'actor_name' => (string)$this->getName(),
2504 if ( $q['actor_user'] === null && self
::isUsableName( $q['actor_name'] ) ) {
2505 throw new CannotCreateActorException(
2506 'Cannot create an actor for a usable name that is not an existing user'
2509 if ( $q['actor_name'] === '' ) {
2510 throw new CannotCreateActorException( 'Cannot create an actor for a user with no name' );
2512 $dbw->insert( 'actor', $q, __METHOD__
, [ 'IGNORE' ] );
2513 if ( $dbw->affectedRows() ) {
2514 $this->mActorId
= (int)$dbw->insertId();
2517 list( , $options ) = DBAccessObjectUtils
::getDBOptions( $this->queryFlagsUsed
);
2518 $this->mActorId
= (int)$dbw->selectField( 'actor', 'actor_id', $q, __METHOD__
, $options );
2519 if ( !$this->mActorId
) {
2520 throw new CannotCreateActorException(
2521 "Cannot create actor ID for user_id={$this->getId()} user_name={$this->getName()}"
2525 $this->invalidateCache();
2527 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $this->queryFlagsUsed
);
2528 $db = wfGetDB( $index );
2529 $this->mActorId
= (int)$db->selectField( 'actor', 'actor_id', $q, __METHOD__
, $options );
2531 $this->setItemLoaded( 'actor' );
2534 return (int)$this->mActorId
;
2538 * Get the user's name escaped by underscores.
2539 * @return string Username escaped by underscores.
2541 public function getTitleKey() {
2542 return str_replace( ' ', '_', $this->getName() );
2546 * Check if the user has new messages.
2547 * @return bool True if the user has new messages
2549 public function getNewtalk() {
2552 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2553 if ( $this->mNewtalk
=== -1 ) {
2554 $this->mNewtalk
= false; # reset talk page status
2556 // Check memcached separately for anons, who have no
2557 // entire User object stored in there.
2558 if ( !$this->mId
) {
2559 global $wgDisableAnonTalk;
2560 if ( $wgDisableAnonTalk ) {
2561 // Anon newtalk disabled by configuration.
2562 $this->mNewtalk
= false;
2564 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
2567 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2571 return (bool)$this->mNewtalk
;
2575 * Return the data needed to construct links for new talk page message
2576 * alerts. If there are new messages, this will return an associative array
2577 * with the following data:
2578 * wiki: The database name of the wiki
2579 * link: Root-relative link to the user's talk page
2580 * rev: The last talk page revision that the user has seen or null. This
2581 * is useful for building diff links.
2582 * If there are no new messages, it returns an empty array.
2583 * @note This function was designed to accomodate multiple talk pages, but
2584 * currently only returns a single link and revision.
2587 public function getNewMessageLinks() {
2588 // Avoid PHP 7.1 warning of passing $this by reference
2591 if ( !Hooks
::run( 'UserRetrieveNewTalks', [ &$user, &$talks ] ) ) {
2593 } elseif ( !$this->getNewtalk() ) {
2596 $utp = $this->getTalkPage();
2597 $dbr = wfGetDB( DB_REPLICA
);
2598 // Get the "last viewed rev" timestamp from the oldest message notification
2599 $timestamp = $dbr->selectField( 'user_newtalk',
2600 'MIN(user_last_timestamp)',
2601 $this->isAnon() ?
[ 'user_ip' => $this->getName() ] : [ 'user_id' => $this->getId() ],
2603 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2604 return [ [ 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ] ];
2608 * Get the revision ID for the last talk page revision viewed by the talk
2610 * @return int|null Revision ID or null
2612 public function getNewMessageRevisionId() {
2613 $newMessageRevisionId = null;
2614 $newMessageLinks = $this->getNewMessageLinks();
2615 if ( $newMessageLinks ) {
2616 // Note: getNewMessageLinks() never returns more than a single link
2617 // and it is always for the same wiki, but we double-check here in
2618 // case that changes some time in the future.
2619 if ( count( $newMessageLinks ) === 1
2620 && $newMessageLinks[0]['wiki'] === wfWikiID()
2621 && $newMessageLinks[0]['rev']
2623 /** @var Revision $newMessageRevision */
2624 $newMessageRevision = $newMessageLinks[0]['rev'];
2625 $newMessageRevisionId = $newMessageRevision->getId();
2628 return $newMessageRevisionId;
2632 * Internal uncached check for new messages
2635 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2636 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2637 * @return bool True if the user has new messages
2639 protected function checkNewtalk( $field, $id ) {
2640 $dbr = wfGetDB( DB_REPLICA
);
2642 $ok = $dbr->selectField( 'user_newtalk', $field, [ $field => $id ], __METHOD__
);
2644 return $ok !== false;
2648 * Add or update the new messages flag
2649 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2650 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2651 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2652 * @return bool True if successful, false otherwise
2654 protected function updateNewtalk( $field, $id, $curRev = null ) {
2655 // Get timestamp of the talk page revision prior to the current one
2656 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2657 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2658 // Mark the user as having new messages since this revision
2659 $dbw = wfGetDB( DB_MASTER
);
2660 $dbw->insert( 'user_newtalk',
2661 [ $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ],
2664 if ( $dbw->affectedRows() ) {
2665 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2668 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2674 * Clear the new messages flag for the given user
2675 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2676 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2677 * @return bool True if successful, false otherwise
2679 protected function deleteNewtalk( $field, $id ) {
2680 $dbw = wfGetDB( DB_MASTER
);
2681 $dbw->delete( 'user_newtalk',
2684 if ( $dbw->affectedRows() ) {
2685 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2688 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2694 * Update the 'You have new messages!' status.
2695 * @param bool $val Whether the user has new messages
2696 * @param Revision|null $curRev New, as yet unseen revision of the user talk
2697 * page. Ignored if null or !$val.
2699 public function setNewtalk( $val, $curRev = null ) {
2700 if ( wfReadOnly() ) {
2705 $this->mNewtalk
= $val;
2707 if ( $this->isAnon() ) {
2709 $id = $this->getName();
2712 $id = $this->getId();
2716 $changed = $this->updateNewtalk( $field, $id, $curRev );
2718 $changed = $this->deleteNewtalk( $field, $id );
2722 $this->invalidateCache();
2727 * Generate a current or new-future timestamp to be stored in the
2728 * user_touched field when we update things.
2729 * @return string Timestamp in TS_MW format
2731 private function newTouchedTimestamp() {
2732 global $wgClockSkewFudge;
2734 $time = wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2735 if ( $this->mTouched
&& $time <= $this->mTouched
) {
2736 $time = wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $this->mTouched
) +
1 );
2743 * Clear user data from memcached
2745 * Use after applying updates to the database; caller's
2746 * responsibility to update user_touched if appropriate.
2748 * Called implicitly from invalidateCache() and saveSettings().
2750 * @param string $mode Use 'refresh' to clear now; otherwise before DB commit
2752 public function clearSharedCache( $mode = 'changed' ) {
2753 if ( !$this->getId() ) {
2757 $cache = ObjectCache
::getMainWANInstance();
2758 $key = $this->getCacheKey( $cache );
2759 if ( $mode === 'refresh' ) {
2760 $cache->delete( $key, 1 );
2762 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
2763 if ( $lb->hasOrMadeRecentMasterChanges() ) {
2764 $lb->getConnection( DB_MASTER
)->onTransactionPreCommitOrIdle(
2765 function () use ( $cache, $key ) {
2766 $cache->delete( $key );
2771 $cache->delete( $key );
2777 * Immediately touch the user data cache for this account
2779 * Calls touch() and removes account data from memcached
2781 public function invalidateCache() {
2783 $this->clearSharedCache();
2787 * Update the "touched" timestamp for the user
2789 * This is useful on various login/logout events when making sure that
2790 * a browser or proxy that has multiple tenants does not suffer cache
2791 * pollution where the new user sees the old users content. The value
2792 * of getTouched() is checked when determining 304 vs 200 responses.
2793 * Unlike invalidateCache(), this preserves the User object cache and
2794 * avoids database writes.
2798 public function touch() {
2799 $id = $this->getId();
2801 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
2802 $key = $cache->makeKey( 'user-quicktouched', 'id', $id );
2803 $cache->touchCheckKey( $key );
2804 $this->mQuickTouched
= null;
2809 * Validate the cache for this account.
2810 * @param string $timestamp A timestamp in TS_MW format
2813 public function validateCache( $timestamp ) {
2814 return ( $timestamp >= $this->getTouched() );
2818 * Get the user touched timestamp
2820 * Use this value only to validate caches via inequalities
2821 * such as in the case of HTTP If-Modified-Since response logic
2823 * @return string TS_MW Timestamp
2825 public function getTouched() {
2829 if ( $this->mQuickTouched
=== null ) {
2830 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
2831 $key = $cache->makeKey( 'user-quicktouched', 'id', $this->mId
);
2833 $this->mQuickTouched
= wfTimestamp( TS_MW
, $cache->getCheckKeyTime( $key ) );
2836 return max( $this->mTouched
, $this->mQuickTouched
);
2839 return $this->mTouched
;
2843 * Get the user_touched timestamp field (time of last DB updates)
2844 * @return string TS_MW Timestamp
2847 public function getDBTouched() {
2850 return $this->mTouched
;
2854 * Set the password and reset the random token.
2855 * Calls through to authentication plugin if necessary;
2856 * will have no effect if the auth plugin refuses to
2857 * pass the change through or if the legal password
2860 * As a special case, setting the password to null
2861 * wipes it, so the account cannot be logged in until
2862 * a new password is set, for instance via e-mail.
2864 * @deprecated since 1.27, use AuthManager instead
2865 * @param string $str New password to set
2866 * @throws PasswordError On failure
2869 public function setPassword( $str ) {
2870 return $this->setPasswordInternal( $str );
2874 * Set the password and reset the random token unconditionally.
2876 * @deprecated since 1.27, use AuthManager instead
2877 * @param string|null $str New password to set or null to set an invalid
2878 * password hash meaning that the user will not be able to log in
2879 * through the web interface.
2881 public function setInternalPassword( $str ) {
2882 $this->setPasswordInternal( $str );
2886 * Actually set the password and such
2887 * @since 1.27 cannot set a password for a user not in the database
2888 * @param string|null $str New password to set or null to set an invalid
2889 * password hash meaning that the user will not be able to log in
2890 * through the web interface.
2891 * @return bool Success
2893 private function setPasswordInternal( $str ) {
2894 $manager = AuthManager
::singleton();
2896 // If the user doesn't exist yet, fail
2897 if ( !$manager->userExists( $this->getName() ) ) {
2898 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2901 $status = $this->changeAuthenticationData( [
2902 'username' => $this->getName(),
2906 if ( !$status->isGood() ) {
2907 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
2908 ->info( __METHOD__
. ': Password change rejected: '
2909 . $status->getWikiText( null, null, 'en' ) );
2913 $this->setOption( 'watchlisttoken', false );
2914 SessionManager
::singleton()->invalidateSessionsForUser( $this );
2920 * Changes credentials of the user.
2922 * This is a convenience wrapper around AuthManager::changeAuthenticationData.
2923 * Note that this can return a status that isOK() but not isGood() on certain types of failures,
2924 * e.g. when no provider handled the change.
2926 * @param array $data A set of authentication data in fieldname => value format. This is the
2927 * same data you would pass the changeauthenticationdata API - 'username', 'password' etc.
2931 public function changeAuthenticationData( array $data ) {
2932 $manager = AuthManager
::singleton();
2933 $reqs = $manager->getAuthenticationRequests( AuthManager
::ACTION_CHANGE
, $this );
2934 $reqs = AuthenticationRequest
::loadRequestsFromSubmission( $reqs, $data );
2936 $status = Status
::newGood( 'ignored' );
2937 foreach ( $reqs as $req ) {
2938 $status->merge( $manager->allowsAuthenticationDataChange( $req ), true );
2940 if ( $status->getValue() === 'ignored' ) {
2941 $status->warning( 'authenticationdatachange-ignored' );
2944 if ( $status->isGood() ) {
2945 foreach ( $reqs as $req ) {
2946 $manager->changeAuthenticationData( $req );
2953 * Get the user's current token.
2954 * @param bool $forceCreation Force the generation of a new token if the
2955 * user doesn't have one (default=true for backwards compatibility).
2956 * @return string|null Token
2958 public function getToken( $forceCreation = true ) {
2959 global $wgAuthenticationTokenVersion;
2962 if ( !$this->mToken
&& $forceCreation ) {
2966 if ( !$this->mToken
) {
2967 // The user doesn't have a token, return null to indicate that.
2969 } elseif ( $this->mToken
=== self
::INVALID_TOKEN
) {
2970 // We return a random value here so existing token checks are very
2972 return MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2973 } elseif ( $wgAuthenticationTokenVersion === null ) {
2974 // $wgAuthenticationTokenVersion not in use, so return the raw secret
2975 return $this->mToken
;
2977 // $wgAuthenticationTokenVersion in use, so hmac it.
2978 $ret = MWCryptHash
::hmac( $wgAuthenticationTokenVersion, $this->mToken
, false );
2980 // The raw hash can be overly long. Shorten it up.
2981 $len = max( 32, self
::TOKEN_LENGTH
);
2982 if ( strlen( $ret ) < $len ) {
2983 // Should never happen, even md5 is 128 bits
2984 throw new \
UnexpectedValueException( 'Hmac returned less than 128 bits' );
2986 return substr( $ret, -$len );
2991 * Set the random token (used for persistent authentication)
2992 * Called from loadDefaults() among other places.
2994 * @param string|bool $token If specified, set the token to this value
2996 public function setToken( $token = false ) {
2998 if ( $this->mToken
=== self
::INVALID_TOKEN
) {
2999 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3000 ->debug( __METHOD__
. ": Ignoring attempt to set token for system user \"$this\"" );
3001 } elseif ( !$token ) {
3002 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
3004 $this->mToken
= $token;
3009 * Set the password for a password reminder or new account email
3011 * @deprecated Removed in 1.27. Use PasswordReset instead.
3012 * @param string $str New password to set or null to set an invalid
3013 * password hash meaning that the user will not be able to use it
3014 * @param bool $throttle If true, reset the throttle timestamp to the present
3016 public function setNewpassword( $str, $throttle = true ) {
3017 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
3021 * Get the user's e-mail address
3022 * @return string User's email address
3024 public function getEmail() {
3026 Hooks
::run( 'UserGetEmail', [ $this, &$this->mEmail
] );
3027 return $this->mEmail
;
3031 * Get the timestamp of the user's e-mail authentication
3032 * @return string TS_MW timestamp
3034 public function getEmailAuthenticationTimestamp() {
3036 Hooks
::run( 'UserGetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
3037 return $this->mEmailAuthenticated
;
3041 * Set the user's e-mail address
3042 * @param string $str New e-mail address
3044 public function setEmail( $str ) {
3046 if ( $str == $this->mEmail
) {
3049 $this->invalidateEmail();
3050 $this->mEmail
= $str;
3051 Hooks
::run( 'UserSetEmail', [ $this, &$this->mEmail
] );
3055 * Set the user's e-mail address and a confirmation mail if needed.
3058 * @param string $str New e-mail address
3061 public function setEmailWithConfirmation( $str ) {
3062 global $wgEnableEmail, $wgEmailAuthentication;
3064 if ( !$wgEnableEmail ) {
3065 return Status
::newFatal( 'emaildisabled' );
3068 $oldaddr = $this->getEmail();
3069 if ( $str === $oldaddr ) {
3070 return Status
::newGood( true );
3073 $type = $oldaddr != '' ?
'changed' : 'set';
3074 $notificationResult = null;
3076 if ( $wgEmailAuthentication ) {
3077 // Send the user an email notifying the user of the change in registered
3078 // email address on their previous email address
3079 if ( $type == 'changed' ) {
3080 $change = $str != '' ?
'changed' : 'removed';
3081 $notificationResult = $this->sendMail(
3082 wfMessage( 'notificationemail_subject_' . $change )->text(),
3083 wfMessage( 'notificationemail_body_' . $change,
3084 $this->getRequest()->getIP(),
3091 $this->setEmail( $str );
3093 if ( $str !== '' && $wgEmailAuthentication ) {
3094 // Send a confirmation request to the new address if needed
3095 $result = $this->sendConfirmationMail( $type );
3097 if ( $notificationResult !== null ) {
3098 $result->merge( $notificationResult );
3101 if ( $result->isGood() ) {
3102 // Say to the caller that a confirmation and notification mail has been sent
3103 $result->value
= 'eauth';
3106 $result = Status
::newGood( true );
3113 * Get the user's real name
3114 * @return string User's real name
3116 public function getRealName() {
3117 if ( !$this->isItemLoaded( 'realname' ) ) {
3121 return $this->mRealName
;
3125 * Set the user's real name
3126 * @param string $str New real name
3128 public function setRealName( $str ) {
3130 $this->mRealName
= $str;
3134 * Get the user's current setting for a given option.
3136 * @param string $oname The option to check
3137 * @param string|array|null $defaultOverride A default value returned if the option does not exist
3138 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
3139 * @return string|array|int|null User's current value for the option
3140 * @see getBoolOption()
3141 * @see getIntOption()
3143 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
3144 global $wgHiddenPrefs;
3145 $this->loadOptions();
3147 # We want 'disabled' preferences to always behave as the default value for
3148 # users, even if they have set the option explicitly in their settings (ie they
3149 # set it, and then it was disabled removing their ability to change it). But
3150 # we don't want to erase the preferences in the database in case the preference
3151 # is re-enabled again. So don't touch $mOptions, just override the returned value
3152 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
3153 return self
::getDefaultOption( $oname );
3156 if ( array_key_exists( $oname, $this->mOptions
) ) {
3157 return $this->mOptions
[$oname];
3159 return $defaultOverride;
3164 * Get all user's options
3166 * @param int $flags Bitwise combination of:
3167 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
3168 * to the default value. (Since 1.25)
3171 public function getOptions( $flags = 0 ) {
3172 global $wgHiddenPrefs;
3173 $this->loadOptions();
3174 $options = $this->mOptions
;
3176 # We want 'disabled' preferences to always behave as the default value for
3177 # users, even if they have set the option explicitly in their settings (ie they
3178 # set it, and then it was disabled removing their ability to change it). But
3179 # we don't want to erase the preferences in the database in case the preference
3180 # is re-enabled again. So don't touch $mOptions, just override the returned value
3181 foreach ( $wgHiddenPrefs as $pref ) {
3182 $default = self
::getDefaultOption( $pref );
3183 if ( $default !== null ) {
3184 $options[$pref] = $default;
3188 if ( $flags & self
::GETOPTIONS_EXCLUDE_DEFAULTS
) {
3189 $options = array_diff_assoc( $options, self
::getDefaultOptions() );
3196 * Get the user's current setting for a given option, as a boolean value.
3198 * @param string $oname The option to check
3199 * @return bool User's current value for the option
3202 public function getBoolOption( $oname ) {
3203 return (bool)$this->getOption( $oname );
3207 * Get the user's current setting for a given option, as an integer value.
3209 * @param string $oname The option to check
3210 * @param int $defaultOverride A default value returned if the option does not exist
3211 * @return int User's current value for the option
3214 public function getIntOption( $oname, $defaultOverride = 0 ) {
3215 $val = $this->getOption( $oname );
3217 $val = $defaultOverride;
3219 return intval( $val );
3223 * Set the given option for a user.
3225 * You need to call saveSettings() to actually write to the database.
3227 * @param string $oname The option to set
3228 * @param mixed $val New value to set
3230 public function setOption( $oname, $val ) {
3231 $this->loadOptions();
3233 // Explicitly NULL values should refer to defaults
3234 if ( is_null( $val ) ) {
3235 $val = self
::getDefaultOption( $oname );
3238 $this->mOptions
[$oname] = $val;
3242 * Get a token stored in the preferences (like the watchlist one),
3243 * resetting it if it's empty (and saving changes).
3245 * @param string $oname The option name to retrieve the token from
3246 * @return string|bool User's current value for the option, or false if this option is disabled.
3247 * @see resetTokenFromOption()
3249 * @deprecated since 1.26 Applications should use the OAuth extension
3251 public function getTokenFromOption( $oname ) {
3252 global $wgHiddenPrefs;
3254 $id = $this->getId();
3255 if ( !$id ||
in_array( $oname, $wgHiddenPrefs ) ) {
3259 $token = $this->getOption( $oname );
3261 // Default to a value based on the user token to avoid space
3262 // wasted on storing tokens for all users. When this option
3263 // is set manually by the user, only then is it stored.
3264 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
3271 * Reset a token stored in the preferences (like the watchlist one).
3272 * *Does not* save user's preferences (similarly to setOption()).
3274 * @param string $oname The option name to reset the token in
3275 * @return string|bool New token value, or false if this option is disabled.
3276 * @see getTokenFromOption()
3279 public function resetTokenFromOption( $oname ) {
3280 global $wgHiddenPrefs;
3281 if ( in_array( $oname, $wgHiddenPrefs ) ) {
3285 $token = MWCryptRand
::generateHex( 40 );
3286 $this->setOption( $oname, $token );
3291 * Return a list of the types of user options currently returned by
3292 * User::getOptionKinds().
3294 * Currently, the option kinds are:
3295 * - 'registered' - preferences which are registered in core MediaWiki or
3296 * by extensions using the UserGetDefaultOptions hook.
3297 * - 'registered-multiselect' - as above, using the 'multiselect' type.
3298 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
3299 * - 'userjs' - preferences with names starting with 'userjs-', intended to
3300 * be used by user scripts.
3301 * - 'special' - "preferences" that are not accessible via User::getOptions
3302 * or User::setOptions.
3303 * - 'unused' - preferences about which MediaWiki doesn't know anything.
3304 * These are usually legacy options, removed in newer versions.
3306 * The API (and possibly others) use this function to determine the possible
3307 * option types for validation purposes, so make sure to update this when a
3308 * new option kind is added.
3310 * @see User::getOptionKinds
3311 * @return array Option kinds
3313 public static function listOptionKinds() {
3316 'registered-multiselect',
3317 'registered-checkmatrix',
3325 * Return an associative array mapping preferences keys to the kind of a preference they're
3326 * used for. Different kinds are handled differently when setting or reading preferences.
3328 * See User::listOptionKinds for the list of valid option types that can be provided.
3330 * @see User::listOptionKinds
3331 * @param IContextSource $context
3332 * @param array|null $options Assoc. array with options keys to check as keys.
3333 * Defaults to $this->mOptions.
3334 * @return array The key => kind mapping data
3336 public function getOptionKinds( IContextSource
$context, $options = null ) {
3337 $this->loadOptions();
3338 if ( $options === null ) {
3339 $options = $this->mOptions
;
3342 $preferencesFactory = MediaWikiServices
::getInstance()->getPreferencesFactory();
3343 $prefs = $preferencesFactory->getFormDescriptor( $this, $context );
3346 // Pull out the "special" options, so they don't get converted as
3347 // multiselect or checkmatrix.
3348 $specialOptions = array_fill_keys( $preferencesFactory->getSaveBlacklist(), true );
3349 foreach ( $specialOptions as $name => $value ) {
3350 unset( $prefs[$name] );
3353 // Multiselect and checkmatrix options are stored in the database with
3354 // one key per option, each having a boolean value. Extract those keys.
3355 $multiselectOptions = [];
3356 foreach ( $prefs as $name => $info ) {
3357 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
3358 ( isset( $info['class'] ) && $info['class'] == HTMLMultiSelectField
::class ) ) {
3359 $opts = HTMLFormField
::flattenOptions( $info['options'] );
3360 $prefix = $info['prefix'] ??
$name;
3362 foreach ( $opts as $value ) {
3363 $multiselectOptions["$prefix$value"] = true;
3366 unset( $prefs[$name] );
3369 $checkmatrixOptions = [];
3370 foreach ( $prefs as $name => $info ) {
3371 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
3372 ( isset( $info['class'] ) && $info['class'] == HTMLCheckMatrix
::class ) ) {
3373 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
3374 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
3375 $prefix = $info['prefix'] ??
$name;
3377 foreach ( $columns as $column ) {
3378 foreach ( $rows as $row ) {
3379 $checkmatrixOptions["$prefix$column-$row"] = true;
3383 unset( $prefs[$name] );
3387 // $value is ignored
3388 foreach ( $options as $key => $value ) {
3389 if ( isset( $prefs[$key] ) ) {
3390 $mapping[$key] = 'registered';
3391 } elseif ( isset( $multiselectOptions[$key] ) ) {
3392 $mapping[$key] = 'registered-multiselect';
3393 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
3394 $mapping[$key] = 'registered-checkmatrix';
3395 } elseif ( isset( $specialOptions[$key] ) ) {
3396 $mapping[$key] = 'special';
3397 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
3398 $mapping[$key] = 'userjs';
3400 $mapping[$key] = 'unused';
3408 * Reset certain (or all) options to the site defaults
3410 * The optional parameter determines which kinds of preferences will be reset.
3411 * Supported values are everything that can be reported by getOptionKinds()
3412 * and 'all', which forces a reset of *all* preferences and overrides everything else.
3414 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
3415 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
3416 * for backwards-compatibility.
3417 * @param IContextSource|null $context Context source used when $resetKinds
3418 * does not contain 'all', passed to getOptionKinds().
3419 * Defaults to RequestContext::getMain() when null.
3421 public function resetOptions(
3422 $resetKinds = [ 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ],
3423 IContextSource
$context = null
3426 $defaultOptions = self
::getDefaultOptions();
3428 if ( !is_array( $resetKinds ) ) {
3429 $resetKinds = [ $resetKinds ];
3432 if ( in_array( 'all', $resetKinds ) ) {
3433 $newOptions = $defaultOptions;
3435 if ( $context === null ) {
3436 $context = RequestContext
::getMain();
3439 $optionKinds = $this->getOptionKinds( $context );
3440 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
3443 // Use default values for the options that should be deleted, and
3444 // copy old values for the ones that shouldn't.
3445 foreach ( $this->mOptions
as $key => $value ) {
3446 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
3447 if ( array_key_exists( $key, $defaultOptions ) ) {
3448 $newOptions[$key] = $defaultOptions[$key];
3451 $newOptions[$key] = $value;
3456 Hooks
::run( 'UserResetAllOptions', [ $this, &$newOptions, $this->mOptions
, $resetKinds ] );
3458 $this->mOptions
= $newOptions;
3459 $this->mOptionsLoaded
= true;
3463 * Get the user's preferred date format.
3464 * @return string User's preferred date format
3466 public function getDatePreference() {
3467 // Important migration for old data rows
3468 if ( is_null( $this->mDatePreference
) ) {
3470 $value = $this->getOption( 'date' );
3471 $map = $wgLang->getDatePreferenceMigrationMap();
3472 if ( isset( $map[$value] ) ) {
3473 $value = $map[$value];
3475 $this->mDatePreference
= $value;
3477 return $this->mDatePreference
;
3481 * Determine based on the wiki configuration and the user's options,
3482 * whether this user must be over HTTPS no matter what.
3486 public function requiresHTTPS() {
3487 global $wgSecureLogin;
3488 if ( !$wgSecureLogin ) {
3491 $https = $this->getBoolOption( 'prefershttps' );
3492 Hooks
::run( 'UserRequiresHTTPS', [ $this, &$https ] );
3494 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
3501 * Get the user preferred stub threshold
3505 public function getStubThreshold() {
3506 global $wgMaxArticleSize; # Maximum article size, in Kb
3507 $threshold = $this->getIntOption( 'stubthreshold' );
3508 if ( $threshold > $wgMaxArticleSize * 1024 ) {
3509 // If they have set an impossible value, disable the preference
3510 // so we can use the parser cache again.
3517 * Get the permissions this user has.
3518 * @return string[] permission names
3520 public function getRights() {
3521 if ( is_null( $this->mRights
) ) {
3522 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
3523 Hooks
::run( 'UserGetRights', [ $this, &$this->mRights
] );
3525 // Deny any rights denied by the user's session, unless this
3526 // endpoint has no sessions.
3527 if ( !defined( 'MW_NO_SESSION' ) ) {
3528 $allowedRights = $this->getRequest()->getSession()->getAllowedUserRights();
3529 if ( $allowedRights !== null ) {
3530 $this->mRights
= array_intersect( $this->mRights
, $allowedRights );
3534 // Force reindexation of rights when a hook has unset one of them
3535 $this->mRights
= array_values( array_unique( $this->mRights
) );
3537 // If block disables login, we should also remove any
3538 // extra rights blocked users might have, in case the
3539 // blocked user has a pre-existing session (T129738).
3540 // This is checked here for cases where people only call
3541 // $user->isAllowed(). It is also checked in Title::checkUserBlock()
3542 // to give a better error message in the common case.
3543 $config = RequestContext
::getMain()->getConfig();
3545 $this->isLoggedIn() &&
3546 $config->get( 'BlockDisablesLogin' ) &&
3550 $this->mRights
= array_intersect( $this->mRights
, $anon->getRights() );
3553 return $this->mRights
;
3557 * Get the list of explicit group memberships this user has.
3558 * The implicit * and user groups are not included.
3559 * @return array Array of String internal group names
3561 public function getGroups() {
3563 $this->loadGroups();
3564 return array_keys( $this->mGroupMemberships
);
3568 * Get the list of explicit group memberships this user has, stored as
3569 * UserGroupMembership objects. Implicit groups are not included.
3571 * @return UserGroupMembership[] Associative array of (group name => UserGroupMembership object)
3574 public function getGroupMemberships() {
3576 $this->loadGroups();
3577 return $this->mGroupMemberships
;
3581 * Get the list of implicit group memberships this user has.
3582 * This includes all explicit groups, plus 'user' if logged in,
3583 * '*' for all accounts, and autopromoted groups
3584 * @param bool $recache Whether to avoid the cache
3585 * @return array Array of String internal group names
3587 public function getEffectiveGroups( $recache = false ) {
3588 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
3589 $this->mEffectiveGroups
= array_unique( array_merge(
3590 $this->getGroups(), // explicit groups
3591 $this->getAutomaticGroups( $recache ) // implicit groups
3593 // Avoid PHP 7.1 warning of passing $this by reference
3595 // Hook for additional groups
3596 Hooks
::run( 'UserEffectiveGroups', [ &$user, &$this->mEffectiveGroups
] );
3597 // Force reindexation of groups when a hook has unset one of them
3598 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
3600 return $this->mEffectiveGroups
;
3604 * Get the list of implicit group memberships this user has.
3605 * This includes 'user' if logged in, '*' for all accounts,
3606 * and autopromoted groups
3607 * @param bool $recache Whether to avoid the cache
3608 * @return array Array of String internal group names
3610 public function getAutomaticGroups( $recache = false ) {
3611 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
3612 $this->mImplicitGroups
= [ '*' ];
3613 if ( $this->getId() ) {
3614 $this->mImplicitGroups
[] = 'user';
3616 $this->mImplicitGroups
= array_unique( array_merge(
3617 $this->mImplicitGroups
,
3618 Autopromote
::getAutopromoteGroups( $this )
3622 // Assure data consistency with rights/groups,
3623 // as getEffectiveGroups() depends on this function
3624 $this->mEffectiveGroups
= null;
3627 return $this->mImplicitGroups
;
3631 * Returns the groups the user has belonged to.
3633 * The user may still belong to the returned groups. Compare with getGroups().
3635 * The function will not return groups the user had belonged to before MW 1.17
3637 * @return array Names of the groups the user has belonged to.
3639 public function getFormerGroups() {
3642 if ( is_null( $this->mFormerGroups
) ) {
3643 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3644 ?
wfGetDB( DB_MASTER
)
3645 : wfGetDB( DB_REPLICA
);
3646 $res = $db->select( 'user_former_groups',
3648 [ 'ufg_user' => $this->mId
],
3650 $this->mFormerGroups
= [];
3651 foreach ( $res as $row ) {
3652 $this->mFormerGroups
[] = $row->ufg_group
;
3656 return $this->mFormerGroups
;
3660 * Get the user's edit count.
3661 * @return int|null Null for anonymous users
3663 public function getEditCount() {
3664 if ( !$this->getId() ) {
3668 if ( $this->mEditCount
=== null ) {
3669 /* Populate the count, if it has not been populated yet */
3670 $dbr = wfGetDB( DB_REPLICA
);
3671 // check if the user_editcount field has been initialized
3672 $count = $dbr->selectField(
3673 'user', 'user_editcount',
3674 [ 'user_id' => $this->mId
],
3678 if ( $count === null ) {
3679 // it has not been initialized. do so.
3680 $count = $this->initEditCount();
3682 $this->mEditCount
= $count;
3684 return (int)$this->mEditCount
;
3688 * Add the user to the given group. This takes immediate effect.
3689 * If the user is already in the group, the expiry time will be updated to the new
3690 * expiry time. (If $expiry is omitted or null, the membership will be altered to
3693 * @param string $group Name of the group to add
3694 * @param string|null $expiry Optional expiry timestamp in any format acceptable to
3695 * wfTimestamp(), or null if the group assignment should not expire
3698 public function addGroup( $group, $expiry = null ) {
3700 $this->loadGroups();
3703 $expiry = wfTimestamp( TS_MW
, $expiry );
3706 if ( !Hooks
::run( 'UserAddGroup', [ $this, &$group, &$expiry ] ) ) {
3710 // create the new UserGroupMembership and put it in the DB
3711 $ugm = new UserGroupMembership( $this->mId
, $group, $expiry );
3712 if ( !$ugm->insert( true ) ) {
3716 $this->mGroupMemberships
[$group] = $ugm;
3718 // Refresh the groups caches, and clear the rights cache so it will be
3719 // refreshed on the next call to $this->getRights().
3720 $this->getEffectiveGroups( true );
3721 $this->mRights
= null;
3723 $this->invalidateCache();
3729 * Remove the user from the given group.
3730 * This takes immediate effect.
3731 * @param string $group Name of the group to remove
3734 public function removeGroup( $group ) {
3737 if ( !Hooks
::run( 'UserRemoveGroup', [ $this, &$group ] ) ) {
3741 $ugm = UserGroupMembership
::getMembership( $this->mId
, $group );
3742 // delete the membership entry
3743 if ( !$ugm ||
!$ugm->delete() ) {
3747 $this->loadGroups();
3748 unset( $this->mGroupMemberships
[$group] );
3750 // Refresh the groups caches, and clear the rights cache so it will be
3751 // refreshed on the next call to $this->getRights().
3752 $this->getEffectiveGroups( true );
3753 $this->mRights
= null;
3755 $this->invalidateCache();
3761 * Get whether the user is logged in
3764 public function isLoggedIn() {
3765 return $this->getId() != 0;
3769 * Get whether the user is anonymous
3772 public function isAnon() {
3773 return !$this->isLoggedIn();
3777 * @return bool Whether this user is flagged as being a bot role account
3780 public function isBot() {
3781 if ( in_array( 'bot', $this->getGroups() ) && $this->isAllowed( 'bot' ) ) {
3786 Hooks
::run( "UserIsBot", [ $this, &$isBot ] );
3792 * Check if user is allowed to access a feature / make an action
3794 * @param string $permissions,... Permissions to test
3795 * @return bool True if user is allowed to perform *any* of the given actions
3797 public function isAllowedAny() {
3798 $permissions = func_get_args();
3799 foreach ( $permissions as $permission ) {
3800 if ( $this->isAllowed( $permission ) ) {
3809 * @param string $permissions,... Permissions to test
3810 * @return bool True if the user is allowed to perform *all* of the given actions
3812 public function isAllowedAll() {
3813 $permissions = func_get_args();
3814 foreach ( $permissions as $permission ) {
3815 if ( !$this->isAllowed( $permission ) ) {
3823 * Internal mechanics of testing a permission
3824 * @param string $action
3827 public function isAllowed( $action = '' ) {
3828 if ( $action === '' ) {
3829 return true; // In the spirit of DWIM
3831 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3832 // by misconfiguration: 0 == 'foo'
3833 return in_array( $action, $this->getRights(), true );
3837 * Check whether to enable recent changes patrol features for this user
3838 * @return bool True or false
3840 public function useRCPatrol() {
3841 global $wgUseRCPatrol;
3842 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3846 * Check whether to enable new pages patrol features for this user
3847 * @return bool True or false
3849 public function useNPPatrol() {
3850 global $wgUseRCPatrol, $wgUseNPPatrol;
3852 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3853 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3858 * Check whether to enable new files patrol features for this user
3859 * @return bool True or false
3861 public function useFilePatrol() {
3862 global $wgUseRCPatrol, $wgUseFilePatrol;
3864 ( $wgUseRCPatrol ||
$wgUseFilePatrol )
3865 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3870 * Get the WebRequest object to use with this object
3872 * @return WebRequest
3874 public function getRequest() {
3875 if ( $this->mRequest
) {
3876 return $this->mRequest
;
3884 * Check the watched status of an article.
3885 * @since 1.22 $checkRights parameter added
3886 * @param Title $title Title of the article to look at
3887 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3888 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3891 public function isWatched( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3892 if ( $title->isWatchable() && ( !$checkRights ||
$this->isAllowed( 'viewmywatchlist' ) ) ) {
3893 return MediaWikiServices
::getInstance()->getWatchedItemStore()->isWatched( $this, $title );
3900 * @since 1.22 $checkRights parameter added
3901 * @param Title $title Title of the article to look at
3902 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3903 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3905 public function addWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3906 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3907 MediaWikiServices
::getInstance()->getWatchedItemStore()->addWatchBatchForUser(
3909 [ $title->getSubjectPage(), $title->getTalkPage() ]
3912 $this->invalidateCache();
3916 * Stop watching an article.
3917 * @since 1.22 $checkRights parameter added
3918 * @param Title $title Title of the article to look at
3919 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3920 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3922 public function removeWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3923 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3924 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
3925 $store->removeWatch( $this, $title->getSubjectPage() );
3926 $store->removeWatch( $this, $title->getTalkPage() );
3928 $this->invalidateCache();
3932 * Clear the user's notification timestamp for the given title.
3933 * If e-notif e-mails are on, they will receive notification mails on
3934 * the next change of the page if it's watched etc.
3935 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3936 * @param Title &$title Title of the article to look at
3937 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3939 public function clearNotification( &$title, $oldid = 0 ) {
3940 global $wgUseEnotif, $wgShowUpdatedMarker;
3942 // Do nothing if the database is locked to writes
3943 if ( wfReadOnly() ) {
3947 // Do nothing if not allowed to edit the watchlist
3948 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3952 // If we're working on user's talk page, we should update the talk page message indicator
3953 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3954 // Avoid PHP 7.1 warning of passing $this by reference
3956 if ( !Hooks
::run( 'UserClearNewTalkNotification', [ &$user, $oldid ] ) ) {
3960 // Try to update the DB post-send and only if needed...
3961 DeferredUpdates
::addCallableUpdate( function () use ( $title, $oldid ) {
3962 if ( !$this->getNewtalk() ) {
3963 return; // no notifications to clear
3966 // Delete the last notifications (they stack up)
3967 $this->setNewtalk( false );
3969 // If there is a new, unseen, revision, use its timestamp
3971 ?
$title->getNextRevisionID( $oldid, Title
::GAID_FOR_UPDATE
)
3974 $this->setNewtalk( true, Revision
::newFromId( $nextid ) );
3979 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3983 if ( $this->isAnon() ) {
3984 // Nothing else to do...
3988 // Only update the timestamp if the page is being watched.
3989 // The query to find out if it is watched is cached both in memcached and per-invocation,
3990 // and when it does have to be executed, it can be on a replica DB
3991 // If this is the user's newtalk page, we always update the timestamp
3993 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3997 MediaWikiServices
::getInstance()->getWatchedItemStore()
3998 ->resetNotificationTimestamp( $this, $title, $force, $oldid );
4002 * Resets all of the given user's page-change notification timestamps.
4003 * If e-notif e-mails are on, they will receive notification mails on
4004 * the next change of any watched page.
4005 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
4007 public function clearAllNotifications() {
4008 global $wgUseEnotif, $wgShowUpdatedMarker;
4009 // Do nothing if not allowed to edit the watchlist
4010 if ( wfReadOnly() ||
!$this->isAllowed( 'editmywatchlist' ) ) {
4014 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
4015 $this->setNewtalk( false );
4019 $id = $this->getId();
4024 $watchedItemStore = MediaWikiServices
::getInstance()->getWatchedItemStore();
4025 $watchedItemStore->resetAllNotificationTimestampsForUser( $this );
4027 // We also need to clear here the "you have new message" notification for the own
4028 // user_talk page; it's cleared one page view later in WikiPage::doViewUpdates().
4032 * Compute experienced level based on edit count and registration date.
4034 * @return string 'newcomer', 'learner', or 'experienced'
4036 public function getExperienceLevel() {
4037 global $wgLearnerEdits,
4038 $wgExperiencedUserEdits,
4039 $wgLearnerMemberSince,
4040 $wgExperiencedUserMemberSince;
4042 if ( $this->isAnon() ) {
4046 $editCount = $this->getEditCount();
4047 $registration = $this->getRegistration();
4049 $learnerRegistration = wfTimestamp( TS_MW
, $now - $wgLearnerMemberSince * 86400 );
4050 $experiencedRegistration = wfTimestamp( TS_MW
, $now - $wgExperiencedUserMemberSince * 86400 );
4053 $editCount < $wgLearnerEdits ||
4054 $registration > $learnerRegistration
4058 $editCount > $wgExperiencedUserEdits &&
4059 $registration <= $experiencedRegistration
4061 return 'experienced';
4068 * Persist this user's session (e.g. set cookies)
4070 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
4072 * @param bool|null $secure Whether to force secure/insecure cookies or use default
4073 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
4075 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
4077 if ( 0 == $this->mId
) {
4081 $session = $this->getRequest()->getSession();
4082 if ( $request && $session->getRequest() !== $request ) {
4083 $session = $session->sessionWithRequest( $request );
4085 $delay = $session->delaySave();
4087 if ( !$session->getUser()->equals( $this ) ) {
4088 if ( !$session->canSetUser() ) {
4089 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
4090 ->warning( __METHOD__
.
4091 ": Cannot save user \"$this\" to a user \"{$session->getUser()}\"'s immutable session"
4095 $session->setUser( $this );
4098 $session->setRememberUser( $rememberMe );
4099 if ( $secure !== null ) {
4100 $session->setForceHTTPS( $secure );
4103 $session->persist();
4105 ScopedCallback
::consume( $delay );
4109 * Log this user out.
4111 public function logout() {
4112 // Avoid PHP 7.1 warning of passing $this by reference
4114 if ( Hooks
::run( 'UserLogout', [ &$user ] ) ) {
4120 * Clear the user's session, and reset the instance cache.
4123 public function doLogout() {
4124 $session = $this->getRequest()->getSession();
4125 if ( !$session->canSetUser() ) {
4126 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
4127 ->warning( __METHOD__
. ": Cannot log out of an immutable session" );
4128 $error = 'immutable';
4129 } elseif ( !$session->getUser()->equals( $this ) ) {
4130 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
4131 ->warning( __METHOD__
.
4132 ": Cannot log user \"$this\" out of a user \"{$session->getUser()}\"'s session"
4134 // But we still may as well make this user object anon
4135 $this->clearInstanceCache( 'defaults' );
4136 $error = 'wronguser';
4138 $this->clearInstanceCache( 'defaults' );
4139 $delay = $session->delaySave();
4140 $session->unpersist(); // Clear cookies (T127436)
4141 $session->setLoggedOutTimestamp( time() );
4142 $session->setUser( new User
);
4143 $session->set( 'wsUserID', 0 ); // Other code expects this
4144 $session->resetAllTokens();
4145 ScopedCallback
::consume( $delay );
4148 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authevents' )->info( 'Logout', [
4149 'event' => 'logout',
4150 'successful' => $error === false,
4151 'status' => $error ?
: 'success',
4156 * Save this user's settings into the database.
4157 * @todo Only rarely do all these fields need to be set!
4159 public function saveSettings() {
4160 if ( wfReadOnly() ) {
4161 // @TODO: caller should deal with this instead!
4162 // This should really just be an exception.
4163 MWExceptionHandler
::logException( new DBExpectedError(
4165 "Could not update user with ID '{$this->mId}'; DB is read-only."
4171 if ( 0 == $this->mId
) {
4175 // Get a new user_touched that is higher than the old one.
4176 // This will be used for a CAS check as a last-resort safety
4177 // check against race conditions and replica DB lag.
4178 $newTouched = $this->newTouchedTimestamp();
4180 $dbw = wfGetDB( DB_MASTER
);
4181 $dbw->doAtomicSection( __METHOD__
, function ( $dbw, $fname ) use ( $newTouched ) {
4182 global $wgActorTableSchemaMigrationStage;
4184 $dbw->update( 'user',
4186 'user_name' => $this->mName
,
4187 'user_real_name' => $this->mRealName
,
4188 'user_email' => $this->mEmail
,
4189 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
4190 'user_touched' => $dbw->timestamp( $newTouched ),
4191 'user_token' => strval( $this->mToken
),
4192 'user_email_token' => $this->mEmailToken
,
4193 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
4194 ], $this->makeUpdateConditions( $dbw, [ /* WHERE */
4195 'user_id' => $this->mId
,
4199 if ( !$dbw->affectedRows() ) {
4200 // Maybe the problem was a missed cache update; clear it to be safe
4201 $this->clearSharedCache( 'refresh' );
4202 // User was changed in the meantime or loaded with stale data
4203 $from = ( $this->queryFlagsUsed
& self
::READ_LATEST
) ?
'master' : 'replica';
4204 throw new MWException(
4205 "CAS update failed on user_touched for user ID '{$this->mId}' (read from $from);" .
4206 " the version of the user to be saved is older than the current version."
4210 if ( $wgActorTableSchemaMigrationStage > MIGRATION_OLD
) {
4213 [ 'actor_name' => $this->mName
],
4214 [ 'actor_user' => $this->mId
],
4220 $this->mTouched
= $newTouched;
4221 $this->saveOptions();
4223 Hooks
::run( 'UserSaveSettings', [ $this ] );
4224 $this->clearSharedCache();
4225 $this->getUserPage()->invalidateCache();
4229 * If only this user's username is known, and it exists, return the user ID.
4231 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
4234 public function idForName( $flags = 0 ) {
4235 $s = trim( $this->getName() );
4240 $db = ( ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
)
4241 ?
wfGetDB( DB_MASTER
)
4242 : wfGetDB( DB_REPLICA
);
4244 $options = ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
)
4245 ?
[ 'LOCK IN SHARE MODE' ]
4248 $id = $db->selectField( 'user',
4249 'user_id', [ 'user_name' => $s ], __METHOD__
, $options );
4255 * Add a user to the database, return the user object
4257 * @param string $name Username to add
4258 * @param array $params Array of Strings Non-default parameters to save to
4259 * the database as user_* fields:
4260 * - email: The user's email address.
4261 * - email_authenticated: The email authentication timestamp.
4262 * - real_name: The user's real name.
4263 * - options: An associative array of non-default options.
4264 * - token: Random authentication token. Do not set.
4265 * - registration: Registration timestamp. Do not set.
4267 * @return User|null User object, or null if the username already exists.
4269 public static function createNew( $name, $params = [] ) {
4270 foreach ( [ 'password', 'newpassword', 'newpass_time', 'password_expires' ] as $field ) {
4271 if ( isset( $params[$field] ) ) {
4272 wfDeprecated( __METHOD__
. " with param '$field'", '1.27' );
4273 unset( $params[$field] );
4279 $user->setToken(); // init token
4280 if ( isset( $params['options'] ) ) {
4281 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
4282 unset( $params['options'] );
4284 $dbw = wfGetDB( DB_MASTER
);
4286 $noPass = PasswordFactory
::newInvalidPassword()->toString();
4289 'user_name' => $name,
4290 'user_password' => $noPass,
4291 'user_newpassword' => $noPass,
4292 'user_email' => $user->mEmail
,
4293 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
4294 'user_real_name' => $user->mRealName
,
4295 'user_token' => strval( $user->mToken
),
4296 'user_registration' => $dbw->timestamp( $user->mRegistration
),
4297 'user_editcount' => 0,
4298 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
4300 foreach ( $params as $name => $value ) {
4301 $fields["user_$name"] = $value;
4304 return $dbw->doAtomicSection( __METHOD__
, function ( $dbw, $fname ) use ( $fields ) {
4305 $dbw->insert( 'user', $fields, $fname, [ 'IGNORE' ] );
4306 if ( $dbw->affectedRows() ) {
4307 $newUser = self
::newFromId( $dbw->insertId() );
4308 // Load the user from master to avoid replica lag
4309 $newUser->load( self
::READ_LATEST
);
4310 $newUser->updateActorId( $dbw );
4319 * Add this existing user object to the database. If the user already
4320 * exists, a fatal status object is returned, and the user object is
4321 * initialised with the data from the database.
4323 * Previously, this function generated a DB error due to a key conflict
4324 * if the user already existed. Many extension callers use this function
4325 * in code along the lines of:
4327 * $user = User::newFromName( $name );
4328 * if ( !$user->isLoggedIn() ) {
4329 * $user->addToDatabase();
4331 * // do something with $user...
4333 * However, this was vulnerable to a race condition (T18020). By
4334 * initialising the user object if the user exists, we aim to support this
4335 * calling sequence as far as possible.
4337 * Note that if the user exists, this function will acquire a write lock,
4338 * so it is still advisable to make the call conditional on isLoggedIn(),
4339 * and to commit the transaction after calling.
4341 * @throws MWException
4344 public function addToDatabase() {
4346 if ( !$this->mToken
) {
4347 $this->setToken(); // init token
4350 if ( !is_string( $this->mName
) ) {
4351 throw new RuntimeException( "User name field is not set." );
4354 $this->mTouched
= $this->newTouchedTimestamp();
4356 $dbw = wfGetDB( DB_MASTER
);
4357 $status = $dbw->doAtomicSection( __METHOD__
, function ( $dbw, $fname ) {
4358 $noPass = PasswordFactory
::newInvalidPassword()->toString();
4359 $dbw->insert( 'user',
4361 'user_name' => $this->mName
,
4362 'user_password' => $noPass,
4363 'user_newpassword' => $noPass,
4364 'user_email' => $this->mEmail
,
4365 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
4366 'user_real_name' => $this->mRealName
,
4367 'user_token' => strval( $this->mToken
),
4368 'user_registration' => $dbw->timestamp( $this->mRegistration
),
4369 'user_editcount' => 0,
4370 'user_touched' => $dbw->timestamp( $this->mTouched
),
4374 if ( !$dbw->affectedRows() ) {
4375 // Use locking reads to bypass any REPEATABLE-READ snapshot.
4376 $this->mId
= $dbw->selectField(
4379 [ 'user_name' => $this->mName
],
4381 [ 'LOCK IN SHARE MODE' ]
4385 if ( $this->loadFromDatabase( self
::READ_LOCKING
) ) {
4390 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
4391 "to insert user '{$this->mName}' row, but it was not present in select!" );
4393 return Status
::newFatal( 'userexists' );
4395 $this->mId
= $dbw->insertId();
4396 self
::$idCacheByName[$this->mName
] = $this->mId
;
4397 $this->updateActorId( $dbw );
4399 return Status
::newGood();
4401 if ( !$status->isGood() ) {
4405 // Clear instance cache other than user table data and actor, which is already accurate
4406 $this->clearInstanceCache();
4408 $this->saveOptions();
4409 return Status
::newGood();
4413 * Update the actor ID after an insert
4414 * @param IDatabase $dbw Writable database handle
4416 private function updateActorId( IDatabase
$dbw ) {
4417 global $wgActorTableSchemaMigrationStage;
4419 if ( $wgActorTableSchemaMigrationStage > MIGRATION_OLD
) {
4422 [ 'actor_user' => $this->mId
, 'actor_name' => $this->mName
],
4425 $this->mActorId
= (int)$dbw->insertId();
4430 * If this user is logged-in and blocked,
4431 * block any IP address they've successfully logged in from.
4432 * @return bool A block was spread
4434 public function spreadAnyEditBlock() {
4435 if ( $this->isLoggedIn() && $this->isBlocked() ) {
4436 return $this->spreadBlock();
4443 * If this (non-anonymous) user is blocked,
4444 * block the IP address they've successfully logged in from.
4445 * @return bool A block was spread
4447 protected function spreadBlock() {
4448 wfDebug( __METHOD__
. "()\n" );
4450 if ( $this->mId
== 0 ) {
4454 $userblock = Block
::newFromTarget( $this->getName() );
4455 if ( !$userblock ) {
4459 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
4463 * Get whether the user is explicitly blocked from account creation.
4464 * @return bool|Block
4466 public function isBlockedFromCreateAccount() {
4467 $this->getBlockedStatus();
4468 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
4469 return $this->mBlock
;
4472 # T15611: if the IP address the user is trying to create an account from is
4473 # blocked with createaccount disabled, prevent new account creation there even
4474 # when the user is logged in
4475 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
4476 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
4478 return $this->mBlockedFromCreateAccount
instanceof Block
4479 && $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
4480 ?
$this->mBlockedFromCreateAccount
4485 * Get whether the user is blocked from using Special:Emailuser.
4488 public function isBlockedFromEmailuser() {
4489 $this->getBlockedStatus();
4490 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
4494 * Get whether the user is allowed to create an account.
4497 public function isAllowedToCreateAccount() {
4498 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
4502 * Get this user's personal page title.
4504 * @return Title User's personal page title
4506 public function getUserPage() {
4507 return Title
::makeTitle( NS_USER
, $this->getName() );
4511 * Get this user's talk page title.
4513 * @return Title User's talk page title
4515 public function getTalkPage() {
4516 $title = $this->getUserPage();
4517 return $title->getTalkPage();
4521 * Determine whether the user is a newbie. Newbies are either
4522 * anonymous IPs, or the most recently created accounts.
4525 public function isNewbie() {
4526 return !$this->isAllowed( 'autoconfirmed' );
4530 * Check to see if the given clear-text password is one of the accepted passwords
4531 * @deprecated since 1.27, use AuthManager instead
4532 * @param string $password User password
4533 * @return bool True if the given password is correct, otherwise False
4535 public function checkPassword( $password ) {
4536 $manager = AuthManager
::singleton();
4537 $reqs = AuthenticationRequest
::loadRequestsFromSubmission(
4538 $manager->getAuthenticationRequests( AuthManager
::ACTION_LOGIN
),
4540 'username' => $this->getName(),
4541 'password' => $password,
4544 $res = AuthManager
::singleton()->beginAuthentication( $reqs, 'null:' );
4545 switch ( $res->status
) {
4546 case AuthenticationResponse
::PASS
:
4548 case AuthenticationResponse
::FAIL
:
4549 // Hope it's not a PreAuthenticationProvider that failed...
4550 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
4551 ->info( __METHOD__
. ': Authentication failed: ' . $res->message
->plain() );
4554 throw new BadMethodCallException(
4555 'AuthManager returned a response unsupported by ' . __METHOD__
4561 * Check if the given clear-text password matches the temporary password
4562 * sent by e-mail for password reset operations.
4564 * @deprecated since 1.27, use AuthManager instead
4565 * @param string $plaintext
4566 * @return bool True if matches, false otherwise
4568 public function checkTemporaryPassword( $plaintext ) {
4569 // Can't check the temporary password individually.
4570 return $this->checkPassword( $plaintext );
4574 * Initialize (if necessary) and return a session token value
4575 * which can be used in edit forms to show that the user's
4576 * login credentials aren't being hijacked with a foreign form
4580 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4581 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4582 * @return MediaWiki\Session\Token The new edit token
4584 public function getEditTokenObject( $salt = '', $request = null ) {
4585 if ( $this->isAnon() ) {
4586 return new LoggedOutEditToken();
4590 $request = $this->getRequest();
4592 return $request->getSession()->getToken( $salt );
4596 * Initialize (if necessary) and return a session token value
4597 * which can be used in edit forms to show that the user's
4598 * login credentials aren't being hijacked with a foreign form
4601 * The $salt for 'edit' and 'csrf' tokens is the default (empty string).
4604 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4605 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4606 * @return string The new edit token
4608 public function getEditToken( $salt = '', $request = null ) {
4609 return $this->getEditTokenObject( $salt, $request )->toString();
4613 * Check given value against the token value stored in the session.
4614 * A match should confirm that the form was submitted from the
4615 * user's own login session, not a form submission from a third-party
4618 * @param string $val Input value to compare
4619 * @param string|array $salt Optional function-specific data for hashing
4620 * @param WebRequest|null $request Object to use or null to use $wgRequest
4621 * @param int|null $maxage Fail tokens older than this, in seconds
4622 * @return bool Whether the token matches
4624 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4625 return $this->getEditTokenObject( $salt, $request )->match( $val, $maxage );
4629 * Check given value against the token value stored in the session,
4630 * ignoring the suffix.
4632 * @param string $val Input value to compare
4633 * @param string|array $salt Optional function-specific data for hashing
4634 * @param WebRequest|null $request Object to use or null to use $wgRequest
4635 * @param int|null $maxage Fail tokens older than this, in seconds
4636 * @return bool Whether the token matches
4638 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4639 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . Token
::SUFFIX
;
4640 return $this->matchEditToken( $val, $salt, $request, $maxage );
4644 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4645 * mail to the user's given address.
4647 * @param string $type Message to send, either "created", "changed" or "set"
4650 public function sendConfirmationMail( $type = 'created' ) {
4652 $expiration = null; // gets passed-by-ref and defined in next line.
4653 $token = $this->confirmationToken( $expiration );
4654 $url = $this->confirmationTokenUrl( $token );
4655 $invalidateURL = $this->invalidationTokenUrl( $token );
4656 $this->saveSettings();
4658 if ( $type == 'created' ||
$type === false ) {
4659 $message = 'confirmemail_body';
4660 } elseif ( $type === true ) {
4661 $message = 'confirmemail_body_changed';
4663 // Messages: confirmemail_body_changed, confirmemail_body_set
4664 $message = 'confirmemail_body_' . $type;
4667 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4668 wfMessage( $message,
4669 $this->getRequest()->getIP(),
4672 $wgLang->userTimeAndDate( $expiration, $this ),
4674 $wgLang->userDate( $expiration, $this ),
4675 $wgLang->userTime( $expiration, $this ) )->text() );
4679 * Send an e-mail to this user's account. Does not check for
4680 * confirmed status or validity.
4682 * @param string $subject Message subject
4683 * @param string $body Message body
4684 * @param User|null $from Optional sending user; if unspecified, default
4685 * $wgPasswordSender will be used.
4686 * @param string|null $replyto Reply-To address
4689 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4690 global $wgPasswordSender;
4692 if ( $from instanceof User
) {
4693 $sender = MailAddress
::newFromUser( $from );
4695 $sender = new MailAddress( $wgPasswordSender,
4696 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4698 $to = MailAddress
::newFromUser( $this );
4700 return UserMailer
::send( $to, $sender, $subject, $body, [
4701 'replyTo' => $replyto,
4706 * Generate, store, and return a new e-mail confirmation code.
4707 * A hash (unsalted, since it's used as a key) is stored.
4709 * @note Call saveSettings() after calling this function to commit
4710 * this change to the database.
4712 * @param string &$expiration Accepts the expiration time
4713 * @return string New token
4715 protected function confirmationToken( &$expiration ) {
4716 global $wgUserEmailConfirmationTokenExpiry;
4718 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4719 $expiration = wfTimestamp( TS_MW
, $expires );
4721 $token = MWCryptRand
::generateHex( 32 );
4722 $hash = md5( $token );
4723 $this->mEmailToken
= $hash;
4724 $this->mEmailTokenExpires
= $expiration;
4729 * Return a URL the user can use to confirm their email address.
4730 * @param string $token Accepts the email confirmation token
4731 * @return string New token URL
4733 protected function confirmationTokenUrl( $token ) {
4734 return $this->getTokenUrl( 'ConfirmEmail', $token );
4738 * Return a URL the user can use to invalidate their email address.
4739 * @param string $token Accepts the email confirmation token
4740 * @return string New token URL
4742 protected function invalidationTokenUrl( $token ) {
4743 return $this->getTokenUrl( 'InvalidateEmail', $token );
4747 * Internal function to format the e-mail validation/invalidation URLs.
4748 * This uses a quickie hack to use the
4749 * hardcoded English names of the Special: pages, for ASCII safety.
4751 * @note Since these URLs get dropped directly into emails, using the
4752 * short English names avoids insanely long URL-encoded links, which
4753 * also sometimes can get corrupted in some browsers/mailers
4754 * (T8957 with Gmail and Internet Explorer).
4756 * @param string $page Special page
4757 * @param string $token
4758 * @return string Formatted URL
4760 protected function getTokenUrl( $page, $token ) {
4761 // Hack to bypass localization of 'Special:'
4762 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4763 return $title->getCanonicalURL();
4767 * Mark the e-mail address confirmed.
4769 * @note Call saveSettings() after calling this function to commit the change.
4773 public function confirmEmail() {
4774 // Check if it's already confirmed, so we don't touch the database
4775 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4776 if ( !$this->isEmailConfirmed() ) {
4777 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4778 Hooks
::run( 'ConfirmEmailComplete', [ $this ] );
4784 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4785 * address if it was already confirmed.
4787 * @note Call saveSettings() after calling this function to commit the change.
4788 * @return bool Returns true
4790 public function invalidateEmail() {
4792 $this->mEmailToken
= null;
4793 $this->mEmailTokenExpires
= null;
4794 $this->setEmailAuthenticationTimestamp( null );
4796 Hooks
::run( 'InvalidateEmailComplete', [ $this ] );
4801 * Set the e-mail authentication timestamp.
4802 * @param string $timestamp TS_MW timestamp
4804 public function setEmailAuthenticationTimestamp( $timestamp ) {
4806 $this->mEmailAuthenticated
= $timestamp;
4807 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
4811 * Is this user allowed to send e-mails within limits of current
4812 * site configuration?
4815 public function canSendEmail() {
4816 global $wgEnableEmail, $wgEnableUserEmail;
4817 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4820 $canSend = $this->isEmailConfirmed();
4821 // Avoid PHP 7.1 warning of passing $this by reference
4823 Hooks
::run( 'UserCanSendEmail', [ &$user, &$canSend ] );
4828 * Is this user allowed to receive e-mails within limits of current
4829 * site configuration?
4832 public function canReceiveEmail() {
4833 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4837 * Is this user's e-mail address valid-looking and confirmed within
4838 * limits of the current site configuration?
4840 * @note If $wgEmailAuthentication is on, this may require the user to have
4841 * confirmed their address by returning a code or using a password
4842 * sent to the address from the wiki.
4846 public function isEmailConfirmed() {
4847 global $wgEmailAuthentication;
4849 // Avoid PHP 7.1 warning of passing $this by reference
4852 if ( Hooks
::run( 'EmailConfirmed', [ &$user, &$confirmed ] ) ) {
4853 if ( $this->isAnon() ) {
4856 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4859 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4869 * Check whether there is an outstanding request for e-mail confirmation.
4872 public function isEmailConfirmationPending() {
4873 global $wgEmailAuthentication;
4874 return $wgEmailAuthentication &&
4875 !$this->isEmailConfirmed() &&
4876 $this->mEmailToken
&&
4877 $this->mEmailTokenExpires
> wfTimestamp();
4881 * Get the timestamp of account creation.
4883 * @return string|bool|null Timestamp of account creation, false for
4884 * non-existent/anonymous user accounts, or null if existing account
4885 * but information is not in database.
4887 public function getRegistration() {
4888 if ( $this->isAnon() ) {
4892 return $this->mRegistration
;
4896 * Get the timestamp of the first edit
4898 * @return string|bool Timestamp of first edit, or false for
4899 * non-existent/anonymous user accounts.
4901 public function getFirstEditTimestamp() {
4902 if ( $this->getId() == 0 ) {
4903 return false; // anons
4905 $dbr = wfGetDB( DB_REPLICA
);
4906 $actorWhere = ActorMigration
::newMigration()->getWhere( $dbr, 'rev_user', $this );
4907 $time = $dbr->selectField(
4908 [ 'revision' ] +
$actorWhere['tables'],
4910 [ $actorWhere['conds'] ],
4912 [ 'ORDER BY' => 'rev_timestamp ASC' ],
4913 $actorWhere['joins']
4916 return false; // no edits
4918 return wfTimestamp( TS_MW
, $time );
4922 * Get the permissions associated with a given list of groups
4924 * @param array $groups Array of Strings List of internal group names
4925 * @return array Array of Strings List of permission key names for given groups combined
4927 public static function getGroupPermissions( $groups ) {
4928 global $wgGroupPermissions, $wgRevokePermissions;
4930 // grant every granted permission first
4931 foreach ( $groups as $group ) {
4932 if ( isset( $wgGroupPermissions[$group] ) ) {
4933 $rights = array_merge( $rights,
4934 // array_filter removes empty items
4935 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4938 // now revoke the revoked permissions
4939 foreach ( $groups as $group ) {
4940 if ( isset( $wgRevokePermissions[$group] ) ) {
4941 $rights = array_diff( $rights,
4942 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4945 return array_unique( $rights );
4949 * Get all the groups who have a given permission
4951 * @param string $role Role to check
4952 * @return array Array of Strings List of internal group names with the given permission
4954 public static function getGroupsWithPermission( $role ) {
4955 global $wgGroupPermissions;
4956 $allowedGroups = [];
4957 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4958 if ( self
::groupHasPermission( $group, $role ) ) {
4959 $allowedGroups[] = $group;
4962 return $allowedGroups;
4966 * Check, if the given group has the given permission
4968 * If you're wanting to check whether all users have a permission, use
4969 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4973 * @param string $group Group to check
4974 * @param string $role Role to check
4977 public static function groupHasPermission( $group, $role ) {
4978 global $wgGroupPermissions, $wgRevokePermissions;
4979 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4980 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4984 * Check if all users may be assumed to have the given permission
4986 * We generally assume so if the right is granted to '*' and isn't revoked
4987 * on any group. It doesn't attempt to take grants or other extension
4988 * limitations on rights into account in the general case, though, as that
4989 * would require it to always return false and defeat the purpose.
4990 * Specifically, session-based rights restrictions (such as OAuth or bot
4991 * passwords) are applied based on the current session.
4994 * @param string $right Right to check
4997 public static function isEveryoneAllowed( $right ) {
4998 global $wgGroupPermissions, $wgRevokePermissions;
5001 // Use the cached results, except in unit tests which rely on
5002 // being able change the permission mid-request
5003 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
5004 return $cache[$right];
5007 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
5008 $cache[$right] = false;
5012 // If it's revoked anywhere, then everyone doesn't have it
5013 foreach ( $wgRevokePermissions as $rights ) {
5014 if ( isset( $rights[$right] ) && $rights[$right] ) {
5015 $cache[$right] = false;
5020 // Remove any rights that aren't allowed to the global-session user,
5021 // unless there are no sessions for this endpoint.
5022 if ( !defined( 'MW_NO_SESSION' ) ) {
5023 $allowedRights = SessionManager
::getGlobalSession()->getAllowedUserRights();
5024 if ( $allowedRights !== null && !in_array( $right, $allowedRights, true ) ) {
5025 $cache[$right] = false;
5030 // Allow extensions to say false
5031 if ( !Hooks
::run( 'UserIsEveryoneAllowed', [ $right ] ) ) {
5032 $cache[$right] = false;
5036 $cache[$right] = true;
5041 * Get the localized descriptive name for a group, if it exists
5042 * @deprecated since 1.29 Use UserGroupMembership::getGroupName instead
5044 * @param string $group Internal group name
5045 * @return string Localized descriptive group name
5047 public static function getGroupName( $group ) {
5048 wfDeprecated( __METHOD__
, '1.29' );
5049 return UserGroupMembership
::getGroupName( $group );
5053 * Get the localized descriptive name for a member of a group, if it exists
5054 * @deprecated since 1.29 Use UserGroupMembership::getGroupMemberName instead
5056 * @param string $group Internal group name
5057 * @param string $username Username for gender (since 1.19)
5058 * @return string Localized name for group member
5060 public static function getGroupMember( $group, $username = '#' ) {
5061 wfDeprecated( __METHOD__
, '1.29' );
5062 return UserGroupMembership
::getGroupMemberName( $group, $username );
5066 * Return the set of defined explicit groups.
5067 * The implicit groups (by default *, 'user' and 'autoconfirmed')
5068 * are not included, as they are defined automatically, not in the database.
5069 * @return array Array of internal group names
5071 public static function getAllGroups() {
5072 global $wgGroupPermissions, $wgRevokePermissions;
5074 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
5075 self
::getImplicitGroups()
5080 * Get a list of all available permissions.
5081 * @return string[] Array of permission names
5083 public static function getAllRights() {
5084 if ( self
::$mAllRights === false ) {
5085 global $wgAvailableRights;
5086 if ( count( $wgAvailableRights ) ) {
5087 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
5089 self
::$mAllRights = self
::$mCoreRights;
5091 Hooks
::run( 'UserGetAllRights', [ &self
::$mAllRights ] );
5093 return self
::$mAllRights;
5097 * Get a list of implicit groups
5098 * @return array Array of Strings Array of internal group names
5100 public static function getImplicitGroups() {
5101 global $wgImplicitGroups;
5103 $groups = $wgImplicitGroups;
5104 # Deprecated, use $wgImplicitGroups instead
5105 Hooks
::run( 'UserGetImplicitGroups', [ &$groups ], '1.25' );
5111 * Get the title of a page describing a particular group
5112 * @deprecated since 1.29 Use UserGroupMembership::getGroupPage instead
5114 * @param string $group Internal group name
5115 * @return Title|bool Title of the page if it exists, false otherwise
5117 public static function getGroupPage( $group ) {
5118 wfDeprecated( __METHOD__
, '1.29' );
5119 return UserGroupMembership
::getGroupPage( $group );
5123 * Create a link to the group in HTML, if available;
5124 * else return the group name.
5125 * @deprecated since 1.29 Use UserGroupMembership::getLink instead, or
5126 * make the link yourself if you need custom text
5128 * @param string $group Internal name of the group
5129 * @param string $text The text of the link
5130 * @return string HTML link to the group
5132 public static function makeGroupLinkHTML( $group, $text = '' ) {
5133 wfDeprecated( __METHOD__
, '1.29' );
5135 if ( $text == '' ) {
5136 $text = UserGroupMembership
::getGroupName( $group );
5138 $title = UserGroupMembership
::getGroupPage( $group );
5140 return MediaWikiServices
::getInstance()
5141 ->getLinkRenderer()->makeLink( $title, $text );
5143 return htmlspecialchars( $text );
5148 * Create a link to the group in Wikitext, if available;
5149 * else return the group name.
5150 * @deprecated since 1.29 Use UserGroupMembership::getLink instead, or
5151 * make the link yourself if you need custom text
5153 * @param string $group Internal name of the group
5154 * @param string $text The text of the link
5155 * @return string Wikilink to the group
5157 public static function makeGroupLinkWiki( $group, $text = '' ) {
5158 wfDeprecated( __METHOD__
, '1.29' );
5160 if ( $text == '' ) {
5161 $text = UserGroupMembership
::getGroupName( $group );
5163 $title = UserGroupMembership
::getGroupPage( $group );
5165 $page = $title->getFullText();
5166 return "[[$page|$text]]";
5173 * Returns an array of the groups that a particular group can add/remove.
5175 * @param string $group The group to check for whether it can add/remove
5176 * @return array Array( 'add' => array( addablegroups ),
5177 * 'remove' => array( removablegroups ),
5178 * 'add-self' => array( addablegroups to self),
5179 * 'remove-self' => array( removable groups from self) )
5181 public static function changeableByGroup( $group ) {
5182 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
5191 if ( empty( $wgAddGroups[$group] ) ) {
5192 // Don't add anything to $groups
5193 } elseif ( $wgAddGroups[$group] === true ) {
5194 // You get everything
5195 $groups['add'] = self
::getAllGroups();
5196 } elseif ( is_array( $wgAddGroups[$group] ) ) {
5197 $groups['add'] = $wgAddGroups[$group];
5200 // Same thing for remove
5201 if ( empty( $wgRemoveGroups[$group] ) ) {
5203 } elseif ( $wgRemoveGroups[$group] === true ) {
5204 $groups['remove'] = self
::getAllGroups();
5205 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
5206 $groups['remove'] = $wgRemoveGroups[$group];
5209 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
5210 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
5211 foreach ( $wgGroupsAddToSelf as $key => $value ) {
5212 if ( is_int( $key ) ) {
5213 $wgGroupsAddToSelf['user'][] = $value;
5218 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
5219 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
5220 if ( is_int( $key ) ) {
5221 $wgGroupsRemoveFromSelf['user'][] = $value;
5226 // Now figure out what groups the user can add to him/herself
5227 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
5229 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
5230 // No idea WHY this would be used, but it's there
5231 $groups['add-self'] = self
::getAllGroups();
5232 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
5233 $groups['add-self'] = $wgGroupsAddToSelf[$group];
5236 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
5238 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
5239 $groups['remove-self'] = self
::getAllGroups();
5240 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
5241 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
5248 * Returns an array of groups that this user can add and remove
5249 * @return array Array( 'add' => array( addablegroups ),
5250 * 'remove' => array( removablegroups ),
5251 * 'add-self' => array( addablegroups to self),
5252 * 'remove-self' => array( removable groups from self) )
5254 public function changeableGroups() {
5255 if ( $this->isAllowed( 'userrights' ) ) {
5256 // This group gives the right to modify everything (reverse-
5257 // compatibility with old "userrights lets you change
5259 // Using array_merge to make the groups reindexed
5260 $all = array_merge( self
::getAllGroups() );
5269 // Okay, it's not so simple, we will have to go through the arrays
5276 $addergroups = $this->getEffectiveGroups();
5278 foreach ( $addergroups as $addergroup ) {
5279 $groups = array_merge_recursive(
5280 $groups, $this->changeableByGroup( $addergroup )
5282 $groups['add'] = array_unique( $groups['add'] );
5283 $groups['remove'] = array_unique( $groups['remove'] );
5284 $groups['add-self'] = array_unique( $groups['add-self'] );
5285 $groups['remove-self'] = array_unique( $groups['remove-self'] );
5291 * Deferred version of incEditCountImmediate()
5293 * This function, rather than incEditCountImmediate(), should be used for
5294 * most cases as it avoids potential deadlocks caused by concurrent editing.
5296 public function incEditCount() {
5297 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle(
5299 $this->incEditCountImmediate();
5306 * Increment the user's edit-count field.
5307 * Will have no effect for anonymous users.
5310 public function incEditCountImmediate() {
5311 if ( $this->isAnon() ) {
5315 $dbw = wfGetDB( DB_MASTER
);
5316 // No rows will be "affected" if user_editcount is NULL
5319 [ 'user_editcount=user_editcount+1' ],
5320 [ 'user_id' => $this->getId(), 'user_editcount IS NOT NULL' ],
5323 // Lazy initialization check...
5324 if ( $dbw->affectedRows() == 0 ) {
5325 // Now here's a goddamn hack...
5326 $dbr = wfGetDB( DB_REPLICA
);
5327 if ( $dbr !== $dbw ) {
5328 // If we actually have a replica DB server, the count is
5329 // at least one behind because the current transaction
5330 // has not been committed and replicated.
5331 $this->mEditCount
= $this->initEditCount( 1 );
5333 // But if DB_REPLICA is selecting the master, then the
5334 // count we just read includes the revision that was
5335 // just added in the working transaction.
5336 $this->mEditCount
= $this->initEditCount();
5339 if ( $this->mEditCount
=== null ) {
5340 $this->getEditCount();
5341 $dbr = wfGetDB( DB_REPLICA
);
5342 $this->mEditCount +
= ( $dbr !== $dbw ) ?
1 : 0;
5344 $this->mEditCount++
;
5347 // Edit count in user cache too
5348 $this->invalidateCache();
5352 * Initialize user_editcount from data out of the revision table
5354 * @param int $add Edits to add to the count from the revision table
5355 * @return int Number of edits
5357 protected function initEditCount( $add = 0 ) {
5358 // Pull from a replica DB to be less cruel to servers
5359 // Accuracy isn't the point anyway here
5360 $dbr = wfGetDB( DB_REPLICA
);
5361 $actorWhere = ActorMigration
::newMigration()->getWhere( $dbr, 'rev_user', $this );
5362 $count = (int)$dbr->selectField(
5363 [ 'revision' ] +
$actorWhere['tables'],
5365 [ $actorWhere['conds'] ],
5368 $actorWhere['joins']
5370 $count = $count +
$add;
5372 $dbw = wfGetDB( DB_MASTER
);
5375 [ 'user_editcount' => $count ],
5376 [ 'user_id' => $this->getId() ],
5384 * Get the description of a given right
5387 * @param string $right Right to query
5388 * @return string Localized description of the right
5390 public static function getRightDescription( $right ) {
5391 $key = "right-$right";
5392 $msg = wfMessage( $key );
5393 return $msg->isDisabled() ?
$right : $msg->text();
5397 * Get the name of a given grant
5400 * @param string $grant Grant to query
5401 * @return string Localized name of the grant
5403 public static function getGrantName( $grant ) {
5404 $key = "grant-$grant";
5405 $msg = wfMessage( $key );
5406 return $msg->isDisabled() ?
$grant : $msg->text();
5410 * Add a newuser log entry for this user.
5411 * Before 1.19 the return value was always true.
5413 * @deprecated since 1.27, AuthManager handles logging
5414 * @param string|bool $action Account creation type.
5415 * - String, one of the following values:
5416 * - 'create' for an anonymous user creating an account for himself.
5417 * This will force the action's performer to be the created user itself,
5418 * no matter the value of $wgUser
5419 * - 'create2' for a logged in user creating an account for someone else
5420 * - 'byemail' when the created user will receive its password by e-mail
5421 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
5422 * - Boolean means whether the account was created by e-mail (deprecated):
5423 * - true will be converted to 'byemail'
5424 * - false will be converted to 'create' if this object is the same as
5425 * $wgUser and to 'create2' otherwise
5426 * @param string $reason User supplied reason
5429 public function addNewUserLogEntry( $action = false, $reason = '' ) {
5430 return true; // disabled
5434 * Add an autocreate newuser log entry for this user
5435 * Used by things like CentralAuth and perhaps other authplugins.
5436 * Consider calling addNewUserLogEntry() directly instead.
5438 * @deprecated since 1.27, AuthManager handles logging
5441 public function addNewUserLogEntryAutoCreate() {
5442 $this->addNewUserLogEntry( 'autocreate' );
5448 * Load the user options either from cache, the database or an array
5450 * @param array|null $data Rows for the current user out of the user_properties table
5452 protected function loadOptions( $data = null ) {
5457 if ( $this->mOptionsLoaded
) {
5461 $this->mOptions
= self
::getDefaultOptions();
5463 if ( !$this->getId() ) {
5464 // For unlogged-in users, load language/variant options from request.
5465 // There's no need to do it for logged-in users: they can set preferences,
5466 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5467 // so don't override user's choice (especially when the user chooses site default).
5468 $variant = $wgContLang->getDefaultVariant();
5469 $this->mOptions
['variant'] = $variant;
5470 $this->mOptions
['language'] = $variant;
5471 $this->mOptionsLoaded
= true;
5475 // Maybe load from the object
5476 if ( !is_null( $this->mOptionOverrides
) ) {
5477 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5478 foreach ( $this->mOptionOverrides
as $key => $value ) {
5479 $this->mOptions
[$key] = $value;
5482 if ( !is_array( $data ) ) {
5483 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5484 // Load from database
5485 $dbr = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
5486 ?
wfGetDB( DB_MASTER
)
5487 : wfGetDB( DB_REPLICA
);
5489 $res = $dbr->select(
5491 [ 'up_property', 'up_value' ],
5492 [ 'up_user' => $this->getId() ],
5496 $this->mOptionOverrides
= [];
5498 foreach ( $res as $row ) {
5499 // Convert '0' to 0. PHP's boolean conversion considers them both
5500 // false, but e.g. JavaScript considers the former as true.
5501 // @todo: T54542 Somehow determine the desired type (string/int/bool)
5502 // and convert all values here.
5503 if ( $row->up_value
=== '0' ) {
5506 $data[$row->up_property
] = $row->up_value
;
5510 // Convert the email blacklist from a new line delimited string
5511 // to an array of ids.
5512 if ( isset( $data['email-blacklist'] ) && $data['email-blacklist'] ) {
5513 $data['email-blacklist'] = array_map( 'intval', explode( "\n", $data['email-blacklist'] ) );
5516 foreach ( $data as $property => $value ) {
5517 $this->mOptionOverrides
[$property] = $value;
5518 $this->mOptions
[$property] = $value;
5522 // Replace deprecated language codes
5523 $this->mOptions
['language'] = LanguageCode
::replaceDeprecatedCodes(
5524 $this->mOptions
['language']
5527 $this->mOptionsLoaded
= true;
5529 Hooks
::run( 'UserLoadOptions', [ $this, &$this->mOptions
] );
5533 * Saves the non-default options for this user, as previously set e.g. via
5534 * setOption(), in the database's "user_properties" (preferences) table.
5535 * Usually used via saveSettings().
5537 protected function saveOptions() {
5538 $this->loadOptions();
5540 // Not using getOptions(), to keep hidden preferences in database
5541 $saveOptions = $this->mOptions
;
5543 // Convert usernames to ids.
5544 if ( isset( $this->mOptions
['email-blacklist'] ) ) {
5545 if ( $this->mOptions
['email-blacklist'] ) {
5546 $value = $this->mOptions
['email-blacklist'];
5547 // Email Blacklist may be an array of ids or a string of new line
5548 // delimnated user names.
5549 if ( is_array( $value ) ) {
5550 $ids = array_filter( $value, 'is_numeric' );
5552 $lookup = CentralIdLookup
::factory();
5553 $ids = $lookup->centralIdsFromNames( explode( "\n", $value ), $this );
5555 $this->mOptions
['email-blacklist'] = $ids;
5556 $saveOptions['email-blacklist'] = implode( "\n", $this->mOptions
['email-blacklist'] );
5558 // If the blacklist is empty, set it to null rather than an empty string.
5559 $this->mOptions
['email-blacklist'] = null;
5563 // Allow hooks to abort, for instance to save to a global profile.
5564 // Reset options to default state before saving.
5565 if ( !Hooks
::run( 'UserSaveOptions', [ $this, &$saveOptions ] ) ) {
5569 $userId = $this->getId();
5571 $insert_rows = []; // all the new preference rows
5572 foreach ( $saveOptions as $key => $value ) {
5573 // Don't bother storing default values
5574 $defaultOption = self
::getDefaultOption( $key );
5575 if ( ( $defaultOption === null && $value !== false && $value !== null )
5576 ||
$value != $defaultOption
5579 'up_user' => $userId,
5580 'up_property' => $key,
5581 'up_value' => $value,
5586 $dbw = wfGetDB( DB_MASTER
);
5588 $res = $dbw->select( 'user_properties',
5589 [ 'up_property', 'up_value' ], [ 'up_user' => $userId ], __METHOD__
);
5591 // Find prior rows that need to be removed or updated. These rows will
5592 // all be deleted (the latter so that INSERT IGNORE applies the new values).
5594 foreach ( $res as $row ) {
5595 if ( !isset( $saveOptions[$row->up_property
] )
5596 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
5598 $keysDelete[] = $row->up_property
;
5602 if ( count( $keysDelete ) ) {
5603 // Do the DELETE by PRIMARY KEY for prior rows.
5604 // In the past a very large portion of calls to this function are for setting
5605 // 'rememberpassword' for new accounts (a preference that has since been removed).
5606 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5607 // caused gap locks on [max user ID,+infinity) which caused high contention since
5608 // updates would pile up on each other as they are for higher (newer) user IDs.
5609 // It might not be necessary these days, but it shouldn't hurt either.
5610 $dbw->delete( 'user_properties',
5611 [ 'up_user' => $userId, 'up_property' => $keysDelete ], __METHOD__
);
5613 // Insert the new preference rows
5614 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, [ 'IGNORE' ] );
5618 * Return the list of user fields that should be selected to create
5619 * a new user object.
5620 * @deprecated since 1.31, use self::getQueryInfo() instead.
5623 public static function selectFields() {
5624 wfDeprecated( __METHOD__
, '1.31' );
5632 'user_email_authenticated',
5634 'user_email_token_expires',
5635 'user_registration',
5641 * Return the tables, fields, and join conditions to be selected to create
5642 * a new user object.
5644 * @return array With three keys:
5645 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
5646 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
5647 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
5649 public static function getQueryInfo() {
5650 global $wgActorTableSchemaMigrationStage;
5653 'tables' => [ 'user' ],
5661 'user_email_authenticated',
5663 'user_email_token_expires',
5664 'user_registration',
5669 if ( $wgActorTableSchemaMigrationStage > MIGRATION_OLD
) {
5670 $ret['tables']['user_actor'] = 'actor';
5671 $ret['fields'][] = 'user_actor.actor_id';
5672 $ret['joins']['user_actor'] = [
5673 $wgActorTableSchemaMigrationStage === MIGRATION_NEW ?
'JOIN' : 'LEFT JOIN',
5674 [ 'user_actor.actor_user = user_id' ]
5681 * Factory function for fatal permission-denied errors
5684 * @param string $permission User right required
5687 static function newFatalPermissionDeniedStatus( $permission ) {
5691 foreach ( self
::getGroupsWithPermission( $permission ) as $group ) {
5692 $groups[] = UserGroupMembership
::getLink( $group, RequestContext
::getMain(), 'wiki' );
5696 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5698 return Status
::newFatal( 'badaccess-group0' );
5703 * Get a new instance of this user that was loaded from the master via a locking read
5705 * Use this instead of the main context User when updating that user. This avoids races
5706 * where that user was loaded from a replica DB or even the master but without proper locks.
5708 * @return User|null Returns null if the user was not found in the DB
5711 public function getInstanceForUpdate() {
5712 if ( !$this->getId() ) {
5713 return null; // anon
5716 $user = self
::newFromId( $this->getId() );
5717 if ( !$user->loadFromId( self
::READ_EXCLUSIVE
) ) {
5725 * Checks if two user objects point to the same user.
5727 * @since 1.25 ; takes a UserIdentity instead of a User since 1.32
5728 * @param UserIdentity $user
5731 public function equals( UserIdentity
$user ) {
5732 // XXX it's not clear whether central ID providers are supposed to obey this
5733 return $this->getName() === $user->getName();