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
;
36 * String Some punctuation to prevent editing from broken text-mangling proxies.
37 * @deprecated since 1.27, use \MediaWiki\Session\Token::SUFFIX
40 define( 'EDIT_TOKEN_SUFFIX', Token
::SUFFIX
);
43 * The User object encapsulates all of the user-specific settings (user_id,
44 * name, rights, email address, options, last login time). Client
45 * classes use the getXXX() functions to access these fields. These functions
46 * do all the work of determining whether the user is logged in,
47 * whether the requested option can be satisfied from cookies or
48 * whether a database query is needed. Most of the settings needed
49 * for rendering normal pages are set in the cookie to minimize use
52 class User
implements IDBAccessObject
, UserIdentity
{
54 * @const int Number of characters in user_token field.
56 const TOKEN_LENGTH
= 32;
59 * @const string An invalid value for user_token
61 const INVALID_TOKEN
= '*** INVALID ***';
64 * Global constant made accessible as class constants so that autoloader
66 * @deprecated since 1.27, use \MediaWiki\Session\Token::SUFFIX
68 const EDIT_TOKEN_SUFFIX
= EDIT_TOKEN_SUFFIX
;
71 * @const int Serialized record version.
76 * Exclude user options that are set to their default value.
79 const GETOPTIONS_EXCLUDE_DEFAULTS
= 1;
84 const CHECK_USER_RIGHTS
= true;
89 const IGNORE_USER_RIGHTS
= false;
92 * Array of Strings List of member variables which are saved to the
93 * shared cache (memcached). Any operation which changes the
94 * corresponding database fields must call a cache-clearing function.
97 protected static $mCacheVars = [
105 'mEmailAuthenticated',
107 'mEmailTokenExpires',
112 // user_properties table
117 * Array of Strings Core rights.
118 * Each of these should have a corresponding message of the form
122 protected static $mCoreRights = [
165 'move-categorypages',
166 'move-rootuserpages',
170 'override-export-depth',
192 'userrights-interwiki',
200 * String Cached results of getAllRights()
202 protected static $mAllRights = false;
204 /** Cache variables */
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 * - 'session' log in from session if possible
256 * Use the User::newFrom*() family of functions to set this.
261 * Lazy-initialized variables, invalidated with clearInstanceCache
265 protected $mDatePreference;
273 protected $mBlockreason;
275 protected $mEffectiveGroups;
277 protected $mImplicitGroups;
279 protected $mFormerGroups;
281 protected $mGlobalBlock;
289 /** @var WebRequest */
296 protected $mAllowUsertalk;
299 private $mBlockedFromCreateAccount = false;
301 /** @var int User::READ_* constant bitfield used to load data */
302 protected $queryFlagsUsed = self
::READ_NORMAL
;
304 public static $idCacheByName = [];
307 * Lightweight constructor for an anonymous user.
308 * Use the User::newFrom* factory functions for other kinds of users.
312 * @see newFromConfirmationCode()
313 * @see newFromSession()
316 public function __construct() {
317 $this->clearInstanceCache( 'defaults' );
323 public function __toString() {
324 return (string)$this->getName();
328 * Test if it's safe to load this User object.
330 * You should typically check this before using $wgUser or
331 * RequestContext::getUser in a method that might be called before the
332 * system has been fully initialized. If the object is unsafe, you should
333 * use an anonymous user:
335 * $user = $wgUser->isSafeToLoad() ? $wgUser : new User;
341 public function isSafeToLoad() {
342 global $wgFullyInitialised;
344 // The user is safe to load if:
345 // * MW_NO_SESSION is undefined AND $wgFullyInitialised is true (safe to use session data)
346 // * mLoadedItems === true (already loaded)
347 // * mFrom !== 'session' (sessions not involved at all)
349 return ( !defined( 'MW_NO_SESSION' ) && $wgFullyInitialised ) ||
350 $this->mLoadedItems
=== true ||
$this->mFrom
!== 'session';
354 * Load the user table data for this object from the source given by mFrom.
356 * @param int $flags User::READ_* constant bitfield
358 public function load( $flags = self
::READ_NORMAL
) {
359 global $wgFullyInitialised;
361 if ( $this->mLoadedItems
=== true ) {
365 // Set it now to avoid infinite recursion in accessors
366 $oldLoadedItems = $this->mLoadedItems
;
367 $this->mLoadedItems
= true;
368 $this->queryFlagsUsed
= $flags;
370 // If this is called too early, things are likely to break.
371 if ( !$wgFullyInitialised && $this->mFrom
=== 'session' ) {
372 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
373 ->warning( 'User::loadFromSession called before the end of Setup.php', [
374 'exception' => new Exception( 'User::loadFromSession called before the end of Setup.php' ),
376 $this->loadDefaults();
377 $this->mLoadedItems
= $oldLoadedItems;
381 switch ( $this->mFrom
) {
383 $this->loadDefaults();
386 // Make sure this thread sees its own changes
387 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
388 if ( $lb->hasOrMadeRecentMasterChanges() ) {
389 $flags |
= self
::READ_LATEST
;
390 $this->queryFlagsUsed
= $flags;
393 $this->mId
= self
::idFromName( $this->mName
, $flags );
395 // Nonexistent user placeholder object
396 $this->loadDefaults( $this->mName
);
398 $this->loadFromId( $flags );
402 $this->loadFromId( $flags );
405 if ( !$this->loadFromSession() ) {
406 // Loading from session failed. Load defaults.
407 $this->loadDefaults();
409 Hooks
::run( 'UserLoadAfterLoadFromSession', [ $this ] );
412 throw new UnexpectedValueException(
413 "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
418 * Load user table data, given mId has already been set.
419 * @param int $flags User::READ_* constant bitfield
420 * @return bool False if the ID does not exist, true otherwise
422 public function loadFromId( $flags = self
::READ_NORMAL
) {
423 if ( $this->mId
== 0 ) {
424 // Anonymous users are not in the database (don't need cache)
425 $this->loadDefaults();
429 // Try cache (unless this needs data from the master DB).
430 // NOTE: if this thread called saveSettings(), the cache was cleared.
431 $latest = DBAccessObjectUtils
::hasFlags( $flags, self
::READ_LATEST
);
433 if ( !$this->loadFromDatabase( $flags ) ) {
434 // Can't load from ID
438 $this->loadFromCache();
441 $this->mLoadedItems
= true;
442 $this->queryFlagsUsed
= $flags;
449 * @param string $wikiId
452 public static function purge( $wikiId, $userId ) {
453 $cache = ObjectCache
::getMainWANInstance();
454 $key = $cache->makeGlobalKey( 'user', 'id', $wikiId, $userId );
455 $cache->delete( $key );
460 * @param WANObjectCache $cache
463 protected function getCacheKey( WANObjectCache
$cache ) {
464 return $cache->makeGlobalKey( 'user', 'id', wfWikiID(), $this->mId
);
468 * @param WANObjectCache $cache
472 public function getMutableCacheKeys( WANObjectCache
$cache ) {
473 $id = $this->getId();
475 return $id ?
[ $this->getCacheKey( $cache ) ] : [];
479 * Load user data from shared cache, given mId has already been set.
484 protected function loadFromCache() {
485 $cache = ObjectCache
::getMainWANInstance();
486 $data = $cache->getWithSetCallback(
487 $this->getCacheKey( $cache ),
489 function ( $oldValue, &$ttl, array &$setOpts ) use ( $cache ) {
490 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
491 wfDebug( "User: cache miss for user {$this->mId}\n" );
493 $this->loadFromDatabase( self
::READ_NORMAL
);
495 $this->loadOptions();
498 foreach ( self
::$mCacheVars as $name ) {
499 $data[$name] = $this->$name;
502 $ttl = $cache->adaptiveTTL( wfTimestamp( TS_UNIX
, $this->mTouched
), $ttl );
504 // if a user group membership is about to expire, the cache needs to
505 // expire at that time (T163691)
506 foreach ( $this->mGroupMemberships
as $ugm ) {
507 if ( $ugm->getExpiry() ) {
508 $secondsUntilExpiry = wfTimestamp( TS_UNIX
, $ugm->getExpiry() ) - time();
509 if ( $secondsUntilExpiry > 0 && $secondsUntilExpiry < $ttl ) {
510 $ttl = $secondsUntilExpiry;
517 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'version' => self
::VERSION
]
520 // Restore from cache
521 foreach ( self
::$mCacheVars as $name ) {
522 $this->$name = $data[$name];
528 /** @name newFrom*() static factory methods */
532 * Static factory method for creation from username.
534 * This is slightly less efficient than newFromId(), so use newFromId() if
535 * you have both an ID and a name handy.
537 * @param string $name Username, validated by Title::newFromText()
538 * @param string|bool $validate Validate username. Takes the same parameters as
539 * User::getCanonicalName(), except that true is accepted as an alias
540 * for 'valid', for BC.
542 * @return User|bool User object, or false if the username is invalid
543 * (e.g. if it contains illegal characters or is an IP address). If the
544 * username is not present in the database, the result will be a user object
545 * with a name, zero user ID and default settings.
547 public static function newFromName( $name, $validate = 'valid' ) {
548 if ( $validate === true ) {
551 $name = self
::getCanonicalName( $name, $validate );
552 if ( $name === false ) {
555 // Create unloaded user object
559 $u->setItemLoaded( 'name' );
565 * Static factory method for creation from a given user ID.
567 * @param int $id Valid user ID
568 * @return User The corresponding User object
570 public static function newFromId( $id ) {
574 $u->setItemLoaded( 'id' );
579 * Factory method to fetch whichever user has a given email confirmation code.
580 * This code is generated when an account is created or its e-mail address
583 * If the code is invalid or has expired, returns NULL.
585 * @param string $code Confirmation code
586 * @param int $flags User::READ_* bitfield
589 public static function newFromConfirmationCode( $code, $flags = 0 ) {
590 $db = ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
591 ?
wfGetDB( DB_MASTER
)
592 : wfGetDB( DB_REPLICA
);
594 $id = $db->selectField(
598 'user_email_token' => md5( $code ),
599 'user_email_token_expires > ' . $db->addQuotes( $db->timestamp() ),
603 return $id ? self
::newFromId( $id ) : null;
607 * Create a new user object using data from session. If the login
608 * credentials are invalid, the result is an anonymous user.
610 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
613 public static function newFromSession( WebRequest
$request = null ) {
615 $user->mFrom
= 'session';
616 $user->mRequest
= $request;
621 * Create a new user object from a user row.
622 * The row should have the following fields from the user table in it:
623 * - either user_name or user_id to load further data if needed (or both)
625 * - all other fields (email, etc.)
626 * It is useless to provide the remaining fields if either user_id,
627 * user_name and user_real_name are not provided because the whole row
628 * will be loaded once more from the database when accessing them.
630 * @param stdClass $row A row from the user table
631 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
634 public static function newFromRow( $row, $data = null ) {
636 $user->loadFromRow( $row, $data );
641 * Static factory method for creation of a "system" user from username.
643 * A "system" user is an account that's used to attribute logged actions
644 * taken by MediaWiki itself, as opposed to a bot or human user. Examples
645 * might include the 'Maintenance script' or 'Conversion script' accounts
646 * used by various scripts in the maintenance/ directory or accounts such
647 * as 'MediaWiki message delivery' used by the MassMessage extension.
649 * This can optionally create the user if it doesn't exist, and "steal" the
650 * account if it does exist.
652 * "Stealing" an existing user is intended to make it impossible for normal
653 * authentication processes to use the account, effectively disabling the
654 * account for normal use:
655 * - Email is invalidated, to prevent account recovery by emailing a
656 * temporary password and to disassociate the account from the existing
658 * - The token is set to a magic invalid value, to kill existing sessions
659 * and to prevent $this->setToken() calls from resetting the token to a
661 * - SessionManager is instructed to prevent new sessions for the user, to
662 * do things like deauthorizing OAuth consumers.
663 * - AuthManager is instructed to revoke access, to invalidate or remove
664 * passwords and other credentials.
666 * @param string $name Username
667 * @param array $options Options are:
668 * - validate: As for User::getCanonicalName(), default 'valid'
669 * - create: Whether to create the user if it doesn't already exist, default true
670 * - steal: Whether to "disable" the account for normal use if it already
671 * exists, default false
675 public static function newSystemUser( $name, $options = [] ) {
677 'validate' => 'valid',
682 $name = self
::getCanonicalName( $name, $options['validate'] );
683 if ( $name === false ) {
687 $dbr = wfGetDB( DB_REPLICA
);
688 $userQuery = self
::getQueryInfo();
689 $row = $dbr->selectRow(
690 $userQuery['tables'],
691 $userQuery['fields'],
692 [ 'user_name' => $name ],
698 // Try the master database...
699 $dbw = wfGetDB( DB_MASTER
);
700 $row = $dbw->selectRow(
701 $userQuery['tables'],
702 $userQuery['fields'],
703 [ 'user_name' => $name ],
711 // No user. Create it?
712 return $options['create']
713 ? self
::createNew( $name, [ 'token' => self
::INVALID_TOKEN
] )
717 $user = self
::newFromRow( $row );
719 // A user is considered to exist as a non-system user if it can
720 // authenticate, or has an email set, or has a non-invalid token.
721 if ( $user->mEmail ||
$user->mToken
!== self
::INVALID_TOKEN ||
722 AuthManager
::singleton()->userCanAuthenticate( $name )
724 // User exists. Steal it?
725 if ( !$options['steal'] ) {
729 AuthManager
::singleton()->revokeAccessForUser( $name );
731 $user->invalidateEmail();
732 $user->mToken
= self
::INVALID_TOKEN
;
733 $user->saveSettings();
734 SessionManager
::singleton()->preventSessionsForUser( $user->getName() );
743 * Get the username corresponding to a given user ID
744 * @param int $id User ID
745 * @return string|bool The corresponding username
747 public static function whoIs( $id ) {
748 return UserCache
::singleton()->getProp( $id, 'name' );
752 * Get the real name of a user given their user ID
754 * @param int $id User ID
755 * @return string|bool The corresponding user's real name
757 public static function whoIsReal( $id ) {
758 return UserCache
::singleton()->getProp( $id, 'real_name' );
762 * Get database id given a user name
763 * @param string $name Username
764 * @param int $flags User::READ_* constant bitfield
765 * @return int|null The corresponding user's ID, or null if user is nonexistent
767 public static function idFromName( $name, $flags = self
::READ_NORMAL
) {
768 $nt = Title
::makeTitleSafe( NS_USER
, $name );
769 if ( is_null( $nt ) ) {
774 if ( !( $flags & self
::READ_LATEST
) && isset( self
::$idCacheByName[$name] ) ) {
775 return self
::$idCacheByName[$name];
778 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
779 $db = wfGetDB( $index );
784 [ 'user_name' => $nt->getText() ],
789 if ( $s === false ) {
792 $result = $s->user_id
;
795 self
::$idCacheByName[$name] = $result;
797 if ( count( self
::$idCacheByName ) > 1000 ) {
798 self
::$idCacheByName = [];
805 * Reset the cache used in idFromName(). For use in tests.
807 public static function resetIdByNameCache() {
808 self
::$idCacheByName = [];
812 * Does the string match an anonymous IP address?
814 * This function exists for username validation, in order to reject
815 * usernames which are similar in form to IP addresses. Strings such
816 * as 300.300.300.300 will return true because it looks like an IP
817 * address, despite not being strictly valid.
819 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
820 * address because the usemod software would "cloak" anonymous IP
821 * addresses like this, if we allowed accounts like this to be created
822 * new users could get the old edits of these anonymous users.
824 * @param string $name Name to match
827 public static function isIP( $name ) {
828 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
829 || IP
::isIPv6( $name );
833 * Is the user an IP range?
838 public function isIPRange() {
839 return IP
::isValidRange( $this->mName
);
843 * Is the input a valid username?
845 * Checks if the input is a valid username, we don't want an empty string,
846 * an IP address, anything that contains slashes (would mess up subpages),
847 * is longer than the maximum allowed username size or doesn't begin with
850 * @param string $name Name to match
853 public static function isValidUserName( $name ) {
854 global $wgContLang, $wgMaxNameChars;
857 || self
::isIP( $name )
858 ||
strpos( $name, '/' ) !== false
859 ||
strlen( $name ) > $wgMaxNameChars
860 ||
$name != $wgContLang->ucfirst( $name )
865 // Ensure that the name can't be misresolved as a different title,
866 // such as with extra namespace keys at the start.
867 $parsed = Title
::newFromText( $name );
868 if ( is_null( $parsed )
869 ||
$parsed->getNamespace()
870 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
874 // Check an additional blacklist of troublemaker characters.
875 // Should these be merged into the title char list?
876 $unicodeBlacklist = '/[' .
877 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
878 '\x{00a0}' . # non-breaking space
879 '\x{2000}-\x{200f}' . # various whitespace
880 '\x{2028}-\x{202f}' . # breaks and control chars
881 '\x{3000}' . # ideographic space
882 '\x{e000}-\x{f8ff}' . # private use
884 if ( preg_match( $unicodeBlacklist, $name ) ) {
892 * Usernames which fail to pass this function will be blocked
893 * from user login and new account registrations, but may be used
894 * internally by batch processes.
896 * If an account already exists in this form, login will be blocked
897 * by a failure to pass this function.
899 * @param string $name Name to match
902 public static function isUsableName( $name ) {
903 global $wgReservedUsernames;
904 // Must be a valid username, obviously ;)
905 if ( !self
::isValidUserName( $name ) ) {
909 static $reservedUsernames = false;
910 if ( !$reservedUsernames ) {
911 $reservedUsernames = $wgReservedUsernames;
912 Hooks
::run( 'UserGetReservedNames', [ &$reservedUsernames ] );
915 // Certain names may be reserved for batch processes.
916 foreach ( $reservedUsernames as $reserved ) {
917 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
918 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
920 if ( $reserved == $name ) {
928 * Return the users who are members of the given group(s). In case of multiple groups,
929 * users who are members of at least one of them are returned.
931 * @param string|array $groups A single group name or an array of group names
932 * @param int $limit Max number of users to return. The actual limit will never exceed 5000
933 * records; larger values are ignored.
934 * @param int $after ID the user to start after
935 * @return UserArrayFromResult
937 public static function findUsersByGroup( $groups, $limit = 5000, $after = null ) {
938 if ( $groups === [] ) {
939 return UserArrayFromResult
::newFromIDs( [] );
942 $groups = array_unique( (array)$groups );
943 $limit = min( 5000, $limit );
945 $conds = [ 'ug_group' => $groups ];
946 if ( $after !== null ) {
947 $conds[] = 'ug_user > ' . (int)$after;
950 $dbr = wfGetDB( DB_REPLICA
);
951 $ids = $dbr->selectFieldValues(
958 'ORDER BY' => 'ug_user',
962 return UserArray
::newFromIDs( $ids );
966 * Usernames which fail to pass this function will be blocked
967 * from new account registrations, but may be used internally
968 * either by batch processes or by user accounts which have
969 * already been created.
971 * Additional blacklisting may be added here rather than in
972 * isValidUserName() to avoid disrupting existing accounts.
974 * @param string $name String to match
977 public static function isCreatableName( $name ) {
978 global $wgInvalidUsernameCharacters;
980 // Ensure that the username isn't longer than 235 bytes, so that
981 // (at least for the builtin skins) user javascript and css files
982 // will work. (T25080)
983 if ( strlen( $name ) > 235 ) {
984 wfDebugLog( 'username', __METHOD__
.
985 ": '$name' invalid due to length" );
989 // Preg yells if you try to give it an empty string
990 if ( $wgInvalidUsernameCharacters !== '' ) {
991 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
992 wfDebugLog( 'username', __METHOD__
.
993 ": '$name' invalid due to wgInvalidUsernameCharacters" );
998 return self
::isUsableName( $name );
1002 * Is the input a valid password for this user?
1004 * @param string $password Desired password
1007 public function isValidPassword( $password ) {
1008 // simple boolean wrapper for getPasswordValidity
1009 return $this->getPasswordValidity( $password ) === true;
1013 * Given unvalidated password input, return error message on failure.
1015 * @param string $password Desired password
1016 * @return bool|string|array True on success, string or array of error message on failure
1018 public function getPasswordValidity( $password ) {
1019 $result = $this->checkPasswordValidity( $password );
1020 if ( $result->isGood() ) {
1024 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
1025 $messages[] = $error['message'];
1027 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
1028 $messages[] = $warning['message'];
1030 if ( count( $messages ) === 1 ) {
1031 return $messages[0];
1038 * Check if this is a valid password for this user
1040 * Create a Status object based on the password's validity.
1041 * The Status should be set to fatal if the user should not
1042 * be allowed to log in, and should have any errors that
1043 * would block changing the password.
1045 * If the return value of this is not OK, the password
1046 * should not be checked. If the return value is not Good,
1047 * the password can be checked, but the user should not be
1048 * able to set their password to this.
1050 * @param string $password Desired password
1054 public function checkPasswordValidity( $password ) {
1055 global $wgPasswordPolicy;
1057 $upp = new UserPasswordPolicy(
1058 $wgPasswordPolicy['policies'],
1059 $wgPasswordPolicy['checks']
1062 $status = Status
::newGood();
1063 $result = false; // init $result to false for the internal checks
1065 if ( !Hooks
::run( 'isValidPassword', [ $password, &$result, $this ] ) ) {
1066 $status->error( $result );
1070 if ( $result === false ) {
1071 $status->merge( $upp->checkUserPassword( $this, $password ) );
1073 } elseif ( $result === true ) {
1076 $status->error( $result );
1077 return $status; // the isValidPassword hook set a string $result and returned true
1082 * Given unvalidated user input, return a canonical username, or false if
1083 * the username is invalid.
1084 * @param string $name User input
1085 * @param string|bool $validate Type of validation to use:
1086 * - false No validation
1087 * - 'valid' Valid for batch processes
1088 * - 'usable' Valid for batch processes and login
1089 * - 'creatable' Valid for batch processes, login and account creation
1091 * @throws InvalidArgumentException
1092 * @return bool|string
1094 public static function getCanonicalName( $name, $validate = 'valid' ) {
1095 // Force usernames to capital
1097 $name = $wgContLang->ucfirst( $name );
1099 # Reject names containing '#'; these will be cleaned up
1100 # with title normalisation, but then it's too late to
1102 if ( strpos( $name, '#' ) !== false ) {
1106 // Clean up name according to title rules,
1107 // but only when validation is requested (T14654)
1108 $t = ( $validate !== false ) ?
1109 Title
::newFromText( $name, NS_USER
) : Title
::makeTitle( NS_USER
, $name );
1110 // Check for invalid titles
1111 if ( is_null( $t ) ||
$t->getNamespace() !== NS_USER ||
$t->isExternal() ) {
1115 // Reject various classes of invalid names
1116 $name = AuthManager
::callLegacyAuthPlugin(
1117 'getCanonicalName', [ $t->getText() ], $t->getText()
1120 switch ( $validate ) {
1124 if ( !self
::isValidUserName( $name ) ) {
1129 if ( !self
::isUsableName( $name ) ) {
1134 if ( !self
::isCreatableName( $name ) ) {
1139 throw new InvalidArgumentException(
1140 'Invalid parameter value for $validate in ' . __METHOD__
);
1146 * Return a random password.
1148 * @deprecated since 1.27, use PasswordFactory::generateRandomPasswordString()
1149 * @return string New random password
1151 public static function randomPassword() {
1152 global $wgMinimalPasswordLength;
1153 return PasswordFactory
::generateRandomPasswordString( $wgMinimalPasswordLength );
1157 * Set cached properties to default.
1159 * @note This no longer clears uncached lazy-initialised properties;
1160 * the constructor does that instead.
1162 * @param string|bool $name
1164 public function loadDefaults( $name = false ) {
1166 $this->mName
= $name;
1167 $this->mRealName
= '';
1169 $this->mOptionOverrides
= null;
1170 $this->mOptionsLoaded
= false;
1172 $loggedOut = $this->mRequest
&& !defined( 'MW_NO_SESSION' )
1173 ?
$this->mRequest
->getSession()->getLoggedOutTimestamp() : 0;
1174 if ( $loggedOut !== 0 ) {
1175 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1177 $this->mTouched
= '1'; # Allow any pages to be cached
1180 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1181 $this->mEmailAuthenticated
= null;
1182 $this->mEmailToken
= '';
1183 $this->mEmailTokenExpires
= null;
1184 $this->mRegistration
= wfTimestamp( TS_MW
);
1185 $this->mGroupMemberships
= [];
1187 Hooks
::run( 'UserLoadDefaults', [ $this, $name ] );
1191 * Return whether an item has been loaded.
1193 * @param string $item Item to check. Current possibilities:
1197 * @param string $all 'all' to check if the whole object has been loaded
1198 * or any other string to check if only the item is available (e.g.
1202 public function isItemLoaded( $item, $all = 'all' ) {
1203 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1204 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1208 * Set that an item has been loaded
1210 * @param string $item
1212 protected function setItemLoaded( $item ) {
1213 if ( is_array( $this->mLoadedItems
) ) {
1214 $this->mLoadedItems
[$item] = true;
1219 * Load user data from the session.
1221 * @return bool True if the user is logged in, false otherwise.
1223 private function loadFromSession() {
1226 Hooks
::run( 'UserLoadFromSession', [ $this, &$result ], '1.27' );
1227 if ( $result !== null ) {
1231 // MediaWiki\Session\Session already did the necessary authentication of the user
1232 // returned here, so just use it if applicable.
1233 $session = $this->getRequest()->getSession();
1234 $user = $session->getUser();
1235 if ( $user->isLoggedIn() ) {
1236 $this->loadFromUserObject( $user );
1238 // If this user is autoblocked, set a cookie to track the Block. This has to be done on
1239 // every session load, because an autoblocked editor might not edit again from the same
1240 // IP address after being blocked.
1241 $config = RequestContext
::getMain()->getConfig();
1242 if ( $config->get( 'CookieSetOnAutoblock' ) === true ) {
1243 $block = $this->getBlock();
1244 $shouldSetCookie = $this->getRequest()->getCookie( 'BlockID' ) === null
1246 && $block->getType() === Block
::TYPE_USER
1247 && $block->isAutoblocking();
1248 if ( $shouldSetCookie ) {
1249 wfDebug( __METHOD__
. ': User is autoblocked, setting cookie to track' );
1250 $block->setCookie( $this->getRequest()->response() );
1254 // Other code expects these to be set in the session, so set them.
1255 $session->set( 'wsUserID', $this->getId() );
1256 $session->set( 'wsUserName', $this->getName() );
1257 $session->set( 'wsToken', $this->getToken() );
1264 * Load user and user_group data from the database.
1265 * $this->mId must be set, this is how the user is identified.
1267 * @param int $flags User::READ_* constant bitfield
1268 * @return bool True if the user exists, false if the user is anonymous
1270 public function loadFromDatabase( $flags = self
::READ_LATEST
) {
1272 $this->mId
= intval( $this->mId
);
1274 if ( !$this->mId
) {
1275 // Anonymous users are not in the database
1276 $this->loadDefaults();
1280 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
1281 $db = wfGetDB( $index );
1283 $userQuery = self
::getQueryInfo();
1284 $s = $db->selectRow(
1285 $userQuery['tables'],
1286 $userQuery['fields'],
1287 [ 'user_id' => $this->mId
],
1293 $this->queryFlagsUsed
= $flags;
1294 Hooks
::run( 'UserLoadFromDatabase', [ $this, &$s ] );
1296 if ( $s !== false ) {
1297 // Initialise user table data
1298 $this->loadFromRow( $s );
1299 $this->mGroupMemberships
= null; // deferred
1300 $this->getEditCount(); // revalidation for nulls
1305 $this->loadDefaults();
1311 * Initialize this object from a row from the user table.
1313 * @param stdClass $row Row from the user table to load.
1314 * @param array $data Further user data to load into the object
1316 * user_groups Array of arrays or stdClass result rows out of the user_groups
1317 * table. Previously you were supposed to pass an array of strings
1318 * here, but we also need expiry info nowadays, so an array of
1319 * strings is ignored.
1320 * user_properties Array with properties out of the user_properties table
1322 protected function loadFromRow( $row, $data = null ) {
1325 $this->mGroupMemberships
= null; // deferred
1327 if ( isset( $row->user_name
) ) {
1328 $this->mName
= $row->user_name
;
1329 $this->mFrom
= 'name';
1330 $this->setItemLoaded( 'name' );
1335 if ( isset( $row->user_real_name
) ) {
1336 $this->mRealName
= $row->user_real_name
;
1337 $this->setItemLoaded( 'realname' );
1342 if ( isset( $row->user_id
) ) {
1343 $this->mId
= intval( $row->user_id
);
1344 $this->mFrom
= 'id';
1345 $this->setItemLoaded( 'id' );
1350 if ( isset( $row->user_id
) && isset( $row->user_name
) ) {
1351 self
::$idCacheByName[$row->user_name
] = $row->user_id
;
1354 if ( isset( $row->user_editcount
) ) {
1355 $this->mEditCount
= $row->user_editcount
;
1360 if ( isset( $row->user_touched
) ) {
1361 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1366 if ( isset( $row->user_token
) ) {
1367 // The definition for the column is binary(32), so trim the NULs
1368 // that appends. The previous definition was char(32), so trim
1370 $this->mToken
= rtrim( $row->user_token
, " \0" );
1371 if ( $this->mToken
=== '' ) {
1372 $this->mToken
= null;
1378 if ( isset( $row->user_email
) ) {
1379 $this->mEmail
= $row->user_email
;
1380 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1381 $this->mEmailToken
= $row->user_email_token
;
1382 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1383 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1389 $this->mLoadedItems
= true;
1392 if ( is_array( $data ) ) {
1393 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1394 if ( !count( $data['user_groups'] ) ) {
1395 $this->mGroupMemberships
= [];
1397 $firstGroup = reset( $data['user_groups'] );
1398 if ( is_array( $firstGroup ) ||
is_object( $firstGroup ) ) {
1399 $this->mGroupMemberships
= [];
1400 foreach ( $data['user_groups'] as $row ) {
1401 $ugm = UserGroupMembership
::newFromRow( (object)$row );
1402 $this->mGroupMemberships
[$ugm->getGroup()] = $ugm;
1407 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1408 $this->loadOptions( $data['user_properties'] );
1414 * Load the data for this user object from another user object.
1418 protected function loadFromUserObject( $user ) {
1420 foreach ( self
::$mCacheVars as $var ) {
1421 $this->$var = $user->$var;
1426 * Load the groups from the database if they aren't already loaded.
1428 private function loadGroups() {
1429 if ( is_null( $this->mGroupMemberships
) ) {
1430 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
1431 ?
wfGetDB( DB_MASTER
)
1432 : wfGetDB( DB_REPLICA
);
1433 $this->mGroupMemberships
= UserGroupMembership
::getMembershipsForUser(
1439 * Add the user to the group if he/she meets given criteria.
1441 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1442 * possible to remove manually via Special:UserRights. In such case it
1443 * will not be re-added automatically. The user will also not lose the
1444 * group if they no longer meet the criteria.
1446 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1448 * @return array Array of groups the user has been promoted to.
1450 * @see $wgAutopromoteOnce
1452 public function addAutopromoteOnceGroups( $event ) {
1453 global $wgAutopromoteOnceLogInRC;
1455 if ( wfReadOnly() ||
!$this->getId() ) {
1459 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1460 if ( !count( $toPromote ) ) {
1464 if ( !$this->checkAndSetTouched() ) {
1465 return []; // raced out (bug T48834)
1468 $oldGroups = $this->getGroups(); // previous groups
1469 $oldUGMs = $this->getGroupMemberships();
1470 foreach ( $toPromote as $group ) {
1471 $this->addGroup( $group );
1473 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1474 $newUGMs = $this->getGroupMemberships();
1476 // update groups in external authentication database
1477 Hooks
::run( 'UserGroupsChanged', [ $this, $toPromote, [], false, false, $oldUGMs, $newUGMs ] );
1478 AuthManager
::callLegacyAuthPlugin( 'updateExternalDBGroups', [ $this, $toPromote ] );
1480 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1481 $logEntry->setPerformer( $this );
1482 $logEntry->setTarget( $this->getUserPage() );
1483 $logEntry->setParameters( [
1484 '4::oldgroups' => $oldGroups,
1485 '5::newgroups' => $newGroups,
1487 $logid = $logEntry->insert();
1488 if ( $wgAutopromoteOnceLogInRC ) {
1489 $logEntry->publish( $logid );
1496 * Builds update conditions. Additional conditions may be added to $conditions to
1497 * protected against race conditions using a compare-and-set (CAS) mechanism
1498 * based on comparing $this->mTouched with the user_touched field.
1500 * @param Database $db
1501 * @param array $conditions WHERE conditions for use with Database::update
1502 * @return array WHERE conditions for use with Database::update
1504 protected function makeUpdateConditions( Database
$db, array $conditions ) {
1505 if ( $this->mTouched
) {
1506 // CAS check: only update if the row wasn't changed sicne it was loaded.
1507 $conditions['user_touched'] = $db->timestamp( $this->mTouched
);
1514 * Bump user_touched if it didn't change since this object was loaded
1516 * On success, the mTouched field is updated.
1517 * The user serialization cache is always cleared.
1519 * @return bool Whether user_touched was actually updated
1522 protected function checkAndSetTouched() {
1525 if ( !$this->mId
) {
1526 return false; // anon
1529 // Get a new user_touched that is higher than the old one
1530 $newTouched = $this->newTouchedTimestamp();
1532 $dbw = wfGetDB( DB_MASTER
);
1533 $dbw->update( 'user',
1534 [ 'user_touched' => $dbw->timestamp( $newTouched ) ],
1535 $this->makeUpdateConditions( $dbw, [
1536 'user_id' => $this->mId
,
1540 $success = ( $dbw->affectedRows() > 0 );
1543 $this->mTouched
= $newTouched;
1544 $this->clearSharedCache();
1546 // Clears on failure too since that is desired if the cache is stale
1547 $this->clearSharedCache( 'refresh' );
1554 * Clear various cached data stored in this object. The cache of the user table
1555 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1557 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1558 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1560 public function clearInstanceCache( $reloadFrom = false ) {
1561 $this->mNewtalk
= -1;
1562 $this->mDatePreference
= null;
1563 $this->mBlockedby
= -1; # Unset
1564 $this->mHash
= false;
1565 $this->mRights
= null;
1566 $this->mEffectiveGroups
= null;
1567 $this->mImplicitGroups
= null;
1568 $this->mGroupMemberships
= null;
1569 $this->mOptions
= null;
1570 $this->mOptionsLoaded
= false;
1571 $this->mEditCount
= null;
1573 if ( $reloadFrom ) {
1574 $this->mLoadedItems
= [];
1575 $this->mFrom
= $reloadFrom;
1580 * Combine the language default options with any site-specific options
1581 * and add the default language variants.
1583 * @return array Array of String options
1585 public static function getDefaultOptions() {
1586 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1588 static $defOpt = null;
1589 static $defOptLang = null;
1591 if ( $defOpt !== null && $defOptLang === $wgContLang->getCode() ) {
1592 // $wgContLang does not change (and should not change) mid-request,
1593 // but the unit tests change it anyway, and expect this method to
1594 // return values relevant to the current $wgContLang.
1598 $defOpt = $wgDefaultUserOptions;
1599 // Default language setting
1600 $defOptLang = $wgContLang->getCode();
1601 $defOpt['language'] = $defOptLang;
1602 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1603 $defOpt[$langCode == $wgContLang->getCode() ?
'variant' : "variant-$langCode"] = $langCode;
1606 // NOTE: don't use SearchEngineConfig::getSearchableNamespaces here,
1607 // since extensions may change the set of searchable namespaces depending
1608 // on user groups/permissions.
1609 foreach ( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
1610 $defOpt['searchNs' . $nsnum] = (bool)$val;
1612 $defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1614 Hooks
::run( 'UserGetDefaultOptions', [ &$defOpt ] );
1620 * Get a given default option value.
1622 * @param string $opt Name of option to retrieve
1623 * @return string Default option value
1625 public static function getDefaultOption( $opt ) {
1626 $defOpts = self
::getDefaultOptions();
1627 if ( isset( $defOpts[$opt] ) ) {
1628 return $defOpts[$opt];
1635 * Get blocking information
1636 * @param bool $bFromSlave Whether to check the replica DB first.
1637 * To improve performance, non-critical checks are done against replica DBs.
1638 * Check when actually saving should be done against master.
1640 private function getBlockedStatus( $bFromSlave = true ) {
1641 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff, $wgSoftBlockRanges;
1643 if ( -1 != $this->mBlockedby
) {
1647 wfDebug( __METHOD__
. ": checking...\n" );
1649 // Initialize data...
1650 // Otherwise something ends up stomping on $this->mBlockedby when
1651 // things get lazy-loaded later, causing false positive block hits
1652 // due to -1 !== 0. Probably session-related... Nothing should be
1653 // overwriting mBlockedby, surely?
1656 # We only need to worry about passing the IP address to the Block generator if the
1657 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1658 # know which IP address they're actually coming from
1660 if ( !$this->isAllowed( 'ipblock-exempt' ) ) {
1661 // $wgUser->getName() only works after the end of Setup.php. Until
1662 // then, assume it's a logged-out user.
1663 $globalUserName = $wgUser->isSafeToLoad()
1664 ?
$wgUser->getName()
1665 : IP
::sanitizeIP( $wgUser->getRequest()->getIP() );
1666 if ( $this->getName() === $globalUserName ) {
1667 $ip = $this->getRequest()->getIP();
1672 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1675 if ( !$block instanceof Block
) {
1676 $block = $this->getBlockFromCookieValue( $this->getRequest()->getCookie( 'BlockID' ) );
1680 if ( !$block instanceof Block
&& $ip !== null && !in_array( $ip, $wgProxyWhitelist ) ) {
1682 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1683 $block = new Block( [
1684 'byText' => wfMessage( 'proxyblocker' )->text(),
1685 'reason' => wfMessage( 'proxyblockreason' )->text(),
1687 'systemBlock' => 'proxy',
1689 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1690 $block = new Block( [
1691 'byText' => wfMessage( 'sorbs' )->text(),
1692 'reason' => wfMessage( 'sorbsreason' )->text(),
1694 'systemBlock' => 'dnsbl',
1699 // (T25343) Apply IP blocks to the contents of XFF headers, if enabled
1700 if ( !$block instanceof Block
1701 && $wgApplyIpBlocksToXff
1703 && !in_array( $ip, $wgProxyWhitelist )
1705 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1706 $xff = array_map( 'trim', explode( ',', $xff ) );
1707 $xff = array_diff( $xff, [ $ip ] );
1708 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1709 $block = Block
::chooseBlock( $xffblocks, $xff );
1710 if ( $block instanceof Block
) {
1711 # Mangle the reason to alert the user that the block
1712 # originated from matching the X-Forwarded-For header.
1713 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->text();
1717 if ( !$block instanceof Block
1720 && IP
::isInRanges( $ip, $wgSoftBlockRanges )
1722 $block = new Block( [
1724 'byText' => 'MediaWiki default',
1725 'reason' => wfMessage( 'softblockrangesreason', $ip )->text(),
1727 'systemBlock' => 'wgSoftBlockRanges',
1731 if ( $block instanceof Block
) {
1732 wfDebug( __METHOD__
. ": Found block.\n" );
1733 $this->mBlock
= $block;
1734 $this->mBlockedby
= $block->getByName();
1735 $this->mBlockreason
= $block->mReason
;
1736 $this->mHideName
= $block->mHideName
;
1737 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1739 $this->mBlockedby
= '';
1740 $this->mHideName
= 0;
1741 $this->mAllowUsertalk
= false;
1744 // Avoid PHP 7.1 warning of passing $this by reference
1747 Hooks
::run( 'GetBlockedStatus', [ &$user ] );
1751 * Try to load a Block from an ID given in a cookie value.
1752 * @param string|null $blockCookieVal The cookie value to check.
1753 * @return Block|bool The Block object, or false if none could be loaded.
1755 protected function getBlockFromCookieValue( $blockCookieVal ) {
1756 // Make sure there's something to check. The cookie value must start with a number.
1757 if ( strlen( $blockCookieVal ) < 1 ||
!is_numeric( substr( $blockCookieVal, 0, 1 ) ) ) {
1760 // Load the Block from the ID in the cookie.
1761 $blockCookieId = Block
::getIdFromCookieValue( $blockCookieVal );
1762 if ( $blockCookieId !== null ) {
1763 // An ID was found in the cookie.
1764 $tmpBlock = Block
::newFromID( $blockCookieId );
1765 if ( $tmpBlock instanceof Block
) {
1766 // Check the validity of the block.
1767 $blockIsValid = $tmpBlock->getType() == Block
::TYPE_USER
1768 && !$tmpBlock->isExpired()
1769 && $tmpBlock->isAutoblocking();
1770 $config = RequestContext
::getMain()->getConfig();
1771 $useBlockCookie = ( $config->get( 'CookieSetOnAutoblock' ) === true );
1772 if ( $blockIsValid && $useBlockCookie ) {
1776 // If the block is not valid, remove the cookie.
1777 Block
::clearCookie( $this->getRequest()->response() );
1780 // If the block doesn't exist, remove the cookie.
1781 Block
::clearCookie( $this->getRequest()->response() );
1788 * Whether the given IP is in a DNS blacklist.
1790 * @param string $ip IP to check
1791 * @param bool $checkWhitelist Whether to check the whitelist first
1792 * @return bool True if blacklisted.
1794 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1795 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1797 if ( !$wgEnableDnsBlacklist ) {
1801 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1805 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1809 * Whether the given IP is in a given DNS blacklist.
1811 * @param string $ip IP to check
1812 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1813 * @return bool True if blacklisted.
1815 public function inDnsBlacklist( $ip, $bases ) {
1817 // @todo FIXME: IPv6 ??? (https://bugs.php.net/bug.php?id=33170)
1818 if ( IP
::isIPv4( $ip ) ) {
1819 // Reverse IP, T23255
1820 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1822 foreach ( (array)$bases as $base ) {
1824 // If we have an access key, use that too (ProjectHoneypot, etc.)
1826 if ( is_array( $base ) ) {
1827 if ( count( $base ) >= 2 ) {
1828 // Access key is 1, base URL is 0
1829 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1831 $host = "$ipReversed.{$base[0]}";
1833 $basename = $base[0];
1835 $host = "$ipReversed.$base";
1839 $ipList = gethostbynamel( $host );
1842 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
1846 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
1855 * Check if an IP address is in the local proxy list
1861 public static function isLocallyBlockedProxy( $ip ) {
1862 global $wgProxyList;
1864 if ( !$wgProxyList ) {
1868 if ( !is_array( $wgProxyList ) ) {
1869 // Load values from the specified file
1870 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1873 $resultProxyList = [];
1874 $deprecatedIPEntries = [];
1876 // backward compatibility: move all ip addresses in keys to values
1877 foreach ( $wgProxyList as $key => $value ) {
1878 $keyIsIP = IP
::isIPAddress( $key );
1879 $valueIsIP = IP
::isIPAddress( $value );
1880 if ( $keyIsIP && !$valueIsIP ) {
1881 $deprecatedIPEntries[] = $key;
1882 $resultProxyList[] = $key;
1883 } elseif ( $keyIsIP && $valueIsIP ) {
1884 $deprecatedIPEntries[] = $key;
1885 $resultProxyList[] = $key;
1886 $resultProxyList[] = $value;
1888 $resultProxyList[] = $value;
1892 if ( $deprecatedIPEntries ) {
1894 'IP addresses in the keys of $wgProxyList (found the following IP addresses in keys: ' .
1895 implode( ', ', $deprecatedIPEntries ) . ', please move them to values)', '1.30' );
1898 $proxyListIPSet = new IPSet( $resultProxyList );
1899 return $proxyListIPSet->match( $ip );
1903 * Is this user subject to rate limiting?
1905 * @return bool True if rate limited
1907 public function isPingLimitable() {
1908 global $wgRateLimitsExcludedIPs;
1909 if ( IP
::isInRanges( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1910 // No other good way currently to disable rate limits
1911 // for specific IPs. :P
1912 // But this is a crappy hack and should die.
1915 return !$this->isAllowed( 'noratelimit' );
1919 * Primitive rate limits: enforce maximum actions per time period
1920 * to put a brake on flooding.
1922 * The method generates both a generic profiling point and a per action one
1923 * (suffix being "-$action".
1925 * @note When using a shared cache like memcached, IP-address
1926 * last-hit counters will be shared across wikis.
1928 * @param string $action Action to enforce; 'edit' if unspecified
1929 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1930 * @return bool True if a rate limiter was tripped
1932 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1933 // Avoid PHP 7.1 warning of passing $this by reference
1935 // Call the 'PingLimiter' hook
1937 if ( !Hooks
::run( 'PingLimiter', [ &$user, $action, &$result, $incrBy ] ) ) {
1941 global $wgRateLimits;
1942 if ( !isset( $wgRateLimits[$action] ) ) {
1946 $limits = array_merge(
1947 [ '&can-bypass' => true ],
1948 $wgRateLimits[$action]
1951 // Some groups shouldn't trigger the ping limiter, ever
1952 if ( $limits['&can-bypass'] && !$this->isPingLimitable() ) {
1957 $id = $this->getId();
1959 $isNewbie = $this->isNewbie();
1960 $cache = ObjectCache
::getLocalClusterInstance();
1964 if ( isset( $limits['anon'] ) ) {
1965 $keys[$cache->makeKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1968 // limits for logged-in users
1969 if ( isset( $limits['user'] ) ) {
1970 $userLimit = $limits['user'];
1972 // limits for newbie logged-in users
1973 if ( $isNewbie && isset( $limits['newbie'] ) ) {
1974 $keys[$cache->makeKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1978 // limits for anons and for newbie logged-in users
1981 if ( isset( $limits['ip'] ) ) {
1982 $ip = $this->getRequest()->getIP();
1983 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1985 // subnet-based limits
1986 if ( isset( $limits['subnet'] ) ) {
1987 $ip = $this->getRequest()->getIP();
1988 $subnet = IP
::getSubnet( $ip );
1989 if ( $subnet !== false ) {
1990 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1995 // Check for group-specific permissions
1996 // If more than one group applies, use the group with the highest limit ratio (max/period)
1997 foreach ( $this->getGroups() as $group ) {
1998 if ( isset( $limits[$group] ) ) {
1999 if ( $userLimit === false
2000 ||
$limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
2002 $userLimit = $limits[$group];
2007 // Set the user limit key
2008 if ( $userLimit !== false ) {
2009 list( $max, $period ) = $userLimit;
2010 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
2011 $keys[$cache->makeKey( 'limiter', $action, 'user', $id )] = $userLimit;
2014 // ip-based limits for all ping-limitable users
2015 if ( isset( $limits['ip-all'] ) ) {
2016 $ip = $this->getRequest()->getIP();
2017 // ignore if user limit is more permissive
2018 if ( $isNewbie ||
$userLimit === false
2019 ||
$limits['ip-all'][0] / $limits['ip-all'][1] > $userLimit[0] / $userLimit[1] ) {
2020 $keys["mediawiki:limiter:$action:ip-all:$ip"] = $limits['ip-all'];
2024 // subnet-based limits for all ping-limitable users
2025 if ( isset( $limits['subnet-all'] ) ) {
2026 $ip = $this->getRequest()->getIP();
2027 $subnet = IP
::getSubnet( $ip );
2028 if ( $subnet !== false ) {
2029 // ignore if user limit is more permissive
2030 if ( $isNewbie ||
$userLimit === false
2031 ||
$limits['ip-all'][0] / $limits['ip-all'][1]
2032 > $userLimit[0] / $userLimit[1] ) {
2033 $keys["mediawiki:limiter:$action:subnet-all:$subnet"] = $limits['subnet-all'];
2039 foreach ( $keys as $key => $limit ) {
2040 list( $max, $period ) = $limit;
2041 $summary = "(limit $max in {$period}s)";
2042 $count = $cache->get( $key );
2045 if ( $count >= $max ) {
2046 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
2047 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
2050 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
2053 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
2054 if ( $incrBy > 0 ) {
2055 $cache->add( $key, 0, intval( $period ) ); // first ping
2058 if ( $incrBy > 0 ) {
2059 $cache->incr( $key, $incrBy );
2067 * Check if user is blocked
2069 * @param bool $bFromSlave Whether to check the replica DB instead of
2070 * the master. Hacked from false due to horrible probs on site.
2071 * @return bool True if blocked, false otherwise
2073 public function isBlocked( $bFromSlave = true ) {
2074 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
2078 * Get the block affecting the user, or null if the user is not blocked
2080 * @param bool $bFromSlave Whether to check the replica DB instead of the master
2081 * @return Block|null
2083 public function getBlock( $bFromSlave = true ) {
2084 $this->getBlockedStatus( $bFromSlave );
2085 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
2089 * Check if user is blocked from editing a particular article
2091 * @param Title $title Title to check
2092 * @param bool $bFromSlave Whether to check the replica DB instead of the master
2095 public function isBlockedFrom( $title, $bFromSlave = false ) {
2096 global $wgBlockAllowsUTEdit;
2098 $blocked = $this->isBlocked( $bFromSlave );
2099 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
2100 // If a user's name is suppressed, they cannot make edits anywhere
2101 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName()
2102 && $title->getNamespace() == NS_USER_TALK
) {
2104 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
2107 Hooks
::run( 'UserIsBlockedFrom', [ $this, $title, &$blocked, &$allowUsertalk ] );
2113 * If user is blocked, return the name of the user who placed the block
2114 * @return string Name of blocker
2116 public function blockedBy() {
2117 $this->getBlockedStatus();
2118 return $this->mBlockedby
;
2122 * If user is blocked, return the specified reason for the block
2123 * @return string Blocking reason
2125 public function blockedFor() {
2126 $this->getBlockedStatus();
2127 return $this->mBlockreason
;
2131 * If user is blocked, return the ID for the block
2132 * @return int Block ID
2134 public function getBlockId() {
2135 $this->getBlockedStatus();
2136 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
2140 * Check if user is blocked on all wikis.
2141 * Do not use for actual edit permission checks!
2142 * This is intended for quick UI checks.
2144 * @param string $ip IP address, uses current client if none given
2145 * @return bool True if blocked, false otherwise
2147 public function isBlockedGlobally( $ip = '' ) {
2148 return $this->getGlobalBlock( $ip ) instanceof Block
;
2152 * Check if user is blocked on all wikis.
2153 * Do not use for actual edit permission checks!
2154 * This is intended for quick UI checks.
2156 * @param string $ip IP address, uses current client if none given
2157 * @return Block|null Block object if blocked, null otherwise
2158 * @throws FatalError
2159 * @throws MWException
2161 public function getGlobalBlock( $ip = '' ) {
2162 if ( $this->mGlobalBlock
!== null ) {
2163 return $this->mGlobalBlock ?
: null;
2165 // User is already an IP?
2166 if ( IP
::isIPAddress( $this->getName() ) ) {
2167 $ip = $this->getName();
2169 $ip = $this->getRequest()->getIP();
2171 // Avoid PHP 7.1 warning of passing $this by reference
2175 Hooks
::run( 'UserIsBlockedGlobally', [ &$user, $ip, &$blocked, &$block ] );
2177 if ( $blocked && $block === null ) {
2178 // back-compat: UserIsBlockedGlobally didn't have $block param first
2179 $block = new Block( [
2181 'systemBlock' => 'global-block'
2185 $this->mGlobalBlock
= $blocked ?
$block : false;
2186 return $this->mGlobalBlock ?
: null;
2190 * Check if user account is locked
2192 * @return bool True if locked, false otherwise
2194 public function isLocked() {
2195 if ( $this->mLocked
!== null ) {
2196 return $this->mLocked
;
2198 // Avoid PHP 7.1 warning of passing $this by reference
2200 $authUser = AuthManager
::callLegacyAuthPlugin( 'getUserInstance', [ &$user ], null );
2201 $this->mLocked
= $authUser && $authUser->isLocked();
2202 Hooks
::run( 'UserIsLocked', [ $this, &$this->mLocked
] );
2203 return $this->mLocked
;
2207 * Check if user account is hidden
2209 * @return bool True if hidden, false otherwise
2211 public function isHidden() {
2212 if ( $this->mHideName
!== null ) {
2213 return $this->mHideName
;
2215 $this->getBlockedStatus();
2216 if ( !$this->mHideName
) {
2217 // Avoid PHP 7.1 warning of passing $this by reference
2219 $authUser = AuthManager
::callLegacyAuthPlugin( 'getUserInstance', [ &$user ], null );
2220 $this->mHideName
= $authUser && $authUser->isHidden();
2221 Hooks
::run( 'UserIsHidden', [ $this, &$this->mHideName
] );
2223 return $this->mHideName
;
2227 * Get the user's ID.
2228 * @return int The user's ID; 0 if the user is anonymous or nonexistent
2230 public function getId() {
2231 if ( $this->mId
=== null && $this->mName
!== null && self
::isIP( $this->mName
) ) {
2232 // Special case, we know the user is anonymous
2234 } elseif ( !$this->isItemLoaded( 'id' ) ) {
2235 // Don't load if this was initialized from an ID
2239 return (int)$this->mId
;
2243 * Set the user and reload all fields according to a given ID
2244 * @param int $v User ID to reload
2246 public function setId( $v ) {
2248 $this->clearInstanceCache( 'id' );
2252 * Get the user name, or the IP of an anonymous user
2253 * @return string User's name or IP address
2255 public function getName() {
2256 if ( $this->isItemLoaded( 'name', 'only' ) ) {
2257 // Special case optimisation
2258 return $this->mName
;
2261 if ( $this->mName
=== false ) {
2263 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
2265 return $this->mName
;
2270 * Set the user name.
2272 * This does not reload fields from the database according to the given
2273 * name. Rather, it is used to create a temporary "nonexistent user" for
2274 * later addition to the database. It can also be used to set the IP
2275 * address for an anonymous user to something other than the current
2278 * @note User::newFromName() has roughly the same function, when the named user
2280 * @param string $str New user name to set
2282 public function setName( $str ) {
2284 $this->mName
= $str;
2288 * Get the user's name escaped by underscores.
2289 * @return string Username escaped by underscores.
2291 public function getTitleKey() {
2292 return str_replace( ' ', '_', $this->getName() );
2296 * Check if the user has new messages.
2297 * @return bool True if the user has new messages
2299 public function getNewtalk() {
2302 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2303 if ( $this->mNewtalk
=== -1 ) {
2304 $this->mNewtalk
= false; # reset talk page status
2306 // Check memcached separately for anons, who have no
2307 // entire User object stored in there.
2308 if ( !$this->mId
) {
2309 global $wgDisableAnonTalk;
2310 if ( $wgDisableAnonTalk ) {
2311 // Anon newtalk disabled by configuration.
2312 $this->mNewtalk
= false;
2314 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
2317 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2321 return (bool)$this->mNewtalk
;
2325 * Return the data needed to construct links for new talk page message
2326 * alerts. If there are new messages, this will return an associative array
2327 * with the following data:
2328 * wiki: The database name of the wiki
2329 * link: Root-relative link to the user's talk page
2330 * rev: The last talk page revision that the user has seen or null. This
2331 * is useful for building diff links.
2332 * If there are no new messages, it returns an empty array.
2333 * @note This function was designed to accomodate multiple talk pages, but
2334 * currently only returns a single link and revision.
2337 public function getNewMessageLinks() {
2338 // Avoid PHP 7.1 warning of passing $this by reference
2341 if ( !Hooks
::run( 'UserRetrieveNewTalks', [ &$user, &$talks ] ) ) {
2343 } elseif ( !$this->getNewtalk() ) {
2346 $utp = $this->getTalkPage();
2347 $dbr = wfGetDB( DB_REPLICA
);
2348 // Get the "last viewed rev" timestamp from the oldest message notification
2349 $timestamp = $dbr->selectField( 'user_newtalk',
2350 'MIN(user_last_timestamp)',
2351 $this->isAnon() ?
[ 'user_ip' => $this->getName() ] : [ 'user_id' => $this->getId() ],
2353 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2354 return [ [ 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ] ];
2358 * Get the revision ID for the last talk page revision viewed by the talk
2360 * @return int|null Revision ID or null
2362 public function getNewMessageRevisionId() {
2363 $newMessageRevisionId = null;
2364 $newMessageLinks = $this->getNewMessageLinks();
2365 if ( $newMessageLinks ) {
2366 // Note: getNewMessageLinks() never returns more than a single link
2367 // and it is always for the same wiki, but we double-check here in
2368 // case that changes some time in the future.
2369 if ( count( $newMessageLinks ) === 1
2370 && $newMessageLinks[0]['wiki'] === wfWikiID()
2371 && $newMessageLinks[0]['rev']
2373 /** @var Revision $newMessageRevision */
2374 $newMessageRevision = $newMessageLinks[0]['rev'];
2375 $newMessageRevisionId = $newMessageRevision->getId();
2378 return $newMessageRevisionId;
2382 * Internal uncached check for new messages
2385 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2386 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2387 * @return bool True if the user has new messages
2389 protected function checkNewtalk( $field, $id ) {
2390 $dbr = wfGetDB( DB_REPLICA
);
2392 $ok = $dbr->selectField( 'user_newtalk', $field, [ $field => $id ], __METHOD__
);
2394 return $ok !== false;
2398 * Add or update the new messages flag
2399 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2400 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2401 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2402 * @return bool True if successful, false otherwise
2404 protected function updateNewtalk( $field, $id, $curRev = null ) {
2405 // Get timestamp of the talk page revision prior to the current one
2406 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2407 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2408 // Mark the user as having new messages since this revision
2409 $dbw = wfGetDB( DB_MASTER
);
2410 $dbw->insert( 'user_newtalk',
2411 [ $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ],
2414 if ( $dbw->affectedRows() ) {
2415 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2418 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2424 * Clear the new messages flag for the given user
2425 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2426 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2427 * @return bool True if successful, false otherwise
2429 protected function deleteNewtalk( $field, $id ) {
2430 $dbw = wfGetDB( DB_MASTER
);
2431 $dbw->delete( 'user_newtalk',
2434 if ( $dbw->affectedRows() ) {
2435 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2438 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2444 * Update the 'You have new messages!' status.
2445 * @param bool $val Whether the user has new messages
2446 * @param Revision $curRev New, as yet unseen revision of the user talk
2447 * page. Ignored if null or !$val.
2449 public function setNewtalk( $val, $curRev = null ) {
2450 if ( wfReadOnly() ) {
2455 $this->mNewtalk
= $val;
2457 if ( $this->isAnon() ) {
2459 $id = $this->getName();
2462 $id = $this->getId();
2466 $changed = $this->updateNewtalk( $field, $id, $curRev );
2468 $changed = $this->deleteNewtalk( $field, $id );
2472 $this->invalidateCache();
2477 * Generate a current or new-future timestamp to be stored in the
2478 * user_touched field when we update things.
2479 * @return string Timestamp in TS_MW format
2481 private function newTouchedTimestamp() {
2482 global $wgClockSkewFudge;
2484 $time = wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2485 if ( $this->mTouched
&& $time <= $this->mTouched
) {
2486 $time = wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $this->mTouched
) +
1 );
2493 * Clear user data from memcached
2495 * Use after applying updates to the database; caller's
2496 * responsibility to update user_touched if appropriate.
2498 * Called implicitly from invalidateCache() and saveSettings().
2500 * @param string $mode Use 'refresh' to clear now; otherwise before DB commit
2502 public function clearSharedCache( $mode = 'changed' ) {
2503 if ( !$this->getId() ) {
2507 $cache = ObjectCache
::getMainWANInstance();
2508 $key = $this->getCacheKey( $cache );
2509 if ( $mode === 'refresh' ) {
2510 $cache->delete( $key, 1 );
2512 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle(
2513 function () use ( $cache, $key ) {
2514 $cache->delete( $key );
2522 * Immediately touch the user data cache for this account
2524 * Calls touch() and removes account data from memcached
2526 public function invalidateCache() {
2528 $this->clearSharedCache();
2532 * Update the "touched" timestamp for the user
2534 * This is useful on various login/logout events when making sure that
2535 * a browser or proxy that has multiple tenants does not suffer cache
2536 * pollution where the new user sees the old users content. The value
2537 * of getTouched() is checked when determining 304 vs 200 responses.
2538 * Unlike invalidateCache(), this preserves the User object cache and
2539 * avoids database writes.
2543 public function touch() {
2544 $id = $this->getId();
2546 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
2547 $key = $cache->makeKey( 'user-quicktouched', 'id', $id );
2548 $cache->touchCheckKey( $key );
2549 $this->mQuickTouched
= null;
2554 * Validate the cache for this account.
2555 * @param string $timestamp A timestamp in TS_MW format
2558 public function validateCache( $timestamp ) {
2559 return ( $timestamp >= $this->getTouched() );
2563 * Get the user touched timestamp
2565 * Use this value only to validate caches via inequalities
2566 * such as in the case of HTTP If-Modified-Since response logic
2568 * @return string TS_MW Timestamp
2570 public function getTouched() {
2574 if ( $this->mQuickTouched
=== null ) {
2575 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
2576 $key = $cache->makeKey( 'user-quicktouched', 'id', $this->mId
);
2578 $this->mQuickTouched
= wfTimestamp( TS_MW
, $cache->getCheckKeyTime( $key ) );
2581 return max( $this->mTouched
, $this->mQuickTouched
);
2584 return $this->mTouched
;
2588 * Get the user_touched timestamp field (time of last DB updates)
2589 * @return string TS_MW Timestamp
2592 public function getDBTouched() {
2595 return $this->mTouched
;
2599 * Set the password and reset the random token.
2600 * Calls through to authentication plugin if necessary;
2601 * will have no effect if the auth plugin refuses to
2602 * pass the change through or if the legal password
2605 * As a special case, setting the password to null
2606 * wipes it, so the account cannot be logged in until
2607 * a new password is set, for instance via e-mail.
2609 * @deprecated since 1.27, use AuthManager instead
2610 * @param string $str New password to set
2611 * @throws PasswordError On failure
2614 public function setPassword( $str ) {
2615 return $this->setPasswordInternal( $str );
2619 * Set the password and reset the random token unconditionally.
2621 * @deprecated since 1.27, use AuthManager instead
2622 * @param string|null $str New password to set or null to set an invalid
2623 * password hash meaning that the user will not be able to log in
2624 * through the web interface.
2626 public function setInternalPassword( $str ) {
2627 $this->setPasswordInternal( $str );
2631 * Actually set the password and such
2632 * @since 1.27 cannot set a password for a user not in the database
2633 * @param string|null $str New password to set or null to set an invalid
2634 * password hash meaning that the user will not be able to log in
2635 * through the web interface.
2636 * @return bool Success
2638 private function setPasswordInternal( $str ) {
2639 $manager = AuthManager
::singleton();
2641 // If the user doesn't exist yet, fail
2642 if ( !$manager->userExists( $this->getName() ) ) {
2643 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2646 $status = $this->changeAuthenticationData( [
2647 'username' => $this->getName(),
2651 if ( !$status->isGood() ) {
2652 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
2653 ->info( __METHOD__
. ': Password change rejected: '
2654 . $status->getWikiText( null, null, 'en' ) );
2658 $this->setOption( 'watchlisttoken', false );
2659 SessionManager
::singleton()->invalidateSessionsForUser( $this );
2665 * Changes credentials of the user.
2667 * This is a convenience wrapper around AuthManager::changeAuthenticationData.
2668 * Note that this can return a status that isOK() but not isGood() on certain types of failures,
2669 * e.g. when no provider handled the change.
2671 * @param array $data A set of authentication data in fieldname => value format. This is the
2672 * same data you would pass the changeauthenticationdata API - 'username', 'password' etc.
2676 public function changeAuthenticationData( array $data ) {
2677 $manager = AuthManager
::singleton();
2678 $reqs = $manager->getAuthenticationRequests( AuthManager
::ACTION_CHANGE
, $this );
2679 $reqs = AuthenticationRequest
::loadRequestsFromSubmission( $reqs, $data );
2681 $status = Status
::newGood( 'ignored' );
2682 foreach ( $reqs as $req ) {
2683 $status->merge( $manager->allowsAuthenticationDataChange( $req ), true );
2685 if ( $status->getValue() === 'ignored' ) {
2686 $status->warning( 'authenticationdatachange-ignored' );
2689 if ( $status->isGood() ) {
2690 foreach ( $reqs as $req ) {
2691 $manager->changeAuthenticationData( $req );
2698 * Get the user's current token.
2699 * @param bool $forceCreation Force the generation of a new token if the
2700 * user doesn't have one (default=true for backwards compatibility).
2701 * @return string|null Token
2703 public function getToken( $forceCreation = true ) {
2704 global $wgAuthenticationTokenVersion;
2707 if ( !$this->mToken
&& $forceCreation ) {
2711 if ( !$this->mToken
) {
2712 // The user doesn't have a token, return null to indicate that.
2714 } elseif ( $this->mToken
=== self
::INVALID_TOKEN
) {
2715 // We return a random value here so existing token checks are very
2717 return MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2718 } elseif ( $wgAuthenticationTokenVersion === null ) {
2719 // $wgAuthenticationTokenVersion not in use, so return the raw secret
2720 return $this->mToken
;
2722 // $wgAuthenticationTokenVersion in use, so hmac it.
2723 $ret = MWCryptHash
::hmac( $wgAuthenticationTokenVersion, $this->mToken
, false );
2725 // The raw hash can be overly long. Shorten it up.
2726 $len = max( 32, self
::TOKEN_LENGTH
);
2727 if ( strlen( $ret ) < $len ) {
2728 // Should never happen, even md5 is 128 bits
2729 throw new \
UnexpectedValueException( 'Hmac returned less than 128 bits' );
2731 return substr( $ret, -$len );
2736 * Set the random token (used for persistent authentication)
2737 * Called from loadDefaults() among other places.
2739 * @param string|bool $token If specified, set the token to this value
2741 public function setToken( $token = false ) {
2743 if ( $this->mToken
=== self
::INVALID_TOKEN
) {
2744 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
2745 ->debug( __METHOD__
. ": Ignoring attempt to set token for system user \"$this\"" );
2746 } elseif ( !$token ) {
2747 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2749 $this->mToken
= $token;
2754 * Set the password for a password reminder or new account email
2756 * @deprecated Removed in 1.27. Use PasswordReset instead.
2757 * @param string $str New password to set or null to set an invalid
2758 * password hash meaning that the user will not be able to use it
2759 * @param bool $throttle If true, reset the throttle timestamp to the present
2761 public function setNewpassword( $str, $throttle = true ) {
2762 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2766 * Get the user's e-mail address
2767 * @return string User's email address
2769 public function getEmail() {
2771 Hooks
::run( 'UserGetEmail', [ $this, &$this->mEmail
] );
2772 return $this->mEmail
;
2776 * Get the timestamp of the user's e-mail authentication
2777 * @return string TS_MW timestamp
2779 public function getEmailAuthenticationTimestamp() {
2781 Hooks
::run( 'UserGetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
2782 return $this->mEmailAuthenticated
;
2786 * Set the user's e-mail address
2787 * @param string $str New e-mail address
2789 public function setEmail( $str ) {
2791 if ( $str == $this->mEmail
) {
2794 $this->invalidateEmail();
2795 $this->mEmail
= $str;
2796 Hooks
::run( 'UserSetEmail', [ $this, &$this->mEmail
] );
2800 * Set the user's e-mail address and a confirmation mail if needed.
2803 * @param string $str New e-mail address
2806 public function setEmailWithConfirmation( $str ) {
2807 global $wgEnableEmail, $wgEmailAuthentication;
2809 if ( !$wgEnableEmail ) {
2810 return Status
::newFatal( 'emaildisabled' );
2813 $oldaddr = $this->getEmail();
2814 if ( $str === $oldaddr ) {
2815 return Status
::newGood( true );
2818 $type = $oldaddr != '' ?
'changed' : 'set';
2819 $notificationResult = null;
2821 if ( $wgEmailAuthentication ) {
2822 // Send the user an email notifying the user of the change in registered
2823 // email address on their previous email address
2824 if ( $type == 'changed' ) {
2825 $change = $str != '' ?
'changed' : 'removed';
2826 $notificationResult = $this->sendMail(
2827 wfMessage( 'notificationemail_subject_' . $change )->text(),
2828 wfMessage( 'notificationemail_body_' . $change,
2829 $this->getRequest()->getIP(),
2836 $this->setEmail( $str );
2838 if ( $str !== '' && $wgEmailAuthentication ) {
2839 // Send a confirmation request to the new address if needed
2840 $result = $this->sendConfirmationMail( $type );
2842 if ( $notificationResult !== null ) {
2843 $result->merge( $notificationResult );
2846 if ( $result->isGood() ) {
2847 // Say to the caller that a confirmation and notification mail has been sent
2848 $result->value
= 'eauth';
2851 $result = Status
::newGood( true );
2858 * Get the user's real name
2859 * @return string User's real name
2861 public function getRealName() {
2862 if ( !$this->isItemLoaded( 'realname' ) ) {
2866 return $this->mRealName
;
2870 * Set the user's real name
2871 * @param string $str New real name
2873 public function setRealName( $str ) {
2875 $this->mRealName
= $str;
2879 * Get the user's current setting for a given option.
2881 * @param string $oname The option to check
2882 * @param string $defaultOverride A default value returned if the option does not exist
2883 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2884 * @return string|null User's current value for the option
2885 * @see getBoolOption()
2886 * @see getIntOption()
2888 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2889 global $wgHiddenPrefs;
2890 $this->loadOptions();
2892 # We want 'disabled' preferences to always behave as the default value for
2893 # users, even if they have set the option explicitly in their settings (ie they
2894 # set it, and then it was disabled removing their ability to change it). But
2895 # we don't want to erase the preferences in the database in case the preference
2896 # is re-enabled again. So don't touch $mOptions, just override the returned value
2897 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2898 return self
::getDefaultOption( $oname );
2901 if ( array_key_exists( $oname, $this->mOptions
) ) {
2902 return $this->mOptions
[$oname];
2904 return $defaultOverride;
2909 * Get all user's options
2911 * @param int $flags Bitwise combination of:
2912 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2913 * to the default value. (Since 1.25)
2916 public function getOptions( $flags = 0 ) {
2917 global $wgHiddenPrefs;
2918 $this->loadOptions();
2919 $options = $this->mOptions
;
2921 # We want 'disabled' preferences to always behave as the default value for
2922 # users, even if they have set the option explicitly in their settings (ie they
2923 # set it, and then it was disabled removing their ability to change it). But
2924 # we don't want to erase the preferences in the database in case the preference
2925 # is re-enabled again. So don't touch $mOptions, just override the returned value
2926 foreach ( $wgHiddenPrefs as $pref ) {
2927 $default = self
::getDefaultOption( $pref );
2928 if ( $default !== null ) {
2929 $options[$pref] = $default;
2933 if ( $flags & self
::GETOPTIONS_EXCLUDE_DEFAULTS
) {
2934 $options = array_diff_assoc( $options, self
::getDefaultOptions() );
2941 * Get the user's current setting for a given option, as a boolean value.
2943 * @param string $oname The option to check
2944 * @return bool User's current value for the option
2947 public function getBoolOption( $oname ) {
2948 return (bool)$this->getOption( $oname );
2952 * Get the user's current setting for a given option, as an integer value.
2954 * @param string $oname The option to check
2955 * @param int $defaultOverride A default value returned if the option does not exist
2956 * @return int User's current value for the option
2959 public function getIntOption( $oname, $defaultOverride = 0 ) {
2960 $val = $this->getOption( $oname );
2962 $val = $defaultOverride;
2964 return intval( $val );
2968 * Set the given option for a user.
2970 * You need to call saveSettings() to actually write to the database.
2972 * @param string $oname The option to set
2973 * @param mixed $val New value to set
2975 public function setOption( $oname, $val ) {
2976 $this->loadOptions();
2978 // Explicitly NULL values should refer to defaults
2979 if ( is_null( $val ) ) {
2980 $val = self
::getDefaultOption( $oname );
2983 $this->mOptions
[$oname] = $val;
2987 * Get a token stored in the preferences (like the watchlist one),
2988 * resetting it if it's empty (and saving changes).
2990 * @param string $oname The option name to retrieve the token from
2991 * @return string|bool User's current value for the option, or false if this option is disabled.
2992 * @see resetTokenFromOption()
2994 * @deprecated since 1.26 Applications should use the OAuth extension
2996 public function getTokenFromOption( $oname ) {
2997 global $wgHiddenPrefs;
2999 $id = $this->getId();
3000 if ( !$id ||
in_array( $oname, $wgHiddenPrefs ) ) {
3004 $token = $this->getOption( $oname );
3006 // Default to a value based on the user token to avoid space
3007 // wasted on storing tokens for all users. When this option
3008 // is set manually by the user, only then is it stored.
3009 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
3016 * Reset a token stored in the preferences (like the watchlist one).
3017 * *Does not* save user's preferences (similarly to setOption()).
3019 * @param string $oname The option name to reset the token in
3020 * @return string|bool New token value, or false if this option is disabled.
3021 * @see getTokenFromOption()
3024 public function resetTokenFromOption( $oname ) {
3025 global $wgHiddenPrefs;
3026 if ( in_array( $oname, $wgHiddenPrefs ) ) {
3030 $token = MWCryptRand
::generateHex( 40 );
3031 $this->setOption( $oname, $token );
3036 * Return a list of the types of user options currently returned by
3037 * User::getOptionKinds().
3039 * Currently, the option kinds are:
3040 * - 'registered' - preferences which are registered in core MediaWiki or
3041 * by extensions using the UserGetDefaultOptions hook.
3042 * - 'registered-multiselect' - as above, using the 'multiselect' type.
3043 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
3044 * - 'userjs' - preferences with names starting with 'userjs-', intended to
3045 * be used by user scripts.
3046 * - 'special' - "preferences" that are not accessible via User::getOptions
3047 * or User::setOptions.
3048 * - 'unused' - preferences about which MediaWiki doesn't know anything.
3049 * These are usually legacy options, removed in newer versions.
3051 * The API (and possibly others) use this function to determine the possible
3052 * option types for validation purposes, so make sure to update this when a
3053 * new option kind is added.
3055 * @see User::getOptionKinds
3056 * @return array Option kinds
3058 public static function listOptionKinds() {
3061 'registered-multiselect',
3062 'registered-checkmatrix',
3070 * Return an associative array mapping preferences keys to the kind of a preference they're
3071 * used for. Different kinds are handled differently when setting or reading preferences.
3073 * See User::listOptionKinds for the list of valid option types that can be provided.
3075 * @see User::listOptionKinds
3076 * @param IContextSource $context
3077 * @param array $options Assoc. array with options keys to check as keys.
3078 * Defaults to $this->mOptions.
3079 * @return array The key => kind mapping data
3081 public function getOptionKinds( IContextSource
$context, $options = null ) {
3082 $this->loadOptions();
3083 if ( $options === null ) {
3084 $options = $this->mOptions
;
3087 $preferencesFactory = MediaWikiServices
::getInstance()->getPreferencesFactory();
3088 $prefs = $preferencesFactory->getFormDescriptor( $this, $context );
3091 // Pull out the "special" options, so they don't get converted as
3092 // multiselect or checkmatrix.
3093 $specialOptions = array_fill_keys( $preferencesFactory->getSaveBlacklist(), true );
3094 foreach ( $specialOptions as $name => $value ) {
3095 unset( $prefs[$name] );
3098 // Multiselect and checkmatrix options are stored in the database with
3099 // one key per option, each having a boolean value. Extract those keys.
3100 $multiselectOptions = [];
3101 foreach ( $prefs as $name => $info ) {
3102 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
3103 ( isset( $info['class'] ) && $info['class'] == HTMLMultiSelectField
::class ) ) {
3104 $opts = HTMLFormField
::flattenOptions( $info['options'] );
3105 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
3107 foreach ( $opts as $value ) {
3108 $multiselectOptions["$prefix$value"] = true;
3111 unset( $prefs[$name] );
3114 $checkmatrixOptions = [];
3115 foreach ( $prefs as $name => $info ) {
3116 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
3117 ( isset( $info['class'] ) && $info['class'] == HTMLCheckMatrix
::class ) ) {
3118 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
3119 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
3120 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
3122 foreach ( $columns as $column ) {
3123 foreach ( $rows as $row ) {
3124 $checkmatrixOptions["$prefix$column-$row"] = true;
3128 unset( $prefs[$name] );
3132 // $value is ignored
3133 foreach ( $options as $key => $value ) {
3134 if ( isset( $prefs[$key] ) ) {
3135 $mapping[$key] = 'registered';
3136 } elseif ( isset( $multiselectOptions[$key] ) ) {
3137 $mapping[$key] = 'registered-multiselect';
3138 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
3139 $mapping[$key] = 'registered-checkmatrix';
3140 } elseif ( isset( $specialOptions[$key] ) ) {
3141 $mapping[$key] = 'special';
3142 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
3143 $mapping[$key] = 'userjs';
3145 $mapping[$key] = 'unused';
3153 * Reset certain (or all) options to the site defaults
3155 * The optional parameter determines which kinds of preferences will be reset.
3156 * Supported values are everything that can be reported by getOptionKinds()
3157 * and 'all', which forces a reset of *all* preferences and overrides everything else.
3159 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
3160 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
3161 * for backwards-compatibility.
3162 * @param IContextSource|null $context Context source used when $resetKinds
3163 * does not contain 'all', passed to getOptionKinds().
3164 * Defaults to RequestContext::getMain() when null.
3166 public function resetOptions(
3167 $resetKinds = [ 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ],
3168 IContextSource
$context = null
3171 $defaultOptions = self
::getDefaultOptions();
3173 if ( !is_array( $resetKinds ) ) {
3174 $resetKinds = [ $resetKinds ];
3177 if ( in_array( 'all', $resetKinds ) ) {
3178 $newOptions = $defaultOptions;
3180 if ( $context === null ) {
3181 $context = RequestContext
::getMain();
3184 $optionKinds = $this->getOptionKinds( $context );
3185 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
3188 // Use default values for the options that should be deleted, and
3189 // copy old values for the ones that shouldn't.
3190 foreach ( $this->mOptions
as $key => $value ) {
3191 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
3192 if ( array_key_exists( $key, $defaultOptions ) ) {
3193 $newOptions[$key] = $defaultOptions[$key];
3196 $newOptions[$key] = $value;
3201 Hooks
::run( 'UserResetAllOptions', [ $this, &$newOptions, $this->mOptions
, $resetKinds ] );
3203 $this->mOptions
= $newOptions;
3204 $this->mOptionsLoaded
= true;
3208 * Get the user's preferred date format.
3209 * @return string User's preferred date format
3211 public function getDatePreference() {
3212 // Important migration for old data rows
3213 if ( is_null( $this->mDatePreference
) ) {
3215 $value = $this->getOption( 'date' );
3216 $map = $wgLang->getDatePreferenceMigrationMap();
3217 if ( isset( $map[$value] ) ) {
3218 $value = $map[$value];
3220 $this->mDatePreference
= $value;
3222 return $this->mDatePreference
;
3226 * Determine based on the wiki configuration and the user's options,
3227 * whether this user must be over HTTPS no matter what.
3231 public function requiresHTTPS() {
3232 global $wgSecureLogin;
3233 if ( !$wgSecureLogin ) {
3236 $https = $this->getBoolOption( 'prefershttps' );
3237 Hooks
::run( 'UserRequiresHTTPS', [ $this, &$https ] );
3239 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
3246 * Get the user preferred stub threshold
3250 public function getStubThreshold() {
3251 global $wgMaxArticleSize; # Maximum article size, in Kb
3252 $threshold = $this->getIntOption( 'stubthreshold' );
3253 if ( $threshold > $wgMaxArticleSize * 1024 ) {
3254 // If they have set an impossible value, disable the preference
3255 // so we can use the parser cache again.
3262 * Get the permissions this user has.
3263 * @return string[] permission names
3265 public function getRights() {
3266 if ( is_null( $this->mRights
) ) {
3267 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
3268 Hooks
::run( 'UserGetRights', [ $this, &$this->mRights
] );
3270 // Deny any rights denied by the user's session, unless this
3271 // endpoint has no sessions.
3272 if ( !defined( 'MW_NO_SESSION' ) ) {
3273 $allowedRights = $this->getRequest()->getSession()->getAllowedUserRights();
3274 if ( $allowedRights !== null ) {
3275 $this->mRights
= array_intersect( $this->mRights
, $allowedRights );
3279 // Force reindexation of rights when a hook has unset one of them
3280 $this->mRights
= array_values( array_unique( $this->mRights
) );
3282 // If block disables login, we should also remove any
3283 // extra rights blocked users might have, in case the
3284 // blocked user has a pre-existing session (T129738).
3285 // This is checked here for cases where people only call
3286 // $user->isAllowed(). It is also checked in Title::checkUserBlock()
3287 // to give a better error message in the common case.
3288 $config = RequestContext
::getMain()->getConfig();
3290 $this->isLoggedIn() &&
3291 $config->get( 'BlockDisablesLogin' ) &&
3295 $this->mRights
= array_intersect( $this->mRights
, $anon->getRights() );
3298 return $this->mRights
;
3302 * Get the list of explicit group memberships this user has.
3303 * The implicit * and user groups are not included.
3304 * @return array Array of String internal group names
3306 public function getGroups() {
3308 $this->loadGroups();
3309 return array_keys( $this->mGroupMemberships
);
3313 * Get the list of explicit group memberships this user has, stored as
3314 * UserGroupMembership objects. Implicit groups are not included.
3316 * @return UserGroupMembership[] Associative array of (group name => UserGroupMembership object)
3319 public function getGroupMemberships() {
3321 $this->loadGroups();
3322 return $this->mGroupMemberships
;
3326 * Get the list of implicit group memberships this user has.
3327 * This includes all explicit groups, plus 'user' if logged in,
3328 * '*' for all accounts, and autopromoted groups
3329 * @param bool $recache Whether to avoid the cache
3330 * @return array Array of String internal group names
3332 public function getEffectiveGroups( $recache = false ) {
3333 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
3334 $this->mEffectiveGroups
= array_unique( array_merge(
3335 $this->getGroups(), // explicit groups
3336 $this->getAutomaticGroups( $recache ) // implicit groups
3338 // Avoid PHP 7.1 warning of passing $this by reference
3340 // Hook for additional groups
3341 Hooks
::run( 'UserEffectiveGroups', [ &$user, &$this->mEffectiveGroups
] );
3342 // Force reindexation of groups when a hook has unset one of them
3343 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
3345 return $this->mEffectiveGroups
;
3349 * Get the list of implicit group memberships this user has.
3350 * This includes 'user' if logged in, '*' for all accounts,
3351 * and autopromoted groups
3352 * @param bool $recache Whether to avoid the cache
3353 * @return array Array of String internal group names
3355 public function getAutomaticGroups( $recache = false ) {
3356 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
3357 $this->mImplicitGroups
= [ '*' ];
3358 if ( $this->getId() ) {
3359 $this->mImplicitGroups
[] = 'user';
3361 $this->mImplicitGroups
= array_unique( array_merge(
3362 $this->mImplicitGroups
,
3363 Autopromote
::getAutopromoteGroups( $this )
3367 // Assure data consistency with rights/groups,
3368 // as getEffectiveGroups() depends on this function
3369 $this->mEffectiveGroups
= null;
3372 return $this->mImplicitGroups
;
3376 * Returns the groups the user has belonged to.
3378 * The user may still belong to the returned groups. Compare with getGroups().
3380 * The function will not return groups the user had belonged to before MW 1.17
3382 * @return array Names of the groups the user has belonged to.
3384 public function getFormerGroups() {
3387 if ( is_null( $this->mFormerGroups
) ) {
3388 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3389 ?
wfGetDB( DB_MASTER
)
3390 : wfGetDB( DB_REPLICA
);
3391 $res = $db->select( 'user_former_groups',
3393 [ 'ufg_user' => $this->mId
],
3395 $this->mFormerGroups
= [];
3396 foreach ( $res as $row ) {
3397 $this->mFormerGroups
[] = $row->ufg_group
;
3401 return $this->mFormerGroups
;
3405 * Get the user's edit count.
3406 * @return int|null Null for anonymous users
3408 public function getEditCount() {
3409 if ( !$this->getId() ) {
3413 if ( $this->mEditCount
=== null ) {
3414 /* Populate the count, if it has not been populated yet */
3415 $dbr = wfGetDB( DB_REPLICA
);
3416 // check if the user_editcount field has been initialized
3417 $count = $dbr->selectField(
3418 'user', 'user_editcount',
3419 [ 'user_id' => $this->mId
],
3423 if ( $count === null ) {
3424 // it has not been initialized. do so.
3425 $count = $this->initEditCount();
3427 $this->mEditCount
= $count;
3429 return (int)$this->mEditCount
;
3433 * Add the user to the given group. This takes immediate effect.
3434 * If the user is already in the group, the expiry time will be updated to the new
3435 * expiry time. (If $expiry is omitted or null, the membership will be altered to
3438 * @param string $group Name of the group to add
3439 * @param string $expiry Optional expiry timestamp in any format acceptable to
3440 * wfTimestamp(), or null if the group assignment should not expire
3443 public function addGroup( $group, $expiry = null ) {
3445 $this->loadGroups();
3448 $expiry = wfTimestamp( TS_MW
, $expiry );
3451 if ( !Hooks
::run( 'UserAddGroup', [ $this, &$group, &$expiry ] ) ) {
3455 // create the new UserGroupMembership and put it in the DB
3456 $ugm = new UserGroupMembership( $this->mId
, $group, $expiry );
3457 if ( !$ugm->insert( true ) ) {
3461 $this->mGroupMemberships
[$group] = $ugm;
3463 // Refresh the groups caches, and clear the rights cache so it will be
3464 // refreshed on the next call to $this->getRights().
3465 $this->getEffectiveGroups( true );
3466 $this->mRights
= null;
3468 $this->invalidateCache();
3474 * Remove the user from the given group.
3475 * This takes immediate effect.
3476 * @param string $group Name of the group to remove
3479 public function removeGroup( $group ) {
3482 if ( !Hooks
::run( 'UserRemoveGroup', [ $this, &$group ] ) ) {
3486 $ugm = UserGroupMembership
::getMembership( $this->mId
, $group );
3487 // delete the membership entry
3488 if ( !$ugm ||
!$ugm->delete() ) {
3492 $this->loadGroups();
3493 unset( $this->mGroupMemberships
[$group] );
3495 // Refresh the groups caches, and clear the rights cache so it will be
3496 // refreshed on the next call to $this->getRights().
3497 $this->getEffectiveGroups( true );
3498 $this->mRights
= null;
3500 $this->invalidateCache();
3506 * Get whether the user is logged in
3509 public function isLoggedIn() {
3510 return $this->getId() != 0;
3514 * Get whether the user is anonymous
3517 public function isAnon() {
3518 return !$this->isLoggedIn();
3522 * @return bool Whether this user is flagged as being a bot role account
3525 public function isBot() {
3526 if ( in_array( 'bot', $this->getGroups() ) && $this->isAllowed( 'bot' ) ) {
3531 Hooks
::run( "UserIsBot", [ $this, &$isBot ] );
3537 * Check if user is allowed to access a feature / make an action
3539 * @param string $permissions,... Permissions to test
3540 * @return bool True if user is allowed to perform *any* of the given actions
3542 public function isAllowedAny() {
3543 $permissions = func_get_args();
3544 foreach ( $permissions as $permission ) {
3545 if ( $this->isAllowed( $permission ) ) {
3554 * @param string $permissions,... Permissions to test
3555 * @return bool True if the user is allowed to perform *all* of the given actions
3557 public function isAllowedAll() {
3558 $permissions = func_get_args();
3559 foreach ( $permissions as $permission ) {
3560 if ( !$this->isAllowed( $permission ) ) {
3568 * Internal mechanics of testing a permission
3569 * @param string $action
3572 public function isAllowed( $action = '' ) {
3573 if ( $action === '' ) {
3574 return true; // In the spirit of DWIM
3576 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3577 // by misconfiguration: 0 == 'foo'
3578 return in_array( $action, $this->getRights(), true );
3582 * Check whether to enable recent changes patrol features for this user
3583 * @return bool True or false
3585 public function useRCPatrol() {
3586 global $wgUseRCPatrol;
3587 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3591 * Check whether to enable new pages patrol features for this user
3592 * @return bool True or false
3594 public function useNPPatrol() {
3595 global $wgUseRCPatrol, $wgUseNPPatrol;
3597 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3598 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3603 * Check whether to enable new files patrol features for this user
3604 * @return bool True or false
3606 public function useFilePatrol() {
3607 global $wgUseRCPatrol, $wgUseFilePatrol;
3609 ( $wgUseRCPatrol ||
$wgUseFilePatrol )
3610 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3615 * Get the WebRequest object to use with this object
3617 * @return WebRequest
3619 public function getRequest() {
3620 if ( $this->mRequest
) {
3621 return $this->mRequest
;
3629 * Check the watched status of an article.
3630 * @since 1.22 $checkRights parameter added
3631 * @param Title $title Title of the article to look at
3632 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3633 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3636 public function isWatched( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3637 if ( $title->isWatchable() && ( !$checkRights ||
$this->isAllowed( 'viewmywatchlist' ) ) ) {
3638 return MediaWikiServices
::getInstance()->getWatchedItemStore()->isWatched( $this, $title );
3645 * @since 1.22 $checkRights parameter added
3646 * @param Title $title Title of the article to look at
3647 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3648 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3650 public function addWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3651 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3652 MediaWikiServices
::getInstance()->getWatchedItemStore()->addWatchBatchForUser(
3654 [ $title->getSubjectPage(), $title->getTalkPage() ]
3657 $this->invalidateCache();
3661 * Stop watching an article.
3662 * @since 1.22 $checkRights parameter added
3663 * @param Title $title Title of the article to look at
3664 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3665 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3667 public function removeWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3668 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3669 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
3670 $store->removeWatch( $this, $title->getSubjectPage() );
3671 $store->removeWatch( $this, $title->getTalkPage() );
3673 $this->invalidateCache();
3677 * Clear the user's notification timestamp for the given title.
3678 * If e-notif e-mails are on, they will receive notification mails on
3679 * the next change of the page if it's watched etc.
3680 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3681 * @param Title &$title Title of the article to look at
3682 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3684 public function clearNotification( &$title, $oldid = 0 ) {
3685 global $wgUseEnotif, $wgShowUpdatedMarker;
3687 // Do nothing if the database is locked to writes
3688 if ( wfReadOnly() ) {
3692 // Do nothing if not allowed to edit the watchlist
3693 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3697 // If we're working on user's talk page, we should update the talk page message indicator
3698 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3699 // Avoid PHP 7.1 warning of passing $this by reference
3701 if ( !Hooks
::run( 'UserClearNewTalkNotification', [ &$user, $oldid ] ) ) {
3705 // Try to update the DB post-send and only if needed...
3706 DeferredUpdates
::addCallableUpdate( function () use ( $title, $oldid ) {
3707 if ( !$this->getNewtalk() ) {
3708 return; // no notifications to clear
3711 // Delete the last notifications (they stack up)
3712 $this->setNewtalk( false );
3714 // If there is a new, unseen, revision, use its timestamp
3716 ?
$title->getNextRevisionID( $oldid, Title
::GAID_FOR_UPDATE
)
3719 $this->setNewtalk( true, Revision
::newFromId( $nextid ) );
3724 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3728 if ( $this->isAnon() ) {
3729 // Nothing else to do...
3733 // Only update the timestamp if the page is being watched.
3734 // The query to find out if it is watched is cached both in memcached and per-invocation,
3735 // and when it does have to be executed, it can be on a replica DB
3736 // If this is the user's newtalk page, we always update the timestamp
3738 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3742 MediaWikiServices
::getInstance()->getWatchedItemStore()
3743 ->resetNotificationTimestamp( $this, $title, $force, $oldid );
3747 * Resets all of the given user's page-change notification timestamps.
3748 * If e-notif e-mails are on, they will receive notification mails on
3749 * the next change of any watched page.
3750 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3752 public function clearAllNotifications() {
3753 global $wgUseEnotif, $wgShowUpdatedMarker;
3754 // Do nothing if not allowed to edit the watchlist
3755 if ( wfReadOnly() ||
!$this->isAllowed( 'editmywatchlist' ) ) {
3759 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3760 $this->setNewtalk( false );
3764 $id = $this->getId();
3769 $dbw = wfGetDB( DB_MASTER
);
3770 $asOfTimes = array_unique( $dbw->selectFieldValues(
3772 'wl_notificationtimestamp',
3773 [ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ],
3775 [ 'ORDER BY' => 'wl_notificationtimestamp DESC', 'LIMIT' => 500 ]
3777 if ( !$asOfTimes ) {
3780 // Immediately update the most recent touched rows, which hopefully covers what
3781 // the user sees on the watchlist page before pressing "mark all pages visited"....
3784 [ 'wl_notificationtimestamp' => null ],
3785 [ 'wl_user' => $id, 'wl_notificationtimestamp' => $asOfTimes ],
3788 // ...and finish the older ones in a post-send update with lag checks...
3789 DeferredUpdates
::addUpdate( new AutoCommitUpdate(
3792 function () use ( $dbw, $id ) {
3793 global $wgUpdateRowsPerQuery;
3795 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
3796 $ticket = $lbFactory->getEmptyTransactionTicket( __METHOD__
);
3797 $asOfTimes = array_unique( $dbw->selectFieldValues(
3799 'wl_notificationtimestamp',
3800 [ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ],
3803 foreach ( array_chunk( $asOfTimes, $wgUpdateRowsPerQuery ) as $asOfTimeBatch ) {
3806 [ 'wl_notificationtimestamp' => null ],
3807 [ 'wl_user' => $id, 'wl_notificationtimestamp' => $asOfTimeBatch ],
3810 $lbFactory->commitAndWaitForReplication( __METHOD__
, $ticket );
3814 // We also need to clear here the "you have new message" notification for the own
3815 // user_talk page; it's cleared one page view later in WikiPage::doViewUpdates().
3819 * Compute experienced level based on edit count and registration date.
3821 * @return string 'newcomer', 'learner', or 'experienced'
3823 public function getExperienceLevel() {
3824 global $wgLearnerEdits,
3825 $wgExperiencedUserEdits,
3826 $wgLearnerMemberSince,
3827 $wgExperiencedUserMemberSince;
3829 if ( $this->isAnon() ) {
3833 $editCount = $this->getEditCount();
3834 $registration = $this->getRegistration();
3836 $learnerRegistration = wfTimestamp( TS_MW
, $now - $wgLearnerMemberSince * 86400 );
3837 $experiencedRegistration = wfTimestamp( TS_MW
, $now - $wgExperiencedUserMemberSince * 86400 );
3840 $editCount < $wgLearnerEdits ||
3841 $registration > $learnerRegistration
3845 $editCount > $wgExperiencedUserEdits &&
3846 $registration <= $experiencedRegistration
3848 return 'experienced';
3855 * Set a cookie on the user's client. Wrapper for
3856 * WebResponse::setCookie
3857 * @deprecated since 1.27
3858 * @param string $name Name of the cookie to set
3859 * @param string $value Value to set
3860 * @param int $exp Expiration time, as a UNIX time value;
3861 * if 0 or not specified, use the default $wgCookieExpiration
3862 * @param bool $secure
3863 * true: Force setting the secure attribute when setting the cookie
3864 * false: Force NOT setting the secure attribute when setting the cookie
3865 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3866 * @param array $params Array of options sent passed to WebResponse::setcookie()
3867 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3870 protected function setCookie(
3871 $name, $value, $exp = 0, $secure = null, $params = [], $request = null
3873 wfDeprecated( __METHOD__
, '1.27' );
3874 if ( $request === null ) {
3875 $request = $this->getRequest();
3877 $params['secure'] = $secure;
3878 $request->response()->setCookie( $name, $value, $exp, $params );
3882 * Clear a cookie on the user's client
3883 * @deprecated since 1.27
3884 * @param string $name Name of the cookie to clear
3885 * @param bool $secure
3886 * true: Force setting the secure attribute when setting the cookie
3887 * false: Force NOT setting the secure attribute when setting the cookie
3888 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3889 * @param array $params Array of options sent passed to WebResponse::setcookie()
3891 protected function clearCookie( $name, $secure = null, $params = [] ) {
3892 wfDeprecated( __METHOD__
, '1.27' );
3893 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3897 * Set an extended login cookie on the user's client. The expiry of the cookie
3898 * is controlled by the $wgExtendedLoginCookieExpiration configuration
3901 * @see User::setCookie
3903 * @deprecated since 1.27
3904 * @param string $name Name of the cookie to set
3905 * @param string $value Value to set
3906 * @param bool $secure
3907 * true: Force setting the secure attribute when setting the cookie
3908 * false: Force NOT setting the secure attribute when setting the cookie
3909 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3911 protected function setExtendedLoginCookie( $name, $value, $secure ) {
3912 global $wgExtendedLoginCookieExpiration, $wgCookieExpiration;
3914 wfDeprecated( __METHOD__
, '1.27' );
3917 $exp +
= $wgExtendedLoginCookieExpiration !== null
3918 ?
$wgExtendedLoginCookieExpiration
3919 : $wgCookieExpiration;
3921 $this->setCookie( $name, $value, $exp, $secure );
3925 * Persist this user's session (e.g. set cookies)
3927 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3929 * @param bool $secure Whether to force secure/insecure cookies or use default
3930 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3932 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3934 if ( 0 == $this->mId
) {
3938 $session = $this->getRequest()->getSession();
3939 if ( $request && $session->getRequest() !== $request ) {
3940 $session = $session->sessionWithRequest( $request );
3942 $delay = $session->delaySave();
3944 if ( !$session->getUser()->equals( $this ) ) {
3945 if ( !$session->canSetUser() ) {
3946 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3947 ->warning( __METHOD__
.
3948 ": Cannot save user \"$this\" to a user \"{$session->getUser()}\"'s immutable session"
3952 $session->setUser( $this );
3955 $session->setRememberUser( $rememberMe );
3956 if ( $secure !== null ) {
3957 $session->setForceHTTPS( $secure );
3960 $session->persist();
3962 ScopedCallback
::consume( $delay );
3966 * Log this user out.
3968 public function logout() {
3969 // Avoid PHP 7.1 warning of passing $this by reference
3971 if ( Hooks
::run( 'UserLogout', [ &$user ] ) ) {
3977 * Clear the user's session, and reset the instance cache.
3980 public function doLogout() {
3981 $session = $this->getRequest()->getSession();
3982 if ( !$session->canSetUser() ) {
3983 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3984 ->warning( __METHOD__
. ": Cannot log out of an immutable session" );
3985 $error = 'immutable';
3986 } elseif ( !$session->getUser()->equals( $this ) ) {
3987 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3988 ->warning( __METHOD__
.
3989 ": Cannot log user \"$this\" out of a user \"{$session->getUser()}\"'s session"
3991 // But we still may as well make this user object anon
3992 $this->clearInstanceCache( 'defaults' );
3993 $error = 'wronguser';
3995 $this->clearInstanceCache( 'defaults' );
3996 $delay = $session->delaySave();
3997 $session->unpersist(); // Clear cookies (T127436)
3998 $session->setLoggedOutTimestamp( time() );
3999 $session->setUser( new User
);
4000 $session->set( 'wsUserID', 0 ); // Other code expects this
4001 $session->resetAllTokens();
4002 ScopedCallback
::consume( $delay );
4005 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authevents' )->info( 'Logout', [
4006 'event' => 'logout',
4007 'successful' => $error === false,
4008 'status' => $error ?
: 'success',
4013 * Save this user's settings into the database.
4014 * @todo Only rarely do all these fields need to be set!
4016 public function saveSettings() {
4017 if ( wfReadOnly() ) {
4018 // @TODO: caller should deal with this instead!
4019 // This should really just be an exception.
4020 MWExceptionHandler
::logException( new DBExpectedError(
4022 "Could not update user with ID '{$this->mId}'; DB is read-only."
4028 if ( 0 == $this->mId
) {
4032 // Get a new user_touched that is higher than the old one.
4033 // This will be used for a CAS check as a last-resort safety
4034 // check against race conditions and replica DB lag.
4035 $newTouched = $this->newTouchedTimestamp();
4037 $dbw = wfGetDB( DB_MASTER
);
4038 $dbw->update( 'user',
4040 'user_name' => $this->mName
,
4041 'user_real_name' => $this->mRealName
,
4042 'user_email' => $this->mEmail
,
4043 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
4044 'user_touched' => $dbw->timestamp( $newTouched ),
4045 'user_token' => strval( $this->mToken
),
4046 'user_email_token' => $this->mEmailToken
,
4047 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
4048 ], $this->makeUpdateConditions( $dbw, [ /* WHERE */
4049 'user_id' => $this->mId
,
4053 if ( !$dbw->affectedRows() ) {
4054 // Maybe the problem was a missed cache update; clear it to be safe
4055 $this->clearSharedCache( 'refresh' );
4056 // User was changed in the meantime or loaded with stale data
4057 $from = ( $this->queryFlagsUsed
& self
::READ_LATEST
) ?
'master' : 'replica';
4058 throw new MWException(
4059 "CAS update failed on user_touched for user ID '{$this->mId}' (read from $from);" .
4060 " the version of the user to be saved is older than the current version."
4064 $this->mTouched
= $newTouched;
4065 $this->saveOptions();
4067 Hooks
::run( 'UserSaveSettings', [ $this ] );
4068 $this->clearSharedCache();
4069 $this->getUserPage()->invalidateCache();
4073 * If only this user's username is known, and it exists, return the user ID.
4075 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
4078 public function idForName( $flags = 0 ) {
4079 $s = trim( $this->getName() );
4084 $db = ( ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
)
4085 ?
wfGetDB( DB_MASTER
)
4086 : wfGetDB( DB_REPLICA
);
4088 $options = ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
)
4089 ?
[ 'LOCK IN SHARE MODE' ]
4092 $id = $db->selectField( 'user',
4093 'user_id', [ 'user_name' => $s ], __METHOD__
, $options );
4099 * Add a user to the database, return the user object
4101 * @param string $name Username to add
4102 * @param array $params Array of Strings Non-default parameters to save to
4103 * the database as user_* fields:
4104 * - email: The user's email address.
4105 * - email_authenticated: The email authentication timestamp.
4106 * - real_name: The user's real name.
4107 * - options: An associative array of non-default options.
4108 * - token: Random authentication token. Do not set.
4109 * - registration: Registration timestamp. Do not set.
4111 * @return User|null User object, or null if the username already exists.
4113 public static function createNew( $name, $params = [] ) {
4114 foreach ( [ 'password', 'newpassword', 'newpass_time', 'password_expires' ] as $field ) {
4115 if ( isset( $params[$field] ) ) {
4116 wfDeprecated( __METHOD__
. " with param '$field'", '1.27' );
4117 unset( $params[$field] );
4123 $user->setToken(); // init token
4124 if ( isset( $params['options'] ) ) {
4125 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
4126 unset( $params['options'] );
4128 $dbw = wfGetDB( DB_MASTER
);
4130 $noPass = PasswordFactory
::newInvalidPassword()->toString();
4133 'user_name' => $name,
4134 'user_password' => $noPass,
4135 'user_newpassword' => $noPass,
4136 'user_email' => $user->mEmail
,
4137 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
4138 'user_real_name' => $user->mRealName
,
4139 'user_token' => strval( $user->mToken
),
4140 'user_registration' => $dbw->timestamp( $user->mRegistration
),
4141 'user_editcount' => 0,
4142 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
4144 foreach ( $params as $name => $value ) {
4145 $fields["user_$name"] = $value;
4147 $dbw->insert( 'user', $fields, __METHOD__
, [ 'IGNORE' ] );
4148 if ( $dbw->affectedRows() ) {
4149 $newUser = self
::newFromId( $dbw->insertId() );
4157 * Add this existing user object to the database. If the user already
4158 * exists, a fatal status object is returned, and the user object is
4159 * initialised with the data from the database.
4161 * Previously, this function generated a DB error due to a key conflict
4162 * if the user already existed. Many extension callers use this function
4163 * in code along the lines of:
4165 * $user = User::newFromName( $name );
4166 * if ( !$user->isLoggedIn() ) {
4167 * $user->addToDatabase();
4169 * // do something with $user...
4171 * However, this was vulnerable to a race condition (T18020). By
4172 * initialising the user object if the user exists, we aim to support this
4173 * calling sequence as far as possible.
4175 * Note that if the user exists, this function will acquire a write lock,
4176 * so it is still advisable to make the call conditional on isLoggedIn(),
4177 * and to commit the transaction after calling.
4179 * @throws MWException
4182 public function addToDatabase() {
4184 if ( !$this->mToken
) {
4185 $this->setToken(); // init token
4188 if ( !is_string( $this->mName
) ) {
4189 throw new RuntimeException( "User name field is not set." );
4192 $this->mTouched
= $this->newTouchedTimestamp();
4194 $noPass = PasswordFactory
::newInvalidPassword()->toString();
4196 $dbw = wfGetDB( DB_MASTER
);
4197 $dbw->insert( 'user',
4199 'user_name' => $this->mName
,
4200 'user_password' => $noPass,
4201 'user_newpassword' => $noPass,
4202 'user_email' => $this->mEmail
,
4203 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
4204 'user_real_name' => $this->mRealName
,
4205 'user_token' => strval( $this->mToken
),
4206 'user_registration' => $dbw->timestamp( $this->mRegistration
),
4207 'user_editcount' => 0,
4208 'user_touched' => $dbw->timestamp( $this->mTouched
),
4212 if ( !$dbw->affectedRows() ) {
4213 // Use locking reads to bypass any REPEATABLE-READ snapshot.
4214 $this->mId
= $dbw->selectField(
4217 [ 'user_name' => $this->mName
],
4219 [ 'LOCK IN SHARE MODE' ]
4223 if ( $this->loadFromDatabase( self
::READ_LOCKING
) ) {
4228 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
4229 "to insert user '{$this->mName}' row, but it was not present in select!" );
4231 return Status
::newFatal( 'userexists' );
4233 $this->mId
= $dbw->insertId();
4234 self
::$idCacheByName[$this->mName
] = $this->mId
;
4236 // Clear instance cache other than user table data, which is already accurate
4237 $this->clearInstanceCache();
4239 $this->saveOptions();
4240 return Status
::newGood();
4244 * If this user is logged-in and blocked,
4245 * block any IP address they've successfully logged in from.
4246 * @return bool A block was spread
4248 public function spreadAnyEditBlock() {
4249 if ( $this->isLoggedIn() && $this->isBlocked() ) {
4250 return $this->spreadBlock();
4257 * If this (non-anonymous) user is blocked,
4258 * block the IP address they've successfully logged in from.
4259 * @return bool A block was spread
4261 protected function spreadBlock() {
4262 wfDebug( __METHOD__
. "()\n" );
4264 if ( $this->mId
== 0 ) {
4268 $userblock = Block
::newFromTarget( $this->getName() );
4269 if ( !$userblock ) {
4273 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
4277 * Get whether the user is explicitly blocked from account creation.
4278 * @return bool|Block
4280 public function isBlockedFromCreateAccount() {
4281 $this->getBlockedStatus();
4282 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
4283 return $this->mBlock
;
4286 # T15611: if the IP address the user is trying to create an account from is
4287 # blocked with createaccount disabled, prevent new account creation there even
4288 # when the user is logged in
4289 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
4290 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
4292 return $this->mBlockedFromCreateAccount
instanceof Block
4293 && $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
4294 ?
$this->mBlockedFromCreateAccount
4299 * Get whether the user is blocked from using Special:Emailuser.
4302 public function isBlockedFromEmailuser() {
4303 $this->getBlockedStatus();
4304 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
4308 * Get whether the user is allowed to create an account.
4311 public function isAllowedToCreateAccount() {
4312 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
4316 * Get this user's personal page title.
4318 * @return Title User's personal page title
4320 public function getUserPage() {
4321 return Title
::makeTitle( NS_USER
, $this->getName() );
4325 * Get this user's talk page title.
4327 * @return Title User's talk page title
4329 public function getTalkPage() {
4330 $title = $this->getUserPage();
4331 return $title->getTalkPage();
4335 * Determine whether the user is a newbie. Newbies are either
4336 * anonymous IPs, or the most recently created accounts.
4339 public function isNewbie() {
4340 return !$this->isAllowed( 'autoconfirmed' );
4344 * Check to see if the given clear-text password is one of the accepted passwords
4345 * @deprecated since 1.27, use AuthManager instead
4346 * @param string $password User password
4347 * @return bool True if the given password is correct, otherwise False
4349 public function checkPassword( $password ) {
4350 $manager = AuthManager
::singleton();
4351 $reqs = AuthenticationRequest
::loadRequestsFromSubmission(
4352 $manager->getAuthenticationRequests( AuthManager
::ACTION_LOGIN
),
4354 'username' => $this->getName(),
4355 'password' => $password,
4358 $res = AuthManager
::singleton()->beginAuthentication( $reqs, 'null:' );
4359 switch ( $res->status
) {
4360 case AuthenticationResponse
::PASS
:
4362 case AuthenticationResponse
::FAIL
:
4363 // Hope it's not a PreAuthenticationProvider that failed...
4364 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
4365 ->info( __METHOD__
. ': Authentication failed: ' . $res->message
->plain() );
4368 throw new BadMethodCallException(
4369 'AuthManager returned a response unsupported by ' . __METHOD__
4375 * Check if the given clear-text password matches the temporary password
4376 * sent by e-mail for password reset operations.
4378 * @deprecated since 1.27, use AuthManager instead
4379 * @param string $plaintext
4380 * @return bool True if matches, false otherwise
4382 public function checkTemporaryPassword( $plaintext ) {
4383 // Can't check the temporary password individually.
4384 return $this->checkPassword( $plaintext );
4388 * Initialize (if necessary) and return a session token value
4389 * which can be used in edit forms to show that the user's
4390 * login credentials aren't being hijacked with a foreign form
4394 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4395 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4396 * @return MediaWiki\Session\Token The new edit token
4398 public function getEditTokenObject( $salt = '', $request = null ) {
4399 if ( $this->isAnon() ) {
4400 return new LoggedOutEditToken();
4404 $request = $this->getRequest();
4406 return $request->getSession()->getToken( $salt );
4410 * Initialize (if necessary) and return a session token value
4411 * which can be used in edit forms to show that the user's
4412 * login credentials aren't being hijacked with a foreign form
4415 * The $salt for 'edit' and 'csrf' tokens is the default (empty string).
4418 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4419 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4420 * @return string The new edit token
4422 public function getEditToken( $salt = '', $request = null ) {
4423 return $this->getEditTokenObject( $salt, $request )->toString();
4427 * Get the embedded timestamp from a token.
4428 * @deprecated since 1.27, use \MediaWiki\Session\Token::getTimestamp instead.
4429 * @param string $val Input token
4432 public static function getEditTokenTimestamp( $val ) {
4433 wfDeprecated( __METHOD__
, '1.27' );
4434 return MediaWiki\Session\Token
::getTimestamp( $val );
4438 * Check given value against the token value stored in the session.
4439 * A match should confirm that the form was submitted from the
4440 * user's own login session, not a form submission from a third-party
4443 * @param string $val Input value to compare
4444 * @param string $salt Optional function-specific data for hashing
4445 * @param WebRequest|null $request Object to use or null to use $wgRequest
4446 * @param int $maxage Fail tokens older than this, in seconds
4447 * @return bool Whether the token matches
4449 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4450 return $this->getEditTokenObject( $salt, $request )->match( $val, $maxage );
4454 * Check given value against the token value stored in the session,
4455 * ignoring the suffix.
4457 * @param string $val Input value to compare
4458 * @param string $salt Optional function-specific data for hashing
4459 * @param WebRequest|null $request Object to use or null to use $wgRequest
4460 * @param int $maxage Fail tokens older than this, in seconds
4461 * @return bool Whether the token matches
4463 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4464 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . Token
::SUFFIX
;
4465 return $this->matchEditToken( $val, $salt, $request, $maxage );
4469 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4470 * mail to the user's given address.
4472 * @param string $type Message to send, either "created", "changed" or "set"
4475 public function sendConfirmationMail( $type = 'created' ) {
4477 $expiration = null; // gets passed-by-ref and defined in next line.
4478 $token = $this->confirmationToken( $expiration );
4479 $url = $this->confirmationTokenUrl( $token );
4480 $invalidateURL = $this->invalidationTokenUrl( $token );
4481 $this->saveSettings();
4483 if ( $type == 'created' ||
$type === false ) {
4484 $message = 'confirmemail_body';
4485 } elseif ( $type === true ) {
4486 $message = 'confirmemail_body_changed';
4488 // Messages: confirmemail_body_changed, confirmemail_body_set
4489 $message = 'confirmemail_body_' . $type;
4492 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4493 wfMessage( $message,
4494 $this->getRequest()->getIP(),
4497 $wgLang->userTimeAndDate( $expiration, $this ),
4499 $wgLang->userDate( $expiration, $this ),
4500 $wgLang->userTime( $expiration, $this ) )->text() );
4504 * Send an e-mail to this user's account. Does not check for
4505 * confirmed status or validity.
4507 * @param string $subject Message subject
4508 * @param string $body Message body
4509 * @param User|null $from Optional sending user; if unspecified, default
4510 * $wgPasswordSender will be used.
4511 * @param string $replyto Reply-To address
4514 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4515 global $wgPasswordSender;
4517 if ( $from instanceof User
) {
4518 $sender = MailAddress
::newFromUser( $from );
4520 $sender = new MailAddress( $wgPasswordSender,
4521 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4523 $to = MailAddress
::newFromUser( $this );
4525 return UserMailer
::send( $to, $sender, $subject, $body, [
4526 'replyTo' => $replyto,
4531 * Generate, store, and return a new e-mail confirmation code.
4532 * A hash (unsalted, since it's used as a key) is stored.
4534 * @note Call saveSettings() after calling this function to commit
4535 * this change to the database.
4537 * @param string &$expiration Accepts the expiration time
4538 * @return string New token
4540 protected function confirmationToken( &$expiration ) {
4541 global $wgUserEmailConfirmationTokenExpiry;
4543 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4544 $expiration = wfTimestamp( TS_MW
, $expires );
4546 $token = MWCryptRand
::generateHex( 32 );
4547 $hash = md5( $token );
4548 $this->mEmailToken
= $hash;
4549 $this->mEmailTokenExpires
= $expiration;
4554 * Return a URL the user can use to confirm their email address.
4555 * @param string $token Accepts the email confirmation token
4556 * @return string New token URL
4558 protected function confirmationTokenUrl( $token ) {
4559 return $this->getTokenUrl( 'ConfirmEmail', $token );
4563 * Return a URL the user can use to invalidate their email address.
4564 * @param string $token Accepts the email confirmation token
4565 * @return string New token URL
4567 protected function invalidationTokenUrl( $token ) {
4568 return $this->getTokenUrl( 'InvalidateEmail', $token );
4572 * Internal function to format the e-mail validation/invalidation URLs.
4573 * This uses a quickie hack to use the
4574 * hardcoded English names of the Special: pages, for ASCII safety.
4576 * @note Since these URLs get dropped directly into emails, using the
4577 * short English names avoids insanely long URL-encoded links, which
4578 * also sometimes can get corrupted in some browsers/mailers
4579 * (T8957 with Gmail and Internet Explorer).
4581 * @param string $page Special page
4582 * @param string $token
4583 * @return string Formatted URL
4585 protected function getTokenUrl( $page, $token ) {
4586 // Hack to bypass localization of 'Special:'
4587 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4588 return $title->getCanonicalURL();
4592 * Mark the e-mail address confirmed.
4594 * @note Call saveSettings() after calling this function to commit the change.
4598 public function confirmEmail() {
4599 // Check if it's already confirmed, so we don't touch the database
4600 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4601 if ( !$this->isEmailConfirmed() ) {
4602 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4603 Hooks
::run( 'ConfirmEmailComplete', [ $this ] );
4609 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4610 * address if it was already confirmed.
4612 * @note Call saveSettings() after calling this function to commit the change.
4613 * @return bool Returns true
4615 public function invalidateEmail() {
4617 $this->mEmailToken
= null;
4618 $this->mEmailTokenExpires
= null;
4619 $this->setEmailAuthenticationTimestamp( null );
4621 Hooks
::run( 'InvalidateEmailComplete', [ $this ] );
4626 * Set the e-mail authentication timestamp.
4627 * @param string $timestamp TS_MW timestamp
4629 public function setEmailAuthenticationTimestamp( $timestamp ) {
4631 $this->mEmailAuthenticated
= $timestamp;
4632 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
4636 * Is this user allowed to send e-mails within limits of current
4637 * site configuration?
4640 public function canSendEmail() {
4641 global $wgEnableEmail, $wgEnableUserEmail;
4642 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4645 $canSend = $this->isEmailConfirmed();
4646 // Avoid PHP 7.1 warning of passing $this by reference
4648 Hooks
::run( 'UserCanSendEmail', [ &$user, &$canSend ] );
4653 * Is this user allowed to receive e-mails within limits of current
4654 * site configuration?
4657 public function canReceiveEmail() {
4658 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4662 * Is this user's e-mail address valid-looking and confirmed within
4663 * limits of the current site configuration?
4665 * @note If $wgEmailAuthentication is on, this may require the user to have
4666 * confirmed their address by returning a code or using a password
4667 * sent to the address from the wiki.
4671 public function isEmailConfirmed() {
4672 global $wgEmailAuthentication;
4674 // Avoid PHP 7.1 warning of passing $this by reference
4677 if ( Hooks
::run( 'EmailConfirmed', [ &$user, &$confirmed ] ) ) {
4678 if ( $this->isAnon() ) {
4681 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4684 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4694 * Check whether there is an outstanding request for e-mail confirmation.
4697 public function isEmailConfirmationPending() {
4698 global $wgEmailAuthentication;
4699 return $wgEmailAuthentication &&
4700 !$this->isEmailConfirmed() &&
4701 $this->mEmailToken
&&
4702 $this->mEmailTokenExpires
> wfTimestamp();
4706 * Get the timestamp of account creation.
4708 * @return string|bool|null Timestamp of account creation, false for
4709 * non-existent/anonymous user accounts, or null if existing account
4710 * but information is not in database.
4712 public function getRegistration() {
4713 if ( $this->isAnon() ) {
4717 return $this->mRegistration
;
4721 * Get the timestamp of the first edit
4723 * @return string|bool Timestamp of first edit, or false for
4724 * non-existent/anonymous user accounts.
4726 public function getFirstEditTimestamp() {
4727 if ( $this->getId() == 0 ) {
4728 return false; // anons
4730 $dbr = wfGetDB( DB_REPLICA
);
4731 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4732 [ 'rev_user' => $this->getId() ],
4734 [ 'ORDER BY' => 'rev_timestamp ASC' ]
4737 return false; // no edits
4739 return wfTimestamp( TS_MW
, $time );
4743 * Get the permissions associated with a given list of groups
4745 * @param array $groups Array of Strings List of internal group names
4746 * @return array Array of Strings List of permission key names for given groups combined
4748 public static function getGroupPermissions( $groups ) {
4749 global $wgGroupPermissions, $wgRevokePermissions;
4751 // grant every granted permission first
4752 foreach ( $groups as $group ) {
4753 if ( isset( $wgGroupPermissions[$group] ) ) {
4754 $rights = array_merge( $rights,
4755 // array_filter removes empty items
4756 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4759 // now revoke the revoked permissions
4760 foreach ( $groups as $group ) {
4761 if ( isset( $wgRevokePermissions[$group] ) ) {
4762 $rights = array_diff( $rights,
4763 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4766 return array_unique( $rights );
4770 * Get all the groups who have a given permission
4772 * @param string $role Role to check
4773 * @return array Array of Strings List of internal group names with the given permission
4775 public static function getGroupsWithPermission( $role ) {
4776 global $wgGroupPermissions;
4777 $allowedGroups = [];
4778 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4779 if ( self
::groupHasPermission( $group, $role ) ) {
4780 $allowedGroups[] = $group;
4783 return $allowedGroups;
4787 * Check, if the given group has the given permission
4789 * If you're wanting to check whether all users have a permission, use
4790 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4794 * @param string $group Group to check
4795 * @param string $role Role to check
4798 public static function groupHasPermission( $group, $role ) {
4799 global $wgGroupPermissions, $wgRevokePermissions;
4800 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4801 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4805 * Check if all users may be assumed to have the given permission
4807 * We generally assume so if the right is granted to '*' and isn't revoked
4808 * on any group. It doesn't attempt to take grants or other extension
4809 * limitations on rights into account in the general case, though, as that
4810 * would require it to always return false and defeat the purpose.
4811 * Specifically, session-based rights restrictions (such as OAuth or bot
4812 * passwords) are applied based on the current session.
4815 * @param string $right Right to check
4818 public static function isEveryoneAllowed( $right ) {
4819 global $wgGroupPermissions, $wgRevokePermissions;
4822 // Use the cached results, except in unit tests which rely on
4823 // being able change the permission mid-request
4824 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4825 return $cache[$right];
4828 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4829 $cache[$right] = false;
4833 // If it's revoked anywhere, then everyone doesn't have it
4834 foreach ( $wgRevokePermissions as $rights ) {
4835 if ( isset( $rights[$right] ) && $rights[$right] ) {
4836 $cache[$right] = false;
4841 // Remove any rights that aren't allowed to the global-session user,
4842 // unless there are no sessions for this endpoint.
4843 if ( !defined( 'MW_NO_SESSION' ) ) {
4844 $allowedRights = SessionManager
::getGlobalSession()->getAllowedUserRights();
4845 if ( $allowedRights !== null && !in_array( $right, $allowedRights, true ) ) {
4846 $cache[$right] = false;
4851 // Allow extensions to say false
4852 if ( !Hooks
::run( 'UserIsEveryoneAllowed', [ $right ] ) ) {
4853 $cache[$right] = false;
4857 $cache[$right] = true;
4862 * Get the localized descriptive name for a group, if it exists
4863 * @deprecated since 1.29 Use UserGroupMembership::getGroupName instead
4865 * @param string $group Internal group name
4866 * @return string Localized descriptive group name
4868 public static function getGroupName( $group ) {
4869 wfDeprecated( __METHOD__
, '1.29' );
4870 return UserGroupMembership
::getGroupName( $group );
4874 * Get the localized descriptive name for a member of a group, if it exists
4875 * @deprecated since 1.29 Use UserGroupMembership::getGroupMemberName instead
4877 * @param string $group Internal group name
4878 * @param string $username Username for gender (since 1.19)
4879 * @return string Localized name for group member
4881 public static function getGroupMember( $group, $username = '#' ) {
4882 wfDeprecated( __METHOD__
, '1.29' );
4883 return UserGroupMembership
::getGroupMemberName( $group, $username );
4887 * Return the set of defined explicit groups.
4888 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4889 * are not included, as they are defined automatically, not in the database.
4890 * @return array Array of internal group names
4892 public static function getAllGroups() {
4893 global $wgGroupPermissions, $wgRevokePermissions;
4895 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4896 self
::getImplicitGroups()
4901 * Get a list of all available permissions.
4902 * @return string[] Array of permission names
4904 public static function getAllRights() {
4905 if ( self
::$mAllRights === false ) {
4906 global $wgAvailableRights;
4907 if ( count( $wgAvailableRights ) ) {
4908 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
4910 self
::$mAllRights = self
::$mCoreRights;
4912 Hooks
::run( 'UserGetAllRights', [ &self
::$mAllRights ] );
4914 return self
::$mAllRights;
4918 * Get a list of implicit groups
4919 * @return array Array of Strings Array of internal group names
4921 public static function getImplicitGroups() {
4922 global $wgImplicitGroups;
4924 $groups = $wgImplicitGroups;
4925 # Deprecated, use $wgImplicitGroups instead
4926 Hooks
::run( 'UserGetImplicitGroups', [ &$groups ], '1.25' );
4932 * Get the title of a page describing a particular group
4933 * @deprecated since 1.29 Use UserGroupMembership::getGroupPage instead
4935 * @param string $group Internal group name
4936 * @return Title|bool Title of the page if it exists, false otherwise
4938 public static function getGroupPage( $group ) {
4939 wfDeprecated( __METHOD__
, '1.29' );
4940 return UserGroupMembership
::getGroupPage( $group );
4944 * Create a link to the group in HTML, if available;
4945 * else return the group name.
4946 * @deprecated since 1.29 Use UserGroupMembership::getLink instead, or
4947 * make the link yourself if you need custom text
4949 * @param string $group Internal name of the group
4950 * @param string $text The text of the link
4951 * @return string HTML link to the group
4953 public static function makeGroupLinkHTML( $group, $text = '' ) {
4954 wfDeprecated( __METHOD__
, '1.29' );
4956 if ( $text == '' ) {
4957 $text = UserGroupMembership
::getGroupName( $group );
4959 $title = UserGroupMembership
::getGroupPage( $group );
4961 return MediaWikiServices
::getInstance()
4962 ->getLinkRenderer()->makeLink( $title, $text );
4964 return htmlspecialchars( $text );
4969 * Create a link to the group in Wikitext, if available;
4970 * else return the group name.
4971 * @deprecated since 1.29 Use UserGroupMembership::getLink instead, or
4972 * make the link yourself if you need custom text
4974 * @param string $group Internal name of the group
4975 * @param string $text The text of the link
4976 * @return string Wikilink to the group
4978 public static function makeGroupLinkWiki( $group, $text = '' ) {
4979 wfDeprecated( __METHOD__
, '1.29' );
4981 if ( $text == '' ) {
4982 $text = UserGroupMembership
::getGroupName( $group );
4984 $title = UserGroupMembership
::getGroupPage( $group );
4986 $page = $title->getFullText();
4987 return "[[$page|$text]]";
4994 * Returns an array of the groups that a particular group can add/remove.
4996 * @param string $group The group to check for whether it can add/remove
4997 * @return array Array( 'add' => array( addablegroups ),
4998 * 'remove' => array( removablegroups ),
4999 * 'add-self' => array( addablegroups to self),
5000 * 'remove-self' => array( removable groups from self) )
5002 public static function changeableByGroup( $group ) {
5003 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
5012 if ( empty( $wgAddGroups[$group] ) ) {
5013 // Don't add anything to $groups
5014 } elseif ( $wgAddGroups[$group] === true ) {
5015 // You get everything
5016 $groups['add'] = self
::getAllGroups();
5017 } elseif ( is_array( $wgAddGroups[$group] ) ) {
5018 $groups['add'] = $wgAddGroups[$group];
5021 // Same thing for remove
5022 if ( empty( $wgRemoveGroups[$group] ) ) {
5024 } elseif ( $wgRemoveGroups[$group] === true ) {
5025 $groups['remove'] = self
::getAllGroups();
5026 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
5027 $groups['remove'] = $wgRemoveGroups[$group];
5030 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
5031 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
5032 foreach ( $wgGroupsAddToSelf as $key => $value ) {
5033 if ( is_int( $key ) ) {
5034 $wgGroupsAddToSelf['user'][] = $value;
5039 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
5040 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
5041 if ( is_int( $key ) ) {
5042 $wgGroupsRemoveFromSelf['user'][] = $value;
5047 // Now figure out what groups the user can add to him/herself
5048 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
5050 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
5051 // No idea WHY this would be used, but it's there
5052 $groups['add-self'] = self
::getAllGroups();
5053 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
5054 $groups['add-self'] = $wgGroupsAddToSelf[$group];
5057 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
5059 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
5060 $groups['remove-self'] = self
::getAllGroups();
5061 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
5062 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
5069 * Returns an array of groups that this user can add and remove
5070 * @return array Array( 'add' => array( addablegroups ),
5071 * 'remove' => array( removablegroups ),
5072 * 'add-self' => array( addablegroups to self),
5073 * 'remove-self' => array( removable groups from self) )
5075 public function changeableGroups() {
5076 if ( $this->isAllowed( 'userrights' ) ) {
5077 // This group gives the right to modify everything (reverse-
5078 // compatibility with old "userrights lets you change
5080 // Using array_merge to make the groups reindexed
5081 $all = array_merge( self
::getAllGroups() );
5090 // Okay, it's not so simple, we will have to go through the arrays
5097 $addergroups = $this->getEffectiveGroups();
5099 foreach ( $addergroups as $addergroup ) {
5100 $groups = array_merge_recursive(
5101 $groups, $this->changeableByGroup( $addergroup )
5103 $groups['add'] = array_unique( $groups['add'] );
5104 $groups['remove'] = array_unique( $groups['remove'] );
5105 $groups['add-self'] = array_unique( $groups['add-self'] );
5106 $groups['remove-self'] = array_unique( $groups['remove-self'] );
5112 * Deferred version of incEditCountImmediate()
5114 * This function, rather than incEditCountImmediate(), should be used for
5115 * most cases as it avoids potential deadlocks caused by concurrent editing.
5117 public function incEditCount() {
5118 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle(
5120 $this->incEditCountImmediate();
5127 * Increment the user's edit-count field.
5128 * Will have no effect for anonymous users.
5131 public function incEditCountImmediate() {
5132 if ( $this->isAnon() ) {
5136 $dbw = wfGetDB( DB_MASTER
);
5137 // No rows will be "affected" if user_editcount is NULL
5140 [ 'user_editcount=user_editcount+1' ],
5141 [ 'user_id' => $this->getId(), 'user_editcount IS NOT NULL' ],
5144 // Lazy initialization check...
5145 if ( $dbw->affectedRows() == 0 ) {
5146 // Now here's a goddamn hack...
5147 $dbr = wfGetDB( DB_REPLICA
);
5148 if ( $dbr !== $dbw ) {
5149 // If we actually have a replica DB server, the count is
5150 // at least one behind because the current transaction
5151 // has not been committed and replicated.
5152 $this->mEditCount
= $this->initEditCount( 1 );
5154 // But if DB_REPLICA is selecting the master, then the
5155 // count we just read includes the revision that was
5156 // just added in the working transaction.
5157 $this->mEditCount
= $this->initEditCount();
5160 if ( $this->mEditCount
=== null ) {
5161 $this->getEditCount();
5162 $dbr = wfGetDB( DB_REPLICA
);
5163 $this->mEditCount +
= ( $dbr !== $dbw ) ?
1 : 0;
5165 $this->mEditCount++
;
5168 // Edit count in user cache too
5169 $this->invalidateCache();
5173 * Initialize user_editcount from data out of the revision table
5175 * @param int $add Edits to add to the count from the revision table
5176 * @return int Number of edits
5178 protected function initEditCount( $add = 0 ) {
5179 // Pull from a replica DB to be less cruel to servers
5180 // Accuracy isn't the point anyway here
5181 $dbr = wfGetDB( DB_REPLICA
);
5182 $count = (int)$dbr->selectField(
5185 [ 'rev_user' => $this->getId() ],
5188 $count = $count +
$add;
5190 $dbw = wfGetDB( DB_MASTER
);
5193 [ 'user_editcount' => $count ],
5194 [ 'user_id' => $this->getId() ],
5202 * Get the description of a given right
5205 * @param string $right Right to query
5206 * @return string Localized description of the right
5208 public static function getRightDescription( $right ) {
5209 $key = "right-$right";
5210 $msg = wfMessage( $key );
5211 return $msg->isDisabled() ?
$right : $msg->text();
5215 * Get the name of a given grant
5218 * @param string $grant Grant to query
5219 * @return string Localized name of the grant
5221 public static function getGrantName( $grant ) {
5222 $key = "grant-$grant";
5223 $msg = wfMessage( $key );
5224 return $msg->isDisabled() ?
$grant : $msg->text();
5228 * Add a newuser log entry for this user.
5229 * Before 1.19 the return value was always true.
5231 * @deprecated since 1.27, AuthManager handles logging
5232 * @param string|bool $action Account creation type.
5233 * - String, one of the following values:
5234 * - 'create' for an anonymous user creating an account for himself.
5235 * This will force the action's performer to be the created user itself,
5236 * no matter the value of $wgUser
5237 * - 'create2' for a logged in user creating an account for someone else
5238 * - 'byemail' when the created user will receive its password by e-mail
5239 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
5240 * - Boolean means whether the account was created by e-mail (deprecated):
5241 * - true will be converted to 'byemail'
5242 * - false will be converted to 'create' if this object is the same as
5243 * $wgUser and to 'create2' otherwise
5244 * @param string $reason User supplied reason
5247 public function addNewUserLogEntry( $action = false, $reason = '' ) {
5248 return true; // disabled
5252 * Add an autocreate newuser log entry for this user
5253 * Used by things like CentralAuth and perhaps other authplugins.
5254 * Consider calling addNewUserLogEntry() directly instead.
5256 * @deprecated since 1.27, AuthManager handles logging
5259 public function addNewUserLogEntryAutoCreate() {
5260 $this->addNewUserLogEntry( 'autocreate' );
5266 * Load the user options either from cache, the database or an array
5268 * @param array $data Rows for the current user out of the user_properties table
5270 protected function loadOptions( $data = null ) {
5275 if ( $this->mOptionsLoaded
) {
5279 $this->mOptions
= self
::getDefaultOptions();
5281 if ( !$this->getId() ) {
5282 // For unlogged-in users, load language/variant options from request.
5283 // There's no need to do it for logged-in users: they can set preferences,
5284 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5285 // so don't override user's choice (especially when the user chooses site default).
5286 $variant = $wgContLang->getDefaultVariant();
5287 $this->mOptions
['variant'] = $variant;
5288 $this->mOptions
['language'] = $variant;
5289 $this->mOptionsLoaded
= true;
5293 // Maybe load from the object
5294 if ( !is_null( $this->mOptionOverrides
) ) {
5295 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5296 foreach ( $this->mOptionOverrides
as $key => $value ) {
5297 $this->mOptions
[$key] = $value;
5300 if ( !is_array( $data ) ) {
5301 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5302 // Load from database
5303 $dbr = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
5304 ?
wfGetDB( DB_MASTER
)
5305 : wfGetDB( DB_REPLICA
);
5307 $res = $dbr->select(
5309 [ 'up_property', 'up_value' ],
5310 [ 'up_user' => $this->getId() ],
5314 $this->mOptionOverrides
= [];
5316 foreach ( $res as $row ) {
5317 // Convert '0' to 0. PHP's boolean conversion considers them both
5318 // false, but e.g. JavaScript considers the former as true.
5319 // @todo: T54542 Somehow determine the desired type (string/int/bool)
5320 // and convert all values here.
5321 if ( $row->up_value
=== '0' ) {
5324 $data[$row->up_property
] = $row->up_value
;
5328 // Convert the email blacklist from a new line delimited string
5329 // to an array of ids.
5330 if ( isset( $data['email-blacklist'] ) && $data['email-blacklist'] ) {
5331 $data['email-blacklist'] = array_map( 'intval', explode( "\n", $data['email-blacklist'] ) );
5334 foreach ( $data as $property => $value ) {
5335 $this->mOptionOverrides
[$property] = $value;
5336 $this->mOptions
[$property] = $value;
5340 $this->mOptionsLoaded
= true;
5342 Hooks
::run( 'UserLoadOptions', [ $this, &$this->mOptions
] );
5346 * Saves the non-default options for this user, as previously set e.g. via
5347 * setOption(), in the database's "user_properties" (preferences) table.
5348 * Usually used via saveSettings().
5350 protected function saveOptions() {
5351 $this->loadOptions();
5353 // Not using getOptions(), to keep hidden preferences in database
5354 $saveOptions = $this->mOptions
;
5356 // Convert usernames to ids.
5357 if ( isset( $this->mOptions
['email-blacklist'] ) ) {
5358 if ( $this->mOptions
['email-blacklist'] ) {
5359 $value = $this->mOptions
['email-blacklist'];
5360 // Email Blacklist may be an array of ids or a string of new line
5361 // delimnated user names.
5362 if ( is_array( $value ) ) {
5363 $ids = array_filter( $value, 'is_numeric' );
5365 $lookup = CentralIdLookup
::factory();
5366 $ids = $lookup->centralIdsFromNames( explode( "\n", $value ), $this );
5368 $this->mOptions
['email-blacklist'] = $ids;
5369 $saveOptions['email-blacklist'] = implode( "\n", $this->mOptions
['email-blacklist'] );
5371 // If the blacklist is empty, set it to null rather than an empty string.
5372 $this->mOptions
['email-blacklist'] = null;
5376 // Allow hooks to abort, for instance to save to a global profile.
5377 // Reset options to default state before saving.
5378 if ( !Hooks
::run( 'UserSaveOptions', [ $this, &$saveOptions ] ) ) {
5382 $userId = $this->getId();
5384 $insert_rows = []; // all the new preference rows
5385 foreach ( $saveOptions as $key => $value ) {
5386 // Don't bother storing default values
5387 $defaultOption = self
::getDefaultOption( $key );
5388 if ( ( $defaultOption === null && $value !== false && $value !== null )
5389 ||
$value != $defaultOption
5392 'up_user' => $userId,
5393 'up_property' => $key,
5394 'up_value' => $value,
5399 $dbw = wfGetDB( DB_MASTER
);
5401 $res = $dbw->select( 'user_properties',
5402 [ 'up_property', 'up_value' ], [ 'up_user' => $userId ], __METHOD__
);
5404 // Find prior rows that need to be removed or updated. These rows will
5405 // all be deleted (the latter so that INSERT IGNORE applies the new values).
5407 foreach ( $res as $row ) {
5408 if ( !isset( $saveOptions[$row->up_property
] )
5409 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
5411 $keysDelete[] = $row->up_property
;
5415 if ( count( $keysDelete ) ) {
5416 // Do the DELETE by PRIMARY KEY for prior rows.
5417 // In the past a very large portion of calls to this function are for setting
5418 // 'rememberpassword' for new accounts (a preference that has since been removed).
5419 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5420 // caused gap locks on [max user ID,+infinity) which caused high contention since
5421 // updates would pile up on each other as they are for higher (newer) user IDs.
5422 // It might not be necessary these days, but it shouldn't hurt either.
5423 $dbw->delete( 'user_properties',
5424 [ 'up_user' => $userId, 'up_property' => $keysDelete ], __METHOD__
);
5426 // Insert the new preference rows
5427 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, [ 'IGNORE' ] );
5431 * Lazily instantiate and return a factory object for making passwords
5433 * @deprecated since 1.27, create a PasswordFactory directly instead
5434 * @return PasswordFactory
5436 public static function getPasswordFactory() {
5437 wfDeprecated( __METHOD__
, '1.27' );
5438 $ret = new PasswordFactory();
5439 $ret->init( RequestContext
::getMain()->getConfig() );
5444 * Provide an array of HTML5 attributes to put on an input element
5445 * intended for the user to enter a new password. This may include
5446 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
5448 * Do *not* use this when asking the user to enter his current password!
5449 * Regardless of configuration, users may have invalid passwords for whatever
5450 * reason (e.g., they were set before requirements were tightened up).
5451 * Only use it when asking for a new password, like on account creation or
5454 * Obviously, you still need to do server-side checking.
5456 * NOTE: A combination of bugs in various browsers means that this function
5457 * actually just returns array() unconditionally at the moment. May as
5458 * well keep it around for when the browser bugs get fixed, though.
5460 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
5462 * @deprecated since 1.27
5463 * @return array Array of HTML attributes suitable for feeding to
5464 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
5465 * That will get confused by the boolean attribute syntax used.)
5467 public static function passwordChangeInputAttribs() {
5468 global $wgMinimalPasswordLength;
5470 if ( $wgMinimalPasswordLength == 0 ) {
5474 # Note that the pattern requirement will always be satisfied if the
5475 # input is empty, so we need required in all cases.
5477 # @todo FIXME: T25769: This needs to not claim the password is required
5478 # if e-mail confirmation is being used. Since HTML5 input validation
5479 # is b0rked anyway in some browsers, just return nothing. When it's
5480 # re-enabled, fix this code to not output required for e-mail
5482 # $ret = array( 'required' );
5485 # We can't actually do this right now, because Opera 9.6 will print out
5486 # the entered password visibly in its error message! When other
5487 # browsers add support for this attribute, or Opera fixes its support,
5488 # we can add support with a version check to avoid doing this on Opera
5489 # versions where it will be a problem. Reported to Opera as
5490 # DSK-262266, but they don't have a public bug tracker for us to follow.
5492 if ( $wgMinimalPasswordLength > 1 ) {
5493 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
5494 $ret['title'] = wfMessage( 'passwordtooshort' )
5495 ->numParams( $wgMinimalPasswordLength )->text();
5503 * Return the list of user fields that should be selected to create
5504 * a new user object.
5505 * @deprecated since 1.31, use self::getQueryInfo() instead.
5508 public static function selectFields() {
5509 wfDeprecated( __METHOD__
, '1.31' );
5517 'user_email_authenticated',
5519 'user_email_token_expires',
5520 'user_registration',
5526 * Return the tables, fields, and join conditions to be selected to create
5527 * a new user object.
5529 * @return array With three keys:
5530 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
5531 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
5532 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
5534 public static function getQueryInfo() {
5536 'tables' => [ 'user' ],
5544 'user_email_authenticated',
5546 'user_email_token_expires',
5547 'user_registration',
5555 * Factory function for fatal permission-denied errors
5558 * @param string $permission User right required
5561 static function newFatalPermissionDeniedStatus( $permission ) {
5565 foreach ( self
::getGroupsWithPermission( $permission ) as $group ) {
5566 $groups[] = UserGroupMembership
::getLink( $group, RequestContext
::getMain(), 'wiki' );
5570 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5572 return Status
::newFatal( 'badaccess-group0' );
5577 * Get a new instance of this user that was loaded from the master via a locking read
5579 * Use this instead of the main context User when updating that user. This avoids races
5580 * where that user was loaded from a replica DB or even the master but without proper locks.
5582 * @return User|null Returns null if the user was not found in the DB
5585 public function getInstanceForUpdate() {
5586 if ( !$this->getId() ) {
5587 return null; // anon
5590 $user = self
::newFromId( $this->getId() );
5591 if ( !$user->loadFromId( self
::READ_EXCLUSIVE
) ) {
5599 * Checks if two user objects point to the same user.
5605 public function equals( User
$user ) {
5606 return $this->getName() === $user->getName();