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
24 use MediaWiki\MediaWikiServices
;
25 use MediaWiki\Session\SessionManager
;
26 use MediaWiki\Session\Token
;
27 use MediaWiki\Auth\AuthManager
;
28 use MediaWiki\Auth\AuthenticationResponse
;
29 use MediaWiki\Auth\AuthenticationRequest
;
30 use Wikimedia\ScopedCallback
;
31 use Wikimedia\Rdbms\Database
;
32 use Wikimedia\Rdbms\DBExpectedError
;
35 * String Some punctuation to prevent editing from broken text-mangling proxies.
36 * @deprecated since 1.27, use \MediaWiki\Session\Token::SUFFIX
39 define( 'EDIT_TOKEN_SUFFIX', Token
::SUFFIX
);
42 * The User object encapsulates all of the user-specific settings (user_id,
43 * name, rights, email address, options, last login time). Client
44 * classes use the getXXX() functions to access these fields. These functions
45 * do all the work of determining whether the user is logged in,
46 * whether the requested option can be satisfied from cookies or
47 * whether a database query is needed. Most of the settings needed
48 * for rendering normal pages are set in the cookie to minimize use
51 class User
implements IDBAccessObject
{
53 * @const int Number of characters in user_token field.
55 const TOKEN_LENGTH
= 32;
58 * @const string An invalid value for user_token
60 const INVALID_TOKEN
= '*** INVALID ***';
63 * Global constant made accessible as class constants so that autoloader
65 * @deprecated since 1.27, use \MediaWiki\Session\Token::SUFFIX
67 const EDIT_TOKEN_SUFFIX
= EDIT_TOKEN_SUFFIX
;
70 * @const int Serialized record version.
75 * Exclude user options that are set to their default value.
78 const GETOPTIONS_EXCLUDE_DEFAULTS
= 1;
83 const CHECK_USER_RIGHTS
= true;
88 const IGNORE_USER_RIGHTS
= false;
91 * Array of Strings List of member variables which are saved to the
92 * shared cache (memcached). Any operation which changes the
93 * corresponding database fields must call a cache-clearing function.
96 protected static $mCacheVars = [
104 'mEmailAuthenticated',
106 'mEmailTokenExpires',
111 // user_properties table
116 * Array of Strings Core rights.
117 * Each of these should have a corresponding message of the form
121 protected static $mCoreRights = [
164 'move-categorypages',
165 'move-rootuserpages',
169 'override-export-depth',
191 'userrights-interwiki',
199 * String Cached results of getAllRights()
201 protected static $mAllRights = false;
203 /** Cache variables */
214 /** @var string TS_MW timestamp from the DB */
216 /** @var string TS_MW timestamp from cache */
217 protected $mQuickTouched;
221 public $mEmailAuthenticated;
223 protected $mEmailToken;
225 protected $mEmailTokenExpires;
227 protected $mRegistration;
229 protected $mEditCount;
231 * @var array No longer used since 1.29; use User::getGroups() instead
232 * @deprecated since 1.29
235 /** @var array Associative array of (group name => UserGroupMembership object) */
236 protected $mGroupMemberships;
238 protected $mOptionOverrides;
242 * Bool Whether the cache variables have been loaded.
245 public $mOptionsLoaded;
248 * Array with already loaded items or true if all items have been loaded.
250 protected $mLoadedItems = [];
254 * String Initialization data source if mLoadedItems!==true. May be one of:
255 * - 'defaults' anonymous user initialised from class defaults
256 * - 'name' initialise from mName
257 * - 'id' initialise from mId
258 * - 'session' log in from session if possible
260 * Use the User::newFrom*() family of functions to set this.
265 * Lazy-initialized variables, invalidated with clearInstanceCache
269 protected $mDatePreference;
277 protected $mBlockreason;
279 protected $mEffectiveGroups;
281 protected $mImplicitGroups;
283 protected $mFormerGroups;
285 protected $mGlobalBlock;
293 /** @var WebRequest */
300 protected $mAllowUsertalk;
303 private $mBlockedFromCreateAccount = false;
305 /** @var int User::READ_* constant bitfield used to load data */
306 protected $queryFlagsUsed = self
::READ_NORMAL
;
308 public static $idCacheByName = [];
311 * Lightweight constructor for an anonymous user.
312 * Use the User::newFrom* factory functions for other kinds of users.
316 * @see newFromConfirmationCode()
317 * @see newFromSession()
320 public function __construct() {
321 $this->clearInstanceCache( 'defaults' );
327 public function __toString() {
328 return (string)$this->getName();
332 * Test if it's safe to load this User object.
334 * You should typically check this before using $wgUser or
335 * RequestContext::getUser in a method that might be called before the
336 * system has been fully initialized. If the object is unsafe, you should
337 * use an anonymous user:
339 * $user = $wgUser->isSafeToLoad() ? $wgUser : new User;
345 public function isSafeToLoad() {
346 global $wgFullyInitialised;
348 // The user is safe to load if:
349 // * MW_NO_SESSION is undefined AND $wgFullyInitialised is true (safe to use session data)
350 // * mLoadedItems === true (already loaded)
351 // * mFrom !== 'session' (sessions not involved at all)
353 return ( !defined( 'MW_NO_SESSION' ) && $wgFullyInitialised ) ||
354 $this->mLoadedItems
=== true ||
$this->mFrom
!== 'session';
358 * Load the user table data for this object from the source given by mFrom.
360 * @param int $flags User::READ_* constant bitfield
362 public function load( $flags = self
::READ_NORMAL
) {
363 global $wgFullyInitialised;
365 if ( $this->mLoadedItems
=== true ) {
369 // Set it now to avoid infinite recursion in accessors
370 $oldLoadedItems = $this->mLoadedItems
;
371 $this->mLoadedItems
= true;
372 $this->queryFlagsUsed
= $flags;
374 // If this is called too early, things are likely to break.
375 if ( !$wgFullyInitialised && $this->mFrom
=== 'session' ) {
376 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
377 ->warning( 'User::loadFromSession called before the end of Setup.php', [
378 'exception' => new Exception( 'User::loadFromSession called before the end of Setup.php' ),
380 $this->loadDefaults();
381 $this->mLoadedItems
= $oldLoadedItems;
385 switch ( $this->mFrom
) {
387 $this->loadDefaults();
390 // Make sure this thread sees its own changes
391 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
392 $flags |
= self
::READ_LATEST
;
393 $this->queryFlagsUsed
= $flags;
396 $this->mId
= self
::idFromName( $this->mName
, $flags );
398 // Nonexistent user placeholder object
399 $this->loadDefaults( $this->mName
);
401 $this->loadFromId( $flags );
405 $this->loadFromId( $flags );
408 if ( !$this->loadFromSession() ) {
409 // Loading from session failed. Load defaults.
410 $this->loadDefaults();
412 Hooks
::run( 'UserLoadAfterLoadFromSession', [ $this ] );
415 throw new UnexpectedValueException(
416 "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
421 * Load user table data, given mId has already been set.
422 * @param int $flags User::READ_* constant bitfield
423 * @return bool False if the ID does not exist, true otherwise
425 public function loadFromId( $flags = self
::READ_NORMAL
) {
426 if ( $this->mId
== 0 ) {
427 // Anonymous users are not in the database (don't need cache)
428 $this->loadDefaults();
432 // Try cache (unless this needs data from the master DB).
433 // NOTE: if this thread called saveSettings(), the cache was cleared.
434 $latest = DBAccessObjectUtils
::hasFlags( $flags, self
::READ_LATEST
);
436 if ( !$this->loadFromDatabase( $flags ) ) {
437 // Can't load from ID
441 $this->loadFromCache();
444 $this->mLoadedItems
= true;
445 $this->queryFlagsUsed
= $flags;
452 * @param string $wikiId
455 public static function purge( $wikiId, $userId ) {
456 $cache = ObjectCache
::getMainWANInstance();
457 $key = $cache->makeGlobalKey( 'user', 'id', $wikiId, $userId );
458 $cache->delete( $key );
463 * @param WANObjectCache $cache
466 protected function getCacheKey( WANObjectCache
$cache ) {
467 return $cache->makeGlobalKey( 'user', 'id', wfWikiID(), $this->mId
);
471 * @param WANObjectCache $cache
475 public function getMutableCacheKeys( WANObjectCache
$cache ) {
476 $id = $this->getId();
478 return $id ?
[ $this->getCacheKey( $cache ) ] : [];
482 * Load user data from shared cache, given mId has already been set.
487 protected function loadFromCache() {
488 $cache = ObjectCache
::getMainWANInstance();
489 $data = $cache->getWithSetCallback(
490 $this->getCacheKey( $cache ),
492 function ( $oldValue, &$ttl, array &$setOpts ) use ( $cache ) {
493 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
494 wfDebug( "User: cache miss for user {$this->mId}\n" );
496 $this->loadFromDatabase( self
::READ_NORMAL
);
498 $this->loadOptions();
501 foreach ( self
::$mCacheVars as $name ) {
502 $data[$name] = $this->$name;
505 $ttl = $cache->adaptiveTTL( wfTimestamp( TS_UNIX
, $this->mTouched
), $ttl );
507 // if a user group membership is about to expire, the cache needs to
508 // expire at that time (T163691)
509 foreach ( $this->mGroupMemberships
as $ugm ) {
510 if ( $ugm->getExpiry() ) {
511 $secondsUntilExpiry = wfTimestamp( TS_UNIX
, $ugm->getExpiry() ) - time();
512 if ( $secondsUntilExpiry > 0 && $secondsUntilExpiry < $ttl ) {
513 $ttl = $secondsUntilExpiry;
520 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'version' => self
::VERSION
]
523 // Restore from cache
524 foreach ( self
::$mCacheVars as $name ) {
525 $this->$name = $data[$name];
531 /** @name newFrom*() static factory methods */
535 * Static factory method for creation from username.
537 * This is slightly less efficient than newFromId(), so use newFromId() if
538 * you have both an ID and a name handy.
540 * @param string $name Username, validated by Title::newFromText()
541 * @param string|bool $validate Validate username. Takes the same parameters as
542 * User::getCanonicalName(), except that true is accepted as an alias
543 * for 'valid', for BC.
545 * @return User|bool User object, or false if the username is invalid
546 * (e.g. if it contains illegal characters or is an IP address). If the
547 * username is not present in the database, the result will be a user object
548 * with a name, zero user ID and default settings.
550 public static function newFromName( $name, $validate = 'valid' ) {
551 if ( $validate === true ) {
554 $name = self
::getCanonicalName( $name, $validate );
555 if ( $name === false ) {
558 // Create unloaded user object
562 $u->setItemLoaded( 'name' );
568 * Static factory method for creation from a given user ID.
570 * @param int $id Valid user ID
571 * @return User The corresponding User object
573 public static function newFromId( $id ) {
577 $u->setItemLoaded( 'id' );
582 * Factory method to fetch whichever user has a given email confirmation code.
583 * This code is generated when an account is created or its e-mail address
586 * If the code is invalid or has expired, returns NULL.
588 * @param string $code Confirmation code
589 * @param int $flags User::READ_* bitfield
592 public static function newFromConfirmationCode( $code, $flags = 0 ) {
593 $db = ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
594 ?
wfGetDB( DB_MASTER
)
595 : wfGetDB( DB_REPLICA
);
597 $id = $db->selectField(
601 'user_email_token' => md5( $code ),
602 'user_email_token_expires > ' . $db->addQuotes( $db->timestamp() ),
606 return $id ? self
::newFromId( $id ) : null;
610 * Create a new user object using data from session. If the login
611 * credentials are invalid, the result is an anonymous user.
613 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
616 public static function newFromSession( WebRequest
$request = null ) {
618 $user->mFrom
= 'session';
619 $user->mRequest
= $request;
624 * Create a new user object from a user row.
625 * The row should have the following fields from the user table in it:
626 * - either user_name or user_id to load further data if needed (or both)
628 * - all other fields (email, etc.)
629 * It is useless to provide the remaining fields if either user_id,
630 * user_name and user_real_name are not provided because the whole row
631 * will be loaded once more from the database when accessing them.
633 * @param stdClass $row A row from the user table
634 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
637 public static function newFromRow( $row, $data = null ) {
639 $user->loadFromRow( $row, $data );
644 * Static factory method for creation of a "system" user from username.
646 * A "system" user is an account that's used to attribute logged actions
647 * taken by MediaWiki itself, as opposed to a bot or human user. Examples
648 * might include the 'Maintenance script' or 'Conversion script' accounts
649 * used by various scripts in the maintenance/ directory or accounts such
650 * as 'MediaWiki message delivery' used by the MassMessage extension.
652 * This can optionally create the user if it doesn't exist, and "steal" the
653 * account if it does exist.
655 * "Stealing" an existing user is intended to make it impossible for normal
656 * authentication processes to use the account, effectively disabling the
657 * account for normal use:
658 * - Email is invalidated, to prevent account recovery by emailing a
659 * temporary password and to disassociate the account from the existing
661 * - The token is set to a magic invalid value, to kill existing sessions
662 * and to prevent $this->setToken() calls from resetting the token to a
664 * - SessionManager is instructed to prevent new sessions for the user, to
665 * do things like deauthorizing OAuth consumers.
666 * - AuthManager is instructed to revoke access, to invalidate or remove
667 * passwords and other credentials.
669 * @param string $name Username
670 * @param array $options Options are:
671 * - validate: As for User::getCanonicalName(), default 'valid'
672 * - create: Whether to create the user if it doesn't already exist, default true
673 * - steal: Whether to "disable" the account for normal use if it already
674 * exists, default false
678 public static function newSystemUser( $name, $options = [] ) {
680 'validate' => 'valid',
685 $name = self
::getCanonicalName( $name, $options['validate'] );
686 if ( $name === false ) {
690 $dbr = wfGetDB( DB_REPLICA
);
691 $row = $dbr->selectRow(
693 self
::selectFields(),
694 [ 'user_name' => $name ],
698 // Try the master database...
699 $dbw = wfGetDB( DB_MASTER
);
700 $row = $dbw->selectRow(
702 self
::selectFields(),
703 [ 'user_name' => $name ],
709 // No user. Create it?
710 return $options['create']
711 ? self
::createNew( $name, [ 'token' => self
::INVALID_TOKEN
] )
715 $user = self
::newFromRow( $row );
717 // A user is considered to exist as a non-system user if it can
718 // authenticate, or has an email set, or has a non-invalid token.
719 if ( $user->mEmail ||
$user->mToken
!== self
::INVALID_TOKEN ||
720 AuthManager
::singleton()->userCanAuthenticate( $name )
722 // User exists. Steal it?
723 if ( !$options['steal'] ) {
727 AuthManager
::singleton()->revokeAccessForUser( $name );
729 $user->invalidateEmail();
730 $user->mToken
= self
::INVALID_TOKEN
;
731 $user->saveSettings();
732 SessionManager
::singleton()->preventSessionsForUser( $user->getName() );
741 * Get the username corresponding to a given user ID
742 * @param int $id User ID
743 * @return string|bool The corresponding username
745 public static function whoIs( $id ) {
746 return UserCache
::singleton()->getProp( $id, 'name' );
750 * Get the real name of a user given their user ID
752 * @param int $id User ID
753 * @return string|bool The corresponding user's real name
755 public static function whoIsReal( $id ) {
756 return UserCache
::singleton()->getProp( $id, 'real_name' );
760 * Get database id given a user name
761 * @param string $name Username
762 * @param int $flags User::READ_* constant bitfield
763 * @return int|null The corresponding user's ID, or null if user is nonexistent
765 public static function idFromName( $name, $flags = self
::READ_NORMAL
) {
766 $nt = Title
::makeTitleSafe( NS_USER
, $name );
767 if ( is_null( $nt ) ) {
772 if ( !( $flags & self
::READ_LATEST
) && isset( self
::$idCacheByName[$name] ) ) {
773 return self
::$idCacheByName[$name];
776 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
777 $db = wfGetDB( $index );
782 [ 'user_name' => $nt->getText() ],
787 if ( $s === false ) {
790 $result = $s->user_id
;
793 self
::$idCacheByName[$name] = $result;
795 if ( count( self
::$idCacheByName ) > 1000 ) {
796 self
::$idCacheByName = [];
803 * Reset the cache used in idFromName(). For use in tests.
805 public static function resetIdByNameCache() {
806 self
::$idCacheByName = [];
810 * Does the string match an anonymous IP address?
812 * This function exists for username validation, in order to reject
813 * usernames which are similar in form to IP addresses. Strings such
814 * as 300.300.300.300 will return true because it looks like an IP
815 * address, despite not being strictly valid.
817 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
818 * address because the usemod software would "cloak" anonymous IP
819 * addresses like this, if we allowed accounts like this to be created
820 * new users could get the old edits of these anonymous users.
822 * @param string $name Name to match
825 public static function isIP( $name ) {
826 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
827 || IP
::isIPv6( $name );
831 * Is the user an IP range?
836 public function isIPRange() {
837 return IP
::isValidRange( $this->mName
);
841 * Is the input a valid username?
843 * Checks if the input is a valid username, we don't want an empty string,
844 * an IP address, anything that contains slashes (would mess up subpages),
845 * is longer than the maximum allowed username size or doesn't begin with
848 * @param string $name Name to match
851 public static function isValidUserName( $name ) {
852 global $wgContLang, $wgMaxNameChars;
855 || self
::isIP( $name )
856 ||
strpos( $name, '/' ) !== false
857 ||
strlen( $name ) > $wgMaxNameChars
858 ||
$name != $wgContLang->ucfirst( $name )
863 // Ensure that the name can't be misresolved as a different title,
864 // such as with extra namespace keys at the start.
865 $parsed = Title
::newFromText( $name );
866 if ( is_null( $parsed )
867 ||
$parsed->getNamespace()
868 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
872 // Check an additional blacklist of troublemaker characters.
873 // Should these be merged into the title char list?
874 $unicodeBlacklist = '/[' .
875 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
876 '\x{00a0}' . # non-breaking space
877 '\x{2000}-\x{200f}' . # various whitespace
878 '\x{2028}-\x{202f}' . # breaks and control chars
879 '\x{3000}' . # ideographic space
880 '\x{e000}-\x{f8ff}' . # private use
882 if ( preg_match( $unicodeBlacklist, $name ) ) {
890 * Usernames which fail to pass this function will be blocked
891 * from user login and new account registrations, but may be used
892 * internally by batch processes.
894 * If an account already exists in this form, login will be blocked
895 * by a failure to pass this function.
897 * @param string $name Name to match
900 public static function isUsableName( $name ) {
901 global $wgReservedUsernames;
902 // Must be a valid username, obviously ;)
903 if ( !self
::isValidUserName( $name ) ) {
907 static $reservedUsernames = false;
908 if ( !$reservedUsernames ) {
909 $reservedUsernames = $wgReservedUsernames;
910 Hooks
::run( 'UserGetReservedNames', [ &$reservedUsernames ] );
913 // Certain names may be reserved for batch processes.
914 foreach ( $reservedUsernames as $reserved ) {
915 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
916 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
918 if ( $reserved == $name ) {
926 * Return the users who are members of the given group(s). In case of multiple groups,
927 * users who are members of at least one of them are returned.
929 * @param string|array $groups A single group name or an array of group names
930 * @param int $limit Max number of users to return. The actual limit will never exceed 5000
931 * records; larger values are ignored.
932 * @param int $after ID the user to start after
933 * @return UserArrayFromResult
935 public static function findUsersByGroup( $groups, $limit = 5000, $after = null ) {
936 if ( $groups === [] ) {
937 return UserArrayFromResult
::newFromIDs( [] );
940 $groups = array_unique( (array)$groups );
941 $limit = min( 5000, $limit );
943 $conds = [ 'ug_group' => $groups ];
944 if ( $after !== null ) {
945 $conds[] = 'ug_user > ' . (int)$after;
948 $dbr = wfGetDB( DB_REPLICA
);
949 $ids = $dbr->selectFieldValues(
956 'ORDER BY' => 'ug_user',
960 return UserArray
::newFromIDs( $ids );
964 * Usernames which fail to pass this function will be blocked
965 * from new account registrations, but may be used internally
966 * either by batch processes or by user accounts which have
967 * already been created.
969 * Additional blacklisting may be added here rather than in
970 * isValidUserName() to avoid disrupting existing accounts.
972 * @param string $name String to match
975 public static function isCreatableName( $name ) {
976 global $wgInvalidUsernameCharacters;
978 // Ensure that the username isn't longer than 235 bytes, so that
979 // (at least for the builtin skins) user javascript and css files
980 // will work. (T25080)
981 if ( strlen( $name ) > 235 ) {
982 wfDebugLog( 'username', __METHOD__
.
983 ": '$name' invalid due to length" );
987 // Preg yells if you try to give it an empty string
988 if ( $wgInvalidUsernameCharacters !== '' ) {
989 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
990 wfDebugLog( 'username', __METHOD__
.
991 ": '$name' invalid due to wgInvalidUsernameCharacters" );
996 return self
::isUsableName( $name );
1000 * Is the input a valid password for this user?
1002 * @param string $password Desired password
1005 public function isValidPassword( $password ) {
1006 // simple boolean wrapper for getPasswordValidity
1007 return $this->getPasswordValidity( $password ) === true;
1011 * Given unvalidated password input, return error message on failure.
1013 * @param string $password Desired password
1014 * @return bool|string|array True on success, string or array of error message on failure
1016 public function getPasswordValidity( $password ) {
1017 $result = $this->checkPasswordValidity( $password );
1018 if ( $result->isGood() ) {
1022 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
1023 $messages[] = $error['message'];
1025 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
1026 $messages[] = $warning['message'];
1028 if ( count( $messages ) === 1 ) {
1029 return $messages[0];
1036 * Check if this is a valid password for this user
1038 * Create a Status object based on the password's validity.
1039 * The Status should be set to fatal if the user should not
1040 * be allowed to log in, and should have any errors that
1041 * would block changing the password.
1043 * If the return value of this is not OK, the password
1044 * should not be checked. If the return value is not Good,
1045 * the password can be checked, but the user should not be
1046 * able to set their password to this.
1048 * @param string $password Desired password
1052 public function checkPasswordValidity( $password ) {
1053 global $wgPasswordPolicy;
1055 $upp = new UserPasswordPolicy(
1056 $wgPasswordPolicy['policies'],
1057 $wgPasswordPolicy['checks']
1060 $status = Status
::newGood();
1061 $result = false; // init $result to false for the internal checks
1063 if ( !Hooks
::run( 'isValidPassword', [ $password, &$result, $this ] ) ) {
1064 $status->error( $result );
1068 if ( $result === false ) {
1069 $status->merge( $upp->checkUserPassword( $this, $password ) );
1071 } elseif ( $result === true ) {
1074 $status->error( $result );
1075 return $status; // the isValidPassword hook set a string $result and returned true
1080 * Given unvalidated user input, return a canonical username, or false if
1081 * the username is invalid.
1082 * @param string $name User input
1083 * @param string|bool $validate Type of validation to use:
1084 * - false No validation
1085 * - 'valid' Valid for batch processes
1086 * - 'usable' Valid for batch processes and login
1087 * - 'creatable' Valid for batch processes, login and account creation
1089 * @throws InvalidArgumentException
1090 * @return bool|string
1092 public static function getCanonicalName( $name, $validate = 'valid' ) {
1093 // Force usernames to capital
1095 $name = $wgContLang->ucfirst( $name );
1097 # Reject names containing '#'; these will be cleaned up
1098 # with title normalisation, but then it's too late to
1100 if ( strpos( $name, '#' ) !== false ) {
1104 // Clean up name according to title rules,
1105 // but only when validation is requested (T14654)
1106 $t = ( $validate !== false ) ?
1107 Title
::newFromText( $name, NS_USER
) : Title
::makeTitle( NS_USER
, $name );
1108 // Check for invalid titles
1109 if ( is_null( $t ) ||
$t->getNamespace() !== NS_USER ||
$t->isExternal() ) {
1113 // Reject various classes of invalid names
1114 $name = AuthManager
::callLegacyAuthPlugin(
1115 'getCanonicalName', [ $t->getText() ], $t->getText()
1118 switch ( $validate ) {
1122 if ( !self
::isValidUserName( $name ) ) {
1127 if ( !self
::isUsableName( $name ) ) {
1132 if ( !self
::isCreatableName( $name ) ) {
1137 throw new InvalidArgumentException(
1138 'Invalid parameter value for $validate in ' . __METHOD__
);
1144 * Return a random password.
1146 * @deprecated since 1.27, use PasswordFactory::generateRandomPasswordString()
1147 * @return string New random password
1149 public static function randomPassword() {
1150 global $wgMinimalPasswordLength;
1151 return PasswordFactory
::generateRandomPasswordString( $wgMinimalPasswordLength );
1155 * Set cached properties to default.
1157 * @note This no longer clears uncached lazy-initialised properties;
1158 * the constructor does that instead.
1160 * @param string|bool $name
1162 public function loadDefaults( $name = false ) {
1164 $this->mName
= $name;
1165 $this->mRealName
= '';
1167 $this->mOptionOverrides
= null;
1168 $this->mOptionsLoaded
= false;
1170 $loggedOut = $this->mRequest
&& !defined( 'MW_NO_SESSION' )
1171 ?
$this->mRequest
->getSession()->getLoggedOutTimestamp() : 0;
1172 if ( $loggedOut !== 0 ) {
1173 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1175 $this->mTouched
= '1'; # Allow any pages to be cached
1178 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1179 $this->mEmailAuthenticated
= null;
1180 $this->mEmailToken
= '';
1181 $this->mEmailTokenExpires
= null;
1182 $this->mRegistration
= wfTimestamp( TS_MW
);
1183 $this->mGroupMemberships
= [];
1185 Hooks
::run( 'UserLoadDefaults', [ $this, $name ] );
1189 * Return whether an item has been loaded.
1191 * @param string $item Item to check. Current possibilities:
1195 * @param string $all 'all' to check if the whole object has been loaded
1196 * or any other string to check if only the item is available (e.g.
1200 public function isItemLoaded( $item, $all = 'all' ) {
1201 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1202 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1206 * Set that an item has been loaded
1208 * @param string $item
1210 protected function setItemLoaded( $item ) {
1211 if ( is_array( $this->mLoadedItems
) ) {
1212 $this->mLoadedItems
[$item] = true;
1217 * Load user data from the session.
1219 * @return bool True if the user is logged in, false otherwise.
1221 private function loadFromSession() {
1224 Hooks
::run( 'UserLoadFromSession', [ $this, &$result ], '1.27' );
1225 if ( $result !== null ) {
1229 // MediaWiki\Session\Session already did the necessary authentication of the user
1230 // returned here, so just use it if applicable.
1231 $session = $this->getRequest()->getSession();
1232 $user = $session->getUser();
1233 if ( $user->isLoggedIn() ) {
1234 $this->loadFromUserObject( $user );
1236 // If this user is autoblocked, set a cookie to track the Block. This has to be done on
1237 // every session load, because an autoblocked editor might not edit again from the same
1238 // IP address after being blocked.
1239 $config = RequestContext
::getMain()->getConfig();
1240 if ( $config->get( 'CookieSetOnAutoblock' ) === true ) {
1241 $block = $this->getBlock();
1242 $shouldSetCookie = $this->getRequest()->getCookie( 'BlockID' ) === null
1244 && $block->getType() === Block
::TYPE_USER
1245 && $block->isAutoblocking();
1246 if ( $shouldSetCookie ) {
1247 wfDebug( __METHOD__
. ': User is autoblocked, setting cookie to track' );
1248 $block->setCookie( $this->getRequest()->response() );
1252 // Other code expects these to be set in the session, so set them.
1253 $session->set( 'wsUserID', $this->getId() );
1254 $session->set( 'wsUserName', $this->getName() );
1255 $session->set( 'wsToken', $this->getToken() );
1262 * Load user and user_group data from the database.
1263 * $this->mId must be set, this is how the user is identified.
1265 * @param int $flags User::READ_* constant bitfield
1266 * @return bool True if the user exists, false if the user is anonymous
1268 public function loadFromDatabase( $flags = self
::READ_LATEST
) {
1270 $this->mId
= intval( $this->mId
);
1272 if ( !$this->mId
) {
1273 // Anonymous users are not in the database
1274 $this->loadDefaults();
1278 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
1279 $db = wfGetDB( $index );
1281 $s = $db->selectRow(
1283 self
::selectFields(),
1284 [ 'user_id' => $this->mId
],
1289 $this->queryFlagsUsed
= $flags;
1290 Hooks
::run( 'UserLoadFromDatabase', [ $this, &$s ] );
1292 if ( $s !== false ) {
1293 // Initialise user table data
1294 $this->loadFromRow( $s );
1295 $this->mGroupMemberships
= null; // deferred
1296 $this->getEditCount(); // revalidation for nulls
1301 $this->loadDefaults();
1307 * Initialize this object from a row from the user table.
1309 * @param stdClass $row Row from the user table to load.
1310 * @param array $data Further user data to load into the object
1312 * user_groups Array of arrays or stdClass result rows out of the user_groups
1313 * table. Previously you were supposed to pass an array of strings
1314 * here, but we also need expiry info nowadays, so an array of
1315 * strings is ignored.
1316 * user_properties Array with properties out of the user_properties table
1318 protected function loadFromRow( $row, $data = null ) {
1321 $this->mGroupMemberships
= null; // deferred
1323 if ( isset( $row->user_name
) ) {
1324 $this->mName
= $row->user_name
;
1325 $this->mFrom
= 'name';
1326 $this->setItemLoaded( 'name' );
1331 if ( isset( $row->user_real_name
) ) {
1332 $this->mRealName
= $row->user_real_name
;
1333 $this->setItemLoaded( 'realname' );
1338 if ( isset( $row->user_id
) ) {
1339 $this->mId
= intval( $row->user_id
);
1340 $this->mFrom
= 'id';
1341 $this->setItemLoaded( 'id' );
1346 if ( isset( $row->user_id
) && isset( $row->user_name
) ) {
1347 self
::$idCacheByName[$row->user_name
] = $row->user_id
;
1350 if ( isset( $row->user_editcount
) ) {
1351 $this->mEditCount
= $row->user_editcount
;
1356 if ( isset( $row->user_touched
) ) {
1357 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1362 if ( isset( $row->user_token
) ) {
1363 // The definition for the column is binary(32), so trim the NULs
1364 // that appends. The previous definition was char(32), so trim
1366 $this->mToken
= rtrim( $row->user_token
, " \0" );
1367 if ( $this->mToken
=== '' ) {
1368 $this->mToken
= null;
1374 if ( isset( $row->user_email
) ) {
1375 $this->mEmail
= $row->user_email
;
1376 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1377 $this->mEmailToken
= $row->user_email_token
;
1378 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1379 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1385 $this->mLoadedItems
= true;
1388 if ( is_array( $data ) ) {
1389 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1390 if ( !count( $data['user_groups'] ) ) {
1391 $this->mGroupMemberships
= [];
1393 $firstGroup = reset( $data['user_groups'] );
1394 if ( is_array( $firstGroup ) ||
is_object( $firstGroup ) ) {
1395 $this->mGroupMemberships
= [];
1396 foreach ( $data['user_groups'] as $row ) {
1397 $ugm = UserGroupMembership
::newFromRow( (object)$row );
1398 $this->mGroupMemberships
[$ugm->getGroup()] = $ugm;
1403 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1404 $this->loadOptions( $data['user_properties'] );
1410 * Load the data for this user object from another user object.
1414 protected function loadFromUserObject( $user ) {
1416 foreach ( self
::$mCacheVars as $var ) {
1417 $this->$var = $user->$var;
1422 * Load the groups from the database if they aren't already loaded.
1424 private function loadGroups() {
1425 if ( is_null( $this->mGroupMemberships
) ) {
1426 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
1427 ?
wfGetDB( DB_MASTER
)
1428 : wfGetDB( DB_REPLICA
);
1429 $this->mGroupMemberships
= UserGroupMembership
::getMembershipsForUser(
1435 * Add the user to the group if he/she meets given criteria.
1437 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1438 * possible to remove manually via Special:UserRights. In such case it
1439 * will not be re-added automatically. The user will also not lose the
1440 * group if they no longer meet the criteria.
1442 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1444 * @return array Array of groups the user has been promoted to.
1446 * @see $wgAutopromoteOnce
1448 public function addAutopromoteOnceGroups( $event ) {
1449 global $wgAutopromoteOnceLogInRC;
1451 if ( wfReadOnly() ||
!$this->getId() ) {
1455 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1456 if ( !count( $toPromote ) ) {
1460 if ( !$this->checkAndSetTouched() ) {
1461 return []; // raced out (bug T48834)
1464 $oldGroups = $this->getGroups(); // previous groups
1465 $oldUGMs = $this->getGroupMemberships();
1466 foreach ( $toPromote as $group ) {
1467 $this->addGroup( $group );
1469 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1470 $newUGMs = $this->getGroupMemberships();
1472 // update groups in external authentication database
1473 Hooks
::run( 'UserGroupsChanged', [ $this, $toPromote, [], false, false, $oldUGMs, $newUGMs ] );
1474 AuthManager
::callLegacyAuthPlugin( 'updateExternalDBGroups', [ $this, $toPromote ] );
1476 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1477 $logEntry->setPerformer( $this );
1478 $logEntry->setTarget( $this->getUserPage() );
1479 $logEntry->setParameters( [
1480 '4::oldgroups' => $oldGroups,
1481 '5::newgroups' => $newGroups,
1483 $logid = $logEntry->insert();
1484 if ( $wgAutopromoteOnceLogInRC ) {
1485 $logEntry->publish( $logid );
1492 * Builds update conditions. Additional conditions may be added to $conditions to
1493 * protected against race conditions using a compare-and-set (CAS) mechanism
1494 * based on comparing $this->mTouched with the user_touched field.
1496 * @param Database $db
1497 * @param array $conditions WHERE conditions for use with Database::update
1498 * @return array WHERE conditions for use with Database::update
1500 protected function makeUpdateConditions( Database
$db, array $conditions ) {
1501 if ( $this->mTouched
) {
1502 // CAS check: only update if the row wasn't changed sicne it was loaded.
1503 $conditions['user_touched'] = $db->timestamp( $this->mTouched
);
1510 * Bump user_touched if it didn't change since this object was loaded
1512 * On success, the mTouched field is updated.
1513 * The user serialization cache is always cleared.
1515 * @return bool Whether user_touched was actually updated
1518 protected function checkAndSetTouched() {
1521 if ( !$this->mId
) {
1522 return false; // anon
1525 // Get a new user_touched that is higher than the old one
1526 $newTouched = $this->newTouchedTimestamp();
1528 $dbw = wfGetDB( DB_MASTER
);
1529 $dbw->update( 'user',
1530 [ 'user_touched' => $dbw->timestamp( $newTouched ) ],
1531 $this->makeUpdateConditions( $dbw, [
1532 'user_id' => $this->mId
,
1536 $success = ( $dbw->affectedRows() > 0 );
1539 $this->mTouched
= $newTouched;
1540 $this->clearSharedCache();
1542 // Clears on failure too since that is desired if the cache is stale
1543 $this->clearSharedCache( 'refresh' );
1550 * Clear various cached data stored in this object. The cache of the user table
1551 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1553 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1554 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1556 public function clearInstanceCache( $reloadFrom = false ) {
1557 $this->mNewtalk
= -1;
1558 $this->mDatePreference
= null;
1559 $this->mBlockedby
= -1; # Unset
1560 $this->mHash
= false;
1561 $this->mRights
= null;
1562 $this->mEffectiveGroups
= null;
1563 $this->mImplicitGroups
= null;
1564 $this->mGroupMemberships
= null;
1565 $this->mOptions
= null;
1566 $this->mOptionsLoaded
= false;
1567 $this->mEditCount
= null;
1569 if ( $reloadFrom ) {
1570 $this->mLoadedItems
= [];
1571 $this->mFrom
= $reloadFrom;
1576 * Combine the language default options with any site-specific options
1577 * and add the default language variants.
1579 * @return array Array of String options
1581 public static function getDefaultOptions() {
1582 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1584 static $defOpt = null;
1585 static $defOptLang = null;
1587 if ( $defOpt !== null && $defOptLang === $wgContLang->getCode() ) {
1588 // $wgContLang does not change (and should not change) mid-request,
1589 // but the unit tests change it anyway, and expect this method to
1590 // return values relevant to the current $wgContLang.
1594 $defOpt = $wgDefaultUserOptions;
1595 // Default language setting
1596 $defOptLang = $wgContLang->getCode();
1597 $defOpt['language'] = $defOptLang;
1598 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1599 $defOpt[$langCode == $wgContLang->getCode() ?
'variant' : "variant-$langCode"] = $langCode;
1602 // NOTE: don't use SearchEngineConfig::getSearchableNamespaces here,
1603 // since extensions may change the set of searchable namespaces depending
1604 // on user groups/permissions.
1605 foreach ( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
1606 $defOpt['searchNs' . $nsnum] = (bool)$val;
1608 $defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1610 Hooks
::run( 'UserGetDefaultOptions', [ &$defOpt ] );
1616 * Get a given default option value.
1618 * @param string $opt Name of option to retrieve
1619 * @return string Default option value
1621 public static function getDefaultOption( $opt ) {
1622 $defOpts = self
::getDefaultOptions();
1623 if ( isset( $defOpts[$opt] ) ) {
1624 return $defOpts[$opt];
1631 * Get blocking information
1632 * @param bool $bFromSlave Whether to check the replica DB first.
1633 * To improve performance, non-critical checks are done against replica DBs.
1634 * Check when actually saving should be done against master.
1636 private function getBlockedStatus( $bFromSlave = true ) {
1637 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff, $wgSoftBlockRanges;
1639 if ( -1 != $this->mBlockedby
) {
1643 wfDebug( __METHOD__
. ": checking...\n" );
1645 // Initialize data...
1646 // Otherwise something ends up stomping on $this->mBlockedby when
1647 // things get lazy-loaded later, causing false positive block hits
1648 // due to -1 !== 0. Probably session-related... Nothing should be
1649 // overwriting mBlockedby, surely?
1652 # We only need to worry about passing the IP address to the Block generator if the
1653 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1654 # know which IP address they're actually coming from
1656 if ( !$this->isAllowed( 'ipblock-exempt' ) ) {
1657 // $wgUser->getName() only works after the end of Setup.php. Until
1658 // then, assume it's a logged-out user.
1659 $globalUserName = $wgUser->isSafeToLoad()
1660 ?
$wgUser->getName()
1661 : IP
::sanitizeIP( $wgUser->getRequest()->getIP() );
1662 if ( $this->getName() === $globalUserName ) {
1663 $ip = $this->getRequest()->getIP();
1668 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1671 if ( !$block instanceof Block
) {
1672 $block = $this->getBlockFromCookieValue( $this->getRequest()->getCookie( 'BlockID' ) );
1676 if ( !$block instanceof Block
&& $ip !== null && !in_array( $ip, $wgProxyWhitelist ) ) {
1678 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1679 $block = new Block( [
1680 'byText' => wfMessage( 'proxyblocker' )->text(),
1681 'reason' => wfMessage( 'proxyblockreason' )->text(),
1683 'systemBlock' => 'proxy',
1685 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1686 $block = new Block( [
1687 'byText' => wfMessage( 'sorbs' )->text(),
1688 'reason' => wfMessage( 'sorbsreason' )->text(),
1690 'systemBlock' => 'dnsbl',
1695 // (T25343) Apply IP blocks to the contents of XFF headers, if enabled
1696 if ( !$block instanceof Block
1697 && $wgApplyIpBlocksToXff
1699 && !in_array( $ip, $wgProxyWhitelist )
1701 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1702 $xff = array_map( 'trim', explode( ',', $xff ) );
1703 $xff = array_diff( $xff, [ $ip ] );
1704 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1705 $block = Block
::chooseBlock( $xffblocks, $xff );
1706 if ( $block instanceof Block
) {
1707 # Mangle the reason to alert the user that the block
1708 # originated from matching the X-Forwarded-For header.
1709 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->text();
1713 if ( !$block instanceof Block
1716 && IP
::isInRanges( $ip, $wgSoftBlockRanges )
1718 $block = new Block( [
1720 'byText' => 'MediaWiki default',
1721 'reason' => wfMessage( 'softblockrangesreason', $ip )->text(),
1723 'systemBlock' => 'wgSoftBlockRanges',
1727 if ( $block instanceof Block
) {
1728 wfDebug( __METHOD__
. ": Found block.\n" );
1729 $this->mBlock
= $block;
1730 $this->mBlockedby
= $block->getByName();
1731 $this->mBlockreason
= $block->mReason
;
1732 $this->mHideName
= $block->mHideName
;
1733 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1735 $this->mBlockedby
= '';
1736 $this->mHideName
= 0;
1737 $this->mAllowUsertalk
= false;
1740 // Avoid PHP 7.1 warning of passing $this by reference
1743 Hooks
::run( 'GetBlockedStatus', [ &$user ] );
1747 * Try to load a Block from an ID given in a cookie value.
1748 * @param string|null $blockCookieVal The cookie value to check.
1749 * @return Block|bool The Block object, or false if none could be loaded.
1751 protected function getBlockFromCookieValue( $blockCookieVal ) {
1752 // Make sure there's something to check. The cookie value must start with a number.
1753 if ( strlen( $blockCookieVal ) < 1 ||
!is_numeric( substr( $blockCookieVal, 0, 1 ) ) ) {
1756 // Load the Block from the ID in the cookie.
1757 $blockCookieId = Block
::getIdFromCookieValue( $blockCookieVal );
1758 if ( $blockCookieId !== null ) {
1759 // An ID was found in the cookie.
1760 $tmpBlock = Block
::newFromID( $blockCookieId );
1761 if ( $tmpBlock instanceof Block
) {
1762 // Check the validity of the block.
1763 $blockIsValid = $tmpBlock->getType() == Block
::TYPE_USER
1764 && !$tmpBlock->isExpired()
1765 && $tmpBlock->isAutoblocking();
1766 $config = RequestContext
::getMain()->getConfig();
1767 $useBlockCookie = ( $config->get( 'CookieSetOnAutoblock' ) === true );
1768 if ( $blockIsValid && $useBlockCookie ) {
1772 // If the block is not valid, remove the cookie.
1773 Block
::clearCookie( $this->getRequest()->response() );
1776 // If the block doesn't exist, remove the cookie.
1777 Block
::clearCookie( $this->getRequest()->response() );
1784 * Whether the given IP is in a DNS blacklist.
1786 * @param string $ip IP to check
1787 * @param bool $checkWhitelist Whether to check the whitelist first
1788 * @return bool True if blacklisted.
1790 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1791 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1793 if ( !$wgEnableDnsBlacklist ) {
1797 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1801 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1805 * Whether the given IP is in a given DNS blacklist.
1807 * @param string $ip IP to check
1808 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1809 * @return bool True if blacklisted.
1811 public function inDnsBlacklist( $ip, $bases ) {
1813 // @todo FIXME: IPv6 ??? (https://bugs.php.net/bug.php?id=33170)
1814 if ( IP
::isIPv4( $ip ) ) {
1815 // Reverse IP, T23255
1816 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1818 foreach ( (array)$bases as $base ) {
1820 // If we have an access key, use that too (ProjectHoneypot, etc.)
1822 if ( is_array( $base ) ) {
1823 if ( count( $base ) >= 2 ) {
1824 // Access key is 1, base URL is 0
1825 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1827 $host = "$ipReversed.{$base[0]}";
1829 $basename = $base[0];
1831 $host = "$ipReversed.$base";
1835 $ipList = gethostbynamel( $host );
1838 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
1842 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
1851 * Check if an IP address is in the local proxy list
1857 public static function isLocallyBlockedProxy( $ip ) {
1858 global $wgProxyList;
1860 if ( !$wgProxyList ) {
1864 if ( !is_array( $wgProxyList ) ) {
1865 // Load values from the specified file
1866 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1869 $resultProxyList = [];
1870 $deprecatedIPEntries = [];
1872 // backward compatibility: move all ip addresses in keys to values
1873 foreach ( $wgProxyList as $key => $value ) {
1874 $keyIsIP = IP
::isIPAddress( $key );
1875 $valueIsIP = IP
::isIPAddress( $value );
1876 if ( $keyIsIP && !$valueIsIP ) {
1877 $deprecatedIPEntries[] = $key;
1878 $resultProxyList[] = $key;
1879 } elseif ( $keyIsIP && $valueIsIP ) {
1880 $deprecatedIPEntries[] = $key;
1881 $resultProxyList[] = $key;
1882 $resultProxyList[] = $value;
1884 $resultProxyList[] = $value;
1888 if ( $deprecatedIPEntries ) {
1890 'IP addresses in the keys of $wgProxyList (found the following IP addresses in keys: ' .
1891 implode( ', ', $deprecatedIPEntries ) . ', please move them to values)', '1.30' );
1894 $proxyListIPSet = new IPSet( $resultProxyList );
1895 return $proxyListIPSet->match( $ip );
1899 * Is this user subject to rate limiting?
1901 * @return bool True if rate limited
1903 public function isPingLimitable() {
1904 global $wgRateLimitsExcludedIPs;
1905 if ( IP
::isInRanges( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1906 // No other good way currently to disable rate limits
1907 // for specific IPs. :P
1908 // But this is a crappy hack and should die.
1911 return !$this->isAllowed( 'noratelimit' );
1915 * Primitive rate limits: enforce maximum actions per time period
1916 * to put a brake on flooding.
1918 * The method generates both a generic profiling point and a per action one
1919 * (suffix being "-$action".
1921 * @note When using a shared cache like memcached, IP-address
1922 * last-hit counters will be shared across wikis.
1924 * @param string $action Action to enforce; 'edit' if unspecified
1925 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1926 * @return bool True if a rate limiter was tripped
1928 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1929 // Avoid PHP 7.1 warning of passing $this by reference
1931 // Call the 'PingLimiter' hook
1933 if ( !Hooks
::run( 'PingLimiter', [ &$user, $action, &$result, $incrBy ] ) ) {
1937 global $wgRateLimits;
1938 if ( !isset( $wgRateLimits[$action] ) ) {
1942 $limits = array_merge(
1943 [ '&can-bypass' => true ],
1944 $wgRateLimits[$action]
1947 // Some groups shouldn't trigger the ping limiter, ever
1948 if ( $limits['&can-bypass'] && !$this->isPingLimitable() ) {
1953 $id = $this->getId();
1955 $isNewbie = $this->isNewbie();
1956 $cache = ObjectCache
::getLocalClusterInstance();
1960 if ( isset( $limits['anon'] ) ) {
1961 $keys[$cache->makeKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1964 // limits for logged-in users
1965 if ( isset( $limits['user'] ) ) {
1966 $userLimit = $limits['user'];
1968 // limits for newbie logged-in users
1969 if ( $isNewbie && isset( $limits['newbie'] ) ) {
1970 $keys[$cache->makeKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1974 // limits for anons and for newbie logged-in users
1977 if ( isset( $limits['ip'] ) ) {
1978 $ip = $this->getRequest()->getIP();
1979 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1981 // subnet-based limits
1982 if ( isset( $limits['subnet'] ) ) {
1983 $ip = $this->getRequest()->getIP();
1984 $subnet = IP
::getSubnet( $ip );
1985 if ( $subnet !== false ) {
1986 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1991 // Check for group-specific permissions
1992 // If more than one group applies, use the group with the highest limit ratio (max/period)
1993 foreach ( $this->getGroups() as $group ) {
1994 if ( isset( $limits[$group] ) ) {
1995 if ( $userLimit === false
1996 ||
$limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1998 $userLimit = $limits[$group];
2003 // Set the user limit key
2004 if ( $userLimit !== false ) {
2005 list( $max, $period ) = $userLimit;
2006 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
2007 $keys[$cache->makeKey( 'limiter', $action, 'user', $id )] = $userLimit;
2010 // ip-based limits for all ping-limitable users
2011 if ( isset( $limits['ip-all'] ) ) {
2012 $ip = $this->getRequest()->getIP();
2013 // ignore if user limit is more permissive
2014 if ( $isNewbie ||
$userLimit === false
2015 ||
$limits['ip-all'][0] / $limits['ip-all'][1] > $userLimit[0] / $userLimit[1] ) {
2016 $keys["mediawiki:limiter:$action:ip-all:$ip"] = $limits['ip-all'];
2020 // subnet-based limits for all ping-limitable users
2021 if ( isset( $limits['subnet-all'] ) ) {
2022 $ip = $this->getRequest()->getIP();
2023 $subnet = IP
::getSubnet( $ip );
2024 if ( $subnet !== false ) {
2025 // ignore if user limit is more permissive
2026 if ( $isNewbie ||
$userLimit === false
2027 ||
$limits['ip-all'][0] / $limits['ip-all'][1]
2028 > $userLimit[0] / $userLimit[1] ) {
2029 $keys["mediawiki:limiter:$action:subnet-all:$subnet"] = $limits['subnet-all'];
2035 foreach ( $keys as $key => $limit ) {
2036 list( $max, $period ) = $limit;
2037 $summary = "(limit $max in {$period}s)";
2038 $count = $cache->get( $key );
2041 if ( $count >= $max ) {
2042 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
2043 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
2046 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
2049 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
2050 if ( $incrBy > 0 ) {
2051 $cache->add( $key, 0, intval( $period ) ); // first ping
2054 if ( $incrBy > 0 ) {
2055 $cache->incr( $key, $incrBy );
2063 * Check if user is blocked
2065 * @param bool $bFromSlave Whether to check the replica DB instead of
2066 * the master. Hacked from false due to horrible probs on site.
2067 * @return bool True if blocked, false otherwise
2069 public function isBlocked( $bFromSlave = true ) {
2070 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
2074 * Get the block affecting the user, or null if the user is not blocked
2076 * @param bool $bFromSlave Whether to check the replica DB instead of the master
2077 * @return Block|null
2079 public function getBlock( $bFromSlave = true ) {
2080 $this->getBlockedStatus( $bFromSlave );
2081 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
2085 * Check if user is blocked from editing a particular article
2087 * @param Title $title Title to check
2088 * @param bool $bFromSlave Whether to check the replica DB instead of the master
2091 public function isBlockedFrom( $title, $bFromSlave = false ) {
2092 global $wgBlockAllowsUTEdit;
2094 $blocked = $this->isBlocked( $bFromSlave );
2095 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
2096 // If a user's name is suppressed, they cannot make edits anywhere
2097 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName()
2098 && $title->getNamespace() == NS_USER_TALK
) {
2100 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
2103 Hooks
::run( 'UserIsBlockedFrom', [ $this, $title, &$blocked, &$allowUsertalk ] );
2109 * If user is blocked, return the name of the user who placed the block
2110 * @return string Name of blocker
2112 public function blockedBy() {
2113 $this->getBlockedStatus();
2114 return $this->mBlockedby
;
2118 * If user is blocked, return the specified reason for the block
2119 * @return string Blocking reason
2121 public function blockedFor() {
2122 $this->getBlockedStatus();
2123 return $this->mBlockreason
;
2127 * If user is blocked, return the ID for the block
2128 * @return int Block ID
2130 public function getBlockId() {
2131 $this->getBlockedStatus();
2132 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
2136 * Check if user is blocked on all wikis.
2137 * Do not use for actual edit permission checks!
2138 * This is intended for quick UI checks.
2140 * @param string $ip IP address, uses current client if none given
2141 * @return bool True if blocked, false otherwise
2143 public function isBlockedGlobally( $ip = '' ) {
2144 return $this->getGlobalBlock( $ip ) instanceof Block
;
2148 * Check if user is blocked on all wikis.
2149 * Do not use for actual edit permission checks!
2150 * This is intended for quick UI checks.
2152 * @param string $ip IP address, uses current client if none given
2153 * @return Block|null Block object if blocked, null otherwise
2154 * @throws FatalError
2155 * @throws MWException
2157 public function getGlobalBlock( $ip = '' ) {
2158 if ( $this->mGlobalBlock
!== null ) {
2159 return $this->mGlobalBlock ?
: null;
2161 // User is already an IP?
2162 if ( IP
::isIPAddress( $this->getName() ) ) {
2163 $ip = $this->getName();
2165 $ip = $this->getRequest()->getIP();
2167 // Avoid PHP 7.1 warning of passing $this by reference
2171 Hooks
::run( 'UserIsBlockedGlobally', [ &$user, $ip, &$blocked, &$block ] );
2173 if ( $blocked && $block === null ) {
2174 // back-compat: UserIsBlockedGlobally didn't have $block param first
2175 $block = new Block( [
2177 'systemBlock' => 'global-block'
2181 $this->mGlobalBlock
= $blocked ?
$block : false;
2182 return $this->mGlobalBlock ?
: null;
2186 * Check if user account is locked
2188 * @return bool True if locked, false otherwise
2190 public function isLocked() {
2191 if ( $this->mLocked
!== null ) {
2192 return $this->mLocked
;
2194 // Avoid PHP 7.1 warning of passing $this by reference
2196 $authUser = AuthManager
::callLegacyAuthPlugin( 'getUserInstance', [ &$user ], null );
2197 $this->mLocked
= $authUser && $authUser->isLocked();
2198 Hooks
::run( 'UserIsLocked', [ $this, &$this->mLocked
] );
2199 return $this->mLocked
;
2203 * Check if user account is hidden
2205 * @return bool True if hidden, false otherwise
2207 public function isHidden() {
2208 if ( $this->mHideName
!== null ) {
2209 return $this->mHideName
;
2211 $this->getBlockedStatus();
2212 if ( !$this->mHideName
) {
2213 // Avoid PHP 7.1 warning of passing $this by reference
2215 $authUser = AuthManager
::callLegacyAuthPlugin( 'getUserInstance', [ &$user ], null );
2216 $this->mHideName
= $authUser && $authUser->isHidden();
2217 Hooks
::run( 'UserIsHidden', [ $this, &$this->mHideName
] );
2219 return $this->mHideName
;
2223 * Get the user's ID.
2224 * @return int The user's ID; 0 if the user is anonymous or nonexistent
2226 public function getId() {
2227 if ( $this->mId
=== null && $this->mName
!== null && self
::isIP( $this->mName
) ) {
2228 // Special case, we know the user is anonymous
2230 } elseif ( !$this->isItemLoaded( 'id' ) ) {
2231 // Don't load if this was initialized from an ID
2235 return (int)$this->mId
;
2239 * Set the user and reload all fields according to a given ID
2240 * @param int $v User ID to reload
2242 public function setId( $v ) {
2244 $this->clearInstanceCache( 'id' );
2248 * Get the user name, or the IP of an anonymous user
2249 * @return string User's name or IP address
2251 public function getName() {
2252 if ( $this->isItemLoaded( 'name', 'only' ) ) {
2253 // Special case optimisation
2254 return $this->mName
;
2257 if ( $this->mName
=== false ) {
2259 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
2261 return $this->mName
;
2266 * Set the user name.
2268 * This does not reload fields from the database according to the given
2269 * name. Rather, it is used to create a temporary "nonexistent user" for
2270 * later addition to the database. It can also be used to set the IP
2271 * address for an anonymous user to something other than the current
2274 * @note User::newFromName() has roughly the same function, when the named user
2276 * @param string $str New user name to set
2278 public function setName( $str ) {
2280 $this->mName
= $str;
2284 * Get the user's name escaped by underscores.
2285 * @return string Username escaped by underscores.
2287 public function getTitleKey() {
2288 return str_replace( ' ', '_', $this->getName() );
2292 * Check if the user has new messages.
2293 * @return bool True if the user has new messages
2295 public function getNewtalk() {
2298 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2299 if ( $this->mNewtalk
=== -1 ) {
2300 $this->mNewtalk
= false; # reset talk page status
2302 // Check memcached separately for anons, who have no
2303 // entire User object stored in there.
2304 if ( !$this->mId
) {
2305 global $wgDisableAnonTalk;
2306 if ( $wgDisableAnonTalk ) {
2307 // Anon newtalk disabled by configuration.
2308 $this->mNewtalk
= false;
2310 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
2313 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2317 return (bool)$this->mNewtalk
;
2321 * Return the data needed to construct links for new talk page message
2322 * alerts. If there are new messages, this will return an associative array
2323 * with the following data:
2324 * wiki: The database name of the wiki
2325 * link: Root-relative link to the user's talk page
2326 * rev: The last talk page revision that the user has seen or null. This
2327 * is useful for building diff links.
2328 * If there are no new messages, it returns an empty array.
2329 * @note This function was designed to accomodate multiple talk pages, but
2330 * currently only returns a single link and revision.
2333 public function getNewMessageLinks() {
2334 // Avoid PHP 7.1 warning of passing $this by reference
2337 if ( !Hooks
::run( 'UserRetrieveNewTalks', [ &$user, &$talks ] ) ) {
2339 } elseif ( !$this->getNewtalk() ) {
2342 $utp = $this->getTalkPage();
2343 $dbr = wfGetDB( DB_REPLICA
);
2344 // Get the "last viewed rev" timestamp from the oldest message notification
2345 $timestamp = $dbr->selectField( 'user_newtalk',
2346 'MIN(user_last_timestamp)',
2347 $this->isAnon() ?
[ 'user_ip' => $this->getName() ] : [ 'user_id' => $this->getId() ],
2349 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2350 return [ [ 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ] ];
2354 * Get the revision ID for the last talk page revision viewed by the talk
2356 * @return int|null Revision ID or null
2358 public function getNewMessageRevisionId() {
2359 $newMessageRevisionId = null;
2360 $newMessageLinks = $this->getNewMessageLinks();
2361 if ( $newMessageLinks ) {
2362 // Note: getNewMessageLinks() never returns more than a single link
2363 // and it is always for the same wiki, but we double-check here in
2364 // case that changes some time in the future.
2365 if ( count( $newMessageLinks ) === 1
2366 && $newMessageLinks[0]['wiki'] === wfWikiID()
2367 && $newMessageLinks[0]['rev']
2369 /** @var Revision $newMessageRevision */
2370 $newMessageRevision = $newMessageLinks[0]['rev'];
2371 $newMessageRevisionId = $newMessageRevision->getId();
2374 return $newMessageRevisionId;
2378 * Internal uncached check for new messages
2381 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2382 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2383 * @return bool True if the user has new messages
2385 protected function checkNewtalk( $field, $id ) {
2386 $dbr = wfGetDB( DB_REPLICA
);
2388 $ok = $dbr->selectField( 'user_newtalk', $field, [ $field => $id ], __METHOD__
);
2390 return $ok !== false;
2394 * Add or update the new messages flag
2395 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2396 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2397 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2398 * @return bool True if successful, false otherwise
2400 protected function updateNewtalk( $field, $id, $curRev = null ) {
2401 // Get timestamp of the talk page revision prior to the current one
2402 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2403 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2404 // Mark the user as having new messages since this revision
2405 $dbw = wfGetDB( DB_MASTER
);
2406 $dbw->insert( 'user_newtalk',
2407 [ $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ],
2410 if ( $dbw->affectedRows() ) {
2411 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2414 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2420 * Clear the new messages flag for the given user
2421 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2422 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2423 * @return bool True if successful, false otherwise
2425 protected function deleteNewtalk( $field, $id ) {
2426 $dbw = wfGetDB( DB_MASTER
);
2427 $dbw->delete( 'user_newtalk',
2430 if ( $dbw->affectedRows() ) {
2431 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2434 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2440 * Update the 'You have new messages!' status.
2441 * @param bool $val Whether the user has new messages
2442 * @param Revision $curRev New, as yet unseen revision of the user talk
2443 * page. Ignored if null or !$val.
2445 public function setNewtalk( $val, $curRev = null ) {
2446 if ( wfReadOnly() ) {
2451 $this->mNewtalk
= $val;
2453 if ( $this->isAnon() ) {
2455 $id = $this->getName();
2458 $id = $this->getId();
2462 $changed = $this->updateNewtalk( $field, $id, $curRev );
2464 $changed = $this->deleteNewtalk( $field, $id );
2468 $this->invalidateCache();
2473 * Generate a current or new-future timestamp to be stored in the
2474 * user_touched field when we update things.
2475 * @return string Timestamp in TS_MW format
2477 private function newTouchedTimestamp() {
2478 global $wgClockSkewFudge;
2480 $time = wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2481 if ( $this->mTouched
&& $time <= $this->mTouched
) {
2482 $time = wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $this->mTouched
) +
1 );
2489 * Clear user data from memcached
2491 * Use after applying updates to the database; caller's
2492 * responsibility to update user_touched if appropriate.
2494 * Called implicitly from invalidateCache() and saveSettings().
2496 * @param string $mode Use 'refresh' to clear now; otherwise before DB commit
2498 public function clearSharedCache( $mode = 'changed' ) {
2499 if ( !$this->getId() ) {
2503 $cache = ObjectCache
::getMainWANInstance();
2504 $key = $this->getCacheKey( $cache );
2505 if ( $mode === 'refresh' ) {
2506 $cache->delete( $key, 1 );
2508 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle(
2509 function () use ( $cache, $key ) {
2510 $cache->delete( $key );
2518 * Immediately touch the user data cache for this account
2520 * Calls touch() and removes account data from memcached
2522 public function invalidateCache() {
2524 $this->clearSharedCache();
2528 * Update the "touched" timestamp for the user
2530 * This is useful on various login/logout events when making sure that
2531 * a browser or proxy that has multiple tenants does not suffer cache
2532 * pollution where the new user sees the old users content. The value
2533 * of getTouched() is checked when determining 304 vs 200 responses.
2534 * Unlike invalidateCache(), this preserves the User object cache and
2535 * avoids database writes.
2539 public function touch() {
2540 $id = $this->getId();
2542 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
2543 $key = $cache->makeKey( 'user-quicktouched', 'id', $id );
2544 $cache->touchCheckKey( $key );
2545 $this->mQuickTouched
= null;
2550 * Validate the cache for this account.
2551 * @param string $timestamp A timestamp in TS_MW format
2554 public function validateCache( $timestamp ) {
2555 return ( $timestamp >= $this->getTouched() );
2559 * Get the user touched timestamp
2561 * Use this value only to validate caches via inequalities
2562 * such as in the case of HTTP If-Modified-Since response logic
2564 * @return string TS_MW Timestamp
2566 public function getTouched() {
2570 if ( $this->mQuickTouched
=== null ) {
2571 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
2572 $key = $cache->makeKey( 'user-quicktouched', 'id', $this->mId
);
2574 $this->mQuickTouched
= wfTimestamp( TS_MW
, $cache->getCheckKeyTime( $key ) );
2577 return max( $this->mTouched
, $this->mQuickTouched
);
2580 return $this->mTouched
;
2584 * Get the user_touched timestamp field (time of last DB updates)
2585 * @return string TS_MW Timestamp
2588 public function getDBTouched() {
2591 return $this->mTouched
;
2595 * Set the password and reset the random token.
2596 * Calls through to authentication plugin if necessary;
2597 * will have no effect if the auth plugin refuses to
2598 * pass the change through or if the legal password
2601 * As a special case, setting the password to null
2602 * wipes it, so the account cannot be logged in until
2603 * a new password is set, for instance via e-mail.
2605 * @deprecated since 1.27, use AuthManager instead
2606 * @param string $str New password to set
2607 * @throws PasswordError On failure
2610 public function setPassword( $str ) {
2611 return $this->setPasswordInternal( $str );
2615 * Set the password and reset the random token unconditionally.
2617 * @deprecated since 1.27, use AuthManager instead
2618 * @param string|null $str New password to set or null to set an invalid
2619 * password hash meaning that the user will not be able to log in
2620 * through the web interface.
2622 public function setInternalPassword( $str ) {
2623 $this->setPasswordInternal( $str );
2627 * Actually set the password and such
2628 * @since 1.27 cannot set a password for a user not in the database
2629 * @param string|null $str New password to set or null to set an invalid
2630 * password hash meaning that the user will not be able to log in
2631 * through the web interface.
2632 * @return bool Success
2634 private function setPasswordInternal( $str ) {
2635 $manager = AuthManager
::singleton();
2637 // If the user doesn't exist yet, fail
2638 if ( !$manager->userExists( $this->getName() ) ) {
2639 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2642 $status = $this->changeAuthenticationData( [
2643 'username' => $this->getName(),
2647 if ( !$status->isGood() ) {
2648 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
2649 ->info( __METHOD__
. ': Password change rejected: '
2650 . $status->getWikiText( null, null, 'en' ) );
2654 $this->setOption( 'watchlisttoken', false );
2655 SessionManager
::singleton()->invalidateSessionsForUser( $this );
2661 * Changes credentials of the user.
2663 * This is a convenience wrapper around AuthManager::changeAuthenticationData.
2664 * Note that this can return a status that isOK() but not isGood() on certain types of failures,
2665 * e.g. when no provider handled the change.
2667 * @param array $data A set of authentication data in fieldname => value format. This is the
2668 * same data you would pass the changeauthenticationdata API - 'username', 'password' etc.
2672 public function changeAuthenticationData( array $data ) {
2673 $manager = AuthManager
::singleton();
2674 $reqs = $manager->getAuthenticationRequests( AuthManager
::ACTION_CHANGE
, $this );
2675 $reqs = AuthenticationRequest
::loadRequestsFromSubmission( $reqs, $data );
2677 $status = Status
::newGood( 'ignored' );
2678 foreach ( $reqs as $req ) {
2679 $status->merge( $manager->allowsAuthenticationDataChange( $req ), true );
2681 if ( $status->getValue() === 'ignored' ) {
2682 $status->warning( 'authenticationdatachange-ignored' );
2685 if ( $status->isGood() ) {
2686 foreach ( $reqs as $req ) {
2687 $manager->changeAuthenticationData( $req );
2694 * Get the user's current token.
2695 * @param bool $forceCreation Force the generation of a new token if the
2696 * user doesn't have one (default=true for backwards compatibility).
2697 * @return string|null Token
2699 public function getToken( $forceCreation = true ) {
2700 global $wgAuthenticationTokenVersion;
2703 if ( !$this->mToken
&& $forceCreation ) {
2707 if ( !$this->mToken
) {
2708 // The user doesn't have a token, return null to indicate that.
2710 } elseif ( $this->mToken
=== self
::INVALID_TOKEN
) {
2711 // We return a random value here so existing token checks are very
2713 return MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2714 } elseif ( $wgAuthenticationTokenVersion === null ) {
2715 // $wgAuthenticationTokenVersion not in use, so return the raw secret
2716 return $this->mToken
;
2718 // $wgAuthenticationTokenVersion in use, so hmac it.
2719 $ret = MWCryptHash
::hmac( $wgAuthenticationTokenVersion, $this->mToken
, false );
2721 // The raw hash can be overly long. Shorten it up.
2722 $len = max( 32, self
::TOKEN_LENGTH
);
2723 if ( strlen( $ret ) < $len ) {
2724 // Should never happen, even md5 is 128 bits
2725 throw new \
UnexpectedValueException( 'Hmac returned less than 128 bits' );
2727 return substr( $ret, -$len );
2732 * Set the random token (used for persistent authentication)
2733 * Called from loadDefaults() among other places.
2735 * @param string|bool $token If specified, set the token to this value
2737 public function setToken( $token = false ) {
2739 if ( $this->mToken
=== self
::INVALID_TOKEN
) {
2740 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
2741 ->debug( __METHOD__
. ": Ignoring attempt to set token for system user \"$this\"" );
2742 } elseif ( !$token ) {
2743 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2745 $this->mToken
= $token;
2750 * Set the password for a password reminder or new account email
2752 * @deprecated Removed in 1.27. Use PasswordReset instead.
2753 * @param string $str New password to set or null to set an invalid
2754 * password hash meaning that the user will not be able to use it
2755 * @param bool $throttle If true, reset the throttle timestamp to the present
2757 public function setNewpassword( $str, $throttle = true ) {
2758 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2762 * Get the user's e-mail address
2763 * @return string User's email address
2765 public function getEmail() {
2767 Hooks
::run( 'UserGetEmail', [ $this, &$this->mEmail
] );
2768 return $this->mEmail
;
2772 * Get the timestamp of the user's e-mail authentication
2773 * @return string TS_MW timestamp
2775 public function getEmailAuthenticationTimestamp() {
2777 Hooks
::run( 'UserGetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
2778 return $this->mEmailAuthenticated
;
2782 * Set the user's e-mail address
2783 * @param string $str New e-mail address
2785 public function setEmail( $str ) {
2787 if ( $str == $this->mEmail
) {
2790 $this->invalidateEmail();
2791 $this->mEmail
= $str;
2792 Hooks
::run( 'UserSetEmail', [ $this, &$this->mEmail
] );
2796 * Set the user's e-mail address and a confirmation mail if needed.
2799 * @param string $str New e-mail address
2802 public function setEmailWithConfirmation( $str ) {
2803 global $wgEnableEmail, $wgEmailAuthentication;
2805 if ( !$wgEnableEmail ) {
2806 return Status
::newFatal( 'emaildisabled' );
2809 $oldaddr = $this->getEmail();
2810 if ( $str === $oldaddr ) {
2811 return Status
::newGood( true );
2814 $type = $oldaddr != '' ?
'changed' : 'set';
2815 $notificationResult = null;
2817 if ( $wgEmailAuthentication ) {
2818 // Send the user an email notifying the user of the change in registered
2819 // email address on their previous email address
2820 if ( $type == 'changed' ) {
2821 $change = $str != '' ?
'changed' : 'removed';
2822 $notificationResult = $this->sendMail(
2823 wfMessage( 'notificationemail_subject_' . $change )->text(),
2824 wfMessage( 'notificationemail_body_' . $change,
2825 $this->getRequest()->getIP(),
2832 $this->setEmail( $str );
2834 if ( $str !== '' && $wgEmailAuthentication ) {
2835 // Send a confirmation request to the new address if needed
2836 $result = $this->sendConfirmationMail( $type );
2838 if ( $notificationResult !== null ) {
2839 $result->merge( $notificationResult );
2842 if ( $result->isGood() ) {
2843 // Say to the caller that a confirmation and notification mail has been sent
2844 $result->value
= 'eauth';
2847 $result = Status
::newGood( true );
2854 * Get the user's real name
2855 * @return string User's real name
2857 public function getRealName() {
2858 if ( !$this->isItemLoaded( 'realname' ) ) {
2862 return $this->mRealName
;
2866 * Set the user's real name
2867 * @param string $str New real name
2869 public function setRealName( $str ) {
2871 $this->mRealName
= $str;
2875 * Get the user's current setting for a given option.
2877 * @param string $oname The option to check
2878 * @param string $defaultOverride A default value returned if the option does not exist
2879 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2880 * @return string|null User's current value for the option
2881 * @see getBoolOption()
2882 * @see getIntOption()
2884 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2885 global $wgHiddenPrefs;
2886 $this->loadOptions();
2888 # We want 'disabled' preferences to always behave as the default value for
2889 # users, even if they have set the option explicitly in their settings (ie they
2890 # set it, and then it was disabled removing their ability to change it). But
2891 # we don't want to erase the preferences in the database in case the preference
2892 # is re-enabled again. So don't touch $mOptions, just override the returned value
2893 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2894 return self
::getDefaultOption( $oname );
2897 if ( array_key_exists( $oname, $this->mOptions
) ) {
2898 return $this->mOptions
[$oname];
2900 return $defaultOverride;
2905 * Get all user's options
2907 * @param int $flags Bitwise combination of:
2908 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2909 * to the default value. (Since 1.25)
2912 public function getOptions( $flags = 0 ) {
2913 global $wgHiddenPrefs;
2914 $this->loadOptions();
2915 $options = $this->mOptions
;
2917 # We want 'disabled' preferences to always behave as the default value for
2918 # users, even if they have set the option explicitly in their settings (ie they
2919 # set it, and then it was disabled removing their ability to change it). But
2920 # we don't want to erase the preferences in the database in case the preference
2921 # is re-enabled again. So don't touch $mOptions, just override the returned value
2922 foreach ( $wgHiddenPrefs as $pref ) {
2923 $default = self
::getDefaultOption( $pref );
2924 if ( $default !== null ) {
2925 $options[$pref] = $default;
2929 if ( $flags & self
::GETOPTIONS_EXCLUDE_DEFAULTS
) {
2930 $options = array_diff_assoc( $options, self
::getDefaultOptions() );
2937 * Get the user's current setting for a given option, as a boolean value.
2939 * @param string $oname The option to check
2940 * @return bool User's current value for the option
2943 public function getBoolOption( $oname ) {
2944 return (bool)$this->getOption( $oname );
2948 * Get the user's current setting for a given option, as an integer value.
2950 * @param string $oname The option to check
2951 * @param int $defaultOverride A default value returned if the option does not exist
2952 * @return int User's current value for the option
2955 public function getIntOption( $oname, $defaultOverride = 0 ) {
2956 $val = $this->getOption( $oname );
2958 $val = $defaultOverride;
2960 return intval( $val );
2964 * Set the given option for a user.
2966 * You need to call saveSettings() to actually write to the database.
2968 * @param string $oname The option to set
2969 * @param mixed $val New value to set
2971 public function setOption( $oname, $val ) {
2972 $this->loadOptions();
2974 // Explicitly NULL values should refer to defaults
2975 if ( is_null( $val ) ) {
2976 $val = self
::getDefaultOption( $oname );
2979 $this->mOptions
[$oname] = $val;
2983 * Get a token stored in the preferences (like the watchlist one),
2984 * resetting it if it's empty (and saving changes).
2986 * @param string $oname The option name to retrieve the token from
2987 * @return string|bool User's current value for the option, or false if this option is disabled.
2988 * @see resetTokenFromOption()
2990 * @deprecated since 1.26 Applications should use the OAuth extension
2992 public function getTokenFromOption( $oname ) {
2993 global $wgHiddenPrefs;
2995 $id = $this->getId();
2996 if ( !$id ||
in_array( $oname, $wgHiddenPrefs ) ) {
3000 $token = $this->getOption( $oname );
3002 // Default to a value based on the user token to avoid space
3003 // wasted on storing tokens for all users. When this option
3004 // is set manually by the user, only then is it stored.
3005 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
3012 * Reset a token stored in the preferences (like the watchlist one).
3013 * *Does not* save user's preferences (similarly to setOption()).
3015 * @param string $oname The option name to reset the token in
3016 * @return string|bool New token value, or false if this option is disabled.
3017 * @see getTokenFromOption()
3020 public function resetTokenFromOption( $oname ) {
3021 global $wgHiddenPrefs;
3022 if ( in_array( $oname, $wgHiddenPrefs ) ) {
3026 $token = MWCryptRand
::generateHex( 40 );
3027 $this->setOption( $oname, $token );
3032 * Return a list of the types of user options currently returned by
3033 * User::getOptionKinds().
3035 * Currently, the option kinds are:
3036 * - 'registered' - preferences which are registered in core MediaWiki or
3037 * by extensions using the UserGetDefaultOptions hook.
3038 * - 'registered-multiselect' - as above, using the 'multiselect' type.
3039 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
3040 * - 'userjs' - preferences with names starting with 'userjs-', intended to
3041 * be used by user scripts.
3042 * - 'special' - "preferences" that are not accessible via User::getOptions
3043 * or User::setOptions.
3044 * - 'unused' - preferences about which MediaWiki doesn't know anything.
3045 * These are usually legacy options, removed in newer versions.
3047 * The API (and possibly others) use this function to determine the possible
3048 * option types for validation purposes, so make sure to update this when a
3049 * new option kind is added.
3051 * @see User::getOptionKinds
3052 * @return array Option kinds
3054 public static function listOptionKinds() {
3057 'registered-multiselect',
3058 'registered-checkmatrix',
3066 * Return an associative array mapping preferences keys to the kind of a preference they're
3067 * used for. Different kinds are handled differently when setting or reading preferences.
3069 * See User::listOptionKinds for the list of valid option types that can be provided.
3071 * @see User::listOptionKinds
3072 * @param IContextSource $context
3073 * @param array $options Assoc. array with options keys to check as keys.
3074 * Defaults to $this->mOptions.
3075 * @return array The key => kind mapping data
3077 public function getOptionKinds( IContextSource
$context, $options = null ) {
3078 $this->loadOptions();
3079 if ( $options === null ) {
3080 $options = $this->mOptions
;
3083 $prefs = Preferences
::getPreferences( $this, $context );
3086 // Pull out the "special" options, so they don't get converted as
3087 // multiselect or checkmatrix.
3088 $specialOptions = array_fill_keys( Preferences
::getSaveBlacklist(), true );
3089 foreach ( $specialOptions as $name => $value ) {
3090 unset( $prefs[$name] );
3093 // Multiselect and checkmatrix options are stored in the database with
3094 // one key per option, each having a boolean value. Extract those keys.
3095 $multiselectOptions = [];
3096 foreach ( $prefs as $name => $info ) {
3097 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
3098 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
3099 $opts = HTMLFormField
::flattenOptions( $info['options'] );
3100 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
3102 foreach ( $opts as $value ) {
3103 $multiselectOptions["$prefix$value"] = true;
3106 unset( $prefs[$name] );
3109 $checkmatrixOptions = [];
3110 foreach ( $prefs as $name => $info ) {
3111 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
3112 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
3113 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
3114 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
3115 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
3117 foreach ( $columns as $column ) {
3118 foreach ( $rows as $row ) {
3119 $checkmatrixOptions["$prefix$column-$row"] = true;
3123 unset( $prefs[$name] );
3127 // $value is ignored
3128 foreach ( $options as $key => $value ) {
3129 if ( isset( $prefs[$key] ) ) {
3130 $mapping[$key] = 'registered';
3131 } elseif ( isset( $multiselectOptions[$key] ) ) {
3132 $mapping[$key] = 'registered-multiselect';
3133 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
3134 $mapping[$key] = 'registered-checkmatrix';
3135 } elseif ( isset( $specialOptions[$key] ) ) {
3136 $mapping[$key] = 'special';
3137 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
3138 $mapping[$key] = 'userjs';
3140 $mapping[$key] = 'unused';
3148 * Reset certain (or all) options to the site defaults
3150 * The optional parameter determines which kinds of preferences will be reset.
3151 * Supported values are everything that can be reported by getOptionKinds()
3152 * and 'all', which forces a reset of *all* preferences and overrides everything else.
3154 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
3155 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
3156 * for backwards-compatibility.
3157 * @param IContextSource|null $context Context source used when $resetKinds
3158 * does not contain 'all', passed to getOptionKinds().
3159 * Defaults to RequestContext::getMain() when null.
3161 public function resetOptions(
3162 $resetKinds = [ 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ],
3163 IContextSource
$context = null
3166 $defaultOptions = self
::getDefaultOptions();
3168 if ( !is_array( $resetKinds ) ) {
3169 $resetKinds = [ $resetKinds ];
3172 if ( in_array( 'all', $resetKinds ) ) {
3173 $newOptions = $defaultOptions;
3175 if ( $context === null ) {
3176 $context = RequestContext
::getMain();
3179 $optionKinds = $this->getOptionKinds( $context );
3180 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
3183 // Use default values for the options that should be deleted, and
3184 // copy old values for the ones that shouldn't.
3185 foreach ( $this->mOptions
as $key => $value ) {
3186 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
3187 if ( array_key_exists( $key, $defaultOptions ) ) {
3188 $newOptions[$key] = $defaultOptions[$key];
3191 $newOptions[$key] = $value;
3196 Hooks
::run( 'UserResetAllOptions', [ $this, &$newOptions, $this->mOptions
, $resetKinds ] );
3198 $this->mOptions
= $newOptions;
3199 $this->mOptionsLoaded
= true;
3203 * Get the user's preferred date format.
3204 * @return string User's preferred date format
3206 public function getDatePreference() {
3207 // Important migration for old data rows
3208 if ( is_null( $this->mDatePreference
) ) {
3210 $value = $this->getOption( 'date' );
3211 $map = $wgLang->getDatePreferenceMigrationMap();
3212 if ( isset( $map[$value] ) ) {
3213 $value = $map[$value];
3215 $this->mDatePreference
= $value;
3217 return $this->mDatePreference
;
3221 * Determine based on the wiki configuration and the user's options,
3222 * whether this user must be over HTTPS no matter what.
3226 public function requiresHTTPS() {
3227 global $wgSecureLogin;
3228 if ( !$wgSecureLogin ) {
3231 $https = $this->getBoolOption( 'prefershttps' );
3232 Hooks
::run( 'UserRequiresHTTPS', [ $this, &$https ] );
3234 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
3241 * Get the user preferred stub threshold
3245 public function getStubThreshold() {
3246 global $wgMaxArticleSize; # Maximum article size, in Kb
3247 $threshold = $this->getIntOption( 'stubthreshold' );
3248 if ( $threshold > $wgMaxArticleSize * 1024 ) {
3249 // If they have set an impossible value, disable the preference
3250 // so we can use the parser cache again.
3257 * Get the permissions this user has.
3258 * @return string[] permission names
3260 public function getRights() {
3261 if ( is_null( $this->mRights
) ) {
3262 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
3263 Hooks
::run( 'UserGetRights', [ $this, &$this->mRights
] );
3265 // Deny any rights denied by the user's session, unless this
3266 // endpoint has no sessions.
3267 if ( !defined( 'MW_NO_SESSION' ) ) {
3268 $allowedRights = $this->getRequest()->getSession()->getAllowedUserRights();
3269 if ( $allowedRights !== null ) {
3270 $this->mRights
= array_intersect( $this->mRights
, $allowedRights );
3274 // Force reindexation of rights when a hook has unset one of them
3275 $this->mRights
= array_values( array_unique( $this->mRights
) );
3277 // If block disables login, we should also remove any
3278 // extra rights blocked users might have, in case the
3279 // blocked user has a pre-existing session (T129738).
3280 // This is checked here for cases where people only call
3281 // $user->isAllowed(). It is also checked in Title::checkUserBlock()
3282 // to give a better error message in the common case.
3283 $config = RequestContext
::getMain()->getConfig();
3285 $this->isLoggedIn() &&
3286 $config->get( 'BlockDisablesLogin' ) &&
3290 $this->mRights
= array_intersect( $this->mRights
, $anon->getRights() );
3293 return $this->mRights
;
3297 * Get the list of explicit group memberships this user has.
3298 * The implicit * and user groups are not included.
3299 * @return array Array of String internal group names
3301 public function getGroups() {
3303 $this->loadGroups();
3304 return array_keys( $this->mGroupMemberships
);
3308 * Get the list of explicit group memberships this user has, stored as
3309 * UserGroupMembership objects. Implicit groups are not included.
3311 * @return array Associative array of (group name as string => UserGroupMembership object)
3314 public function getGroupMemberships() {
3316 $this->loadGroups();
3317 return $this->mGroupMemberships
;
3321 * Get the list of implicit group memberships this user has.
3322 * This includes all explicit groups, plus 'user' if logged in,
3323 * '*' for all accounts, and autopromoted groups
3324 * @param bool $recache Whether to avoid the cache
3325 * @return array Array of String internal group names
3327 public function getEffectiveGroups( $recache = false ) {
3328 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
3329 $this->mEffectiveGroups
= array_unique( array_merge(
3330 $this->getGroups(), // explicit groups
3331 $this->getAutomaticGroups( $recache ) // implicit groups
3333 // Avoid PHP 7.1 warning of passing $this by reference
3335 // Hook for additional groups
3336 Hooks
::run( 'UserEffectiveGroups', [ &$user, &$this->mEffectiveGroups
] );
3337 // Force reindexation of groups when a hook has unset one of them
3338 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
3340 return $this->mEffectiveGroups
;
3344 * Get the list of implicit group memberships this user has.
3345 * This includes 'user' if logged in, '*' for all accounts,
3346 * and autopromoted groups
3347 * @param bool $recache Whether to avoid the cache
3348 * @return array Array of String internal group names
3350 public function getAutomaticGroups( $recache = false ) {
3351 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
3352 $this->mImplicitGroups
= [ '*' ];
3353 if ( $this->getId() ) {
3354 $this->mImplicitGroups
[] = 'user';
3356 $this->mImplicitGroups
= array_unique( array_merge(
3357 $this->mImplicitGroups
,
3358 Autopromote
::getAutopromoteGroups( $this )
3362 // Assure data consistency with rights/groups,
3363 // as getEffectiveGroups() depends on this function
3364 $this->mEffectiveGroups
= null;
3367 return $this->mImplicitGroups
;
3371 * Returns the groups the user has belonged to.
3373 * The user may still belong to the returned groups. Compare with getGroups().
3375 * The function will not return groups the user had belonged to before MW 1.17
3377 * @return array Names of the groups the user has belonged to.
3379 public function getFormerGroups() {
3382 if ( is_null( $this->mFormerGroups
) ) {
3383 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3384 ?
wfGetDB( DB_MASTER
)
3385 : wfGetDB( DB_REPLICA
);
3386 $res = $db->select( 'user_former_groups',
3388 [ 'ufg_user' => $this->mId
],
3390 $this->mFormerGroups
= [];
3391 foreach ( $res as $row ) {
3392 $this->mFormerGroups
[] = $row->ufg_group
;
3396 return $this->mFormerGroups
;
3400 * Get the user's edit count.
3401 * @return int|null Null for anonymous users
3403 public function getEditCount() {
3404 if ( !$this->getId() ) {
3408 if ( $this->mEditCount
=== null ) {
3409 /* Populate the count, if it has not been populated yet */
3410 $dbr = wfGetDB( DB_REPLICA
);
3411 // check if the user_editcount field has been initialized
3412 $count = $dbr->selectField(
3413 'user', 'user_editcount',
3414 [ 'user_id' => $this->mId
],
3418 if ( $count === null ) {
3419 // it has not been initialized. do so.
3420 $count = $this->initEditCount();
3422 $this->mEditCount
= $count;
3424 return (int)$this->mEditCount
;
3428 * Add the user to the given group. This takes immediate effect.
3429 * If the user is already in the group, the expiry time will be updated to the new
3430 * expiry time. (If $expiry is omitted or null, the membership will be altered to
3433 * @param string $group Name of the group to add
3434 * @param string $expiry Optional expiry timestamp in any format acceptable to
3435 * wfTimestamp(), or null if the group assignment should not expire
3438 public function addGroup( $group, $expiry = null ) {
3440 $this->loadGroups();
3443 $expiry = wfTimestamp( TS_MW
, $expiry );
3446 if ( !Hooks
::run( 'UserAddGroup', [ $this, &$group, &$expiry ] ) ) {
3450 // create the new UserGroupMembership and put it in the DB
3451 $ugm = new UserGroupMembership( $this->mId
, $group, $expiry );
3452 if ( !$ugm->insert( true ) ) {
3456 $this->mGroupMemberships
[$group] = $ugm;
3458 // Refresh the groups caches, and clear the rights cache so it will be
3459 // refreshed on the next call to $this->getRights().
3460 $this->getEffectiveGroups( true );
3461 $this->mRights
= null;
3463 $this->invalidateCache();
3469 * Remove the user from the given group.
3470 * This takes immediate effect.
3471 * @param string $group Name of the group to remove
3474 public function removeGroup( $group ) {
3477 if ( !Hooks
::run( 'UserRemoveGroup', [ $this, &$group ] ) ) {
3481 $ugm = UserGroupMembership
::getMembership( $this->mId
, $group );
3482 // delete the membership entry
3483 if ( !$ugm ||
!$ugm->delete() ) {
3487 $this->loadGroups();
3488 unset( $this->mGroupMemberships
[$group] );
3490 // Refresh the groups caches, and clear the rights cache so it will be
3491 // refreshed on the next call to $this->getRights().
3492 $this->getEffectiveGroups( true );
3493 $this->mRights
= null;
3495 $this->invalidateCache();
3501 * Get whether the user is logged in
3504 public function isLoggedIn() {
3505 return $this->getId() != 0;
3509 * Get whether the user is anonymous
3512 public function isAnon() {
3513 return !$this->isLoggedIn();
3517 * @return bool Whether this user is flagged as being a bot role account
3520 public function isBot() {
3521 if ( in_array( 'bot', $this->getGroups() ) && $this->isAllowed( 'bot' ) ) {
3526 Hooks
::run( "UserIsBot", [ $this, &$isBot ] );
3532 * Check if user is allowed to access a feature / make an action
3534 * @param string $permissions,... Permissions to test
3535 * @return bool True if user is allowed to perform *any* of the given actions
3537 public function isAllowedAny() {
3538 $permissions = func_get_args();
3539 foreach ( $permissions as $permission ) {
3540 if ( $this->isAllowed( $permission ) ) {
3549 * @param string $permissions,... Permissions to test
3550 * @return bool True if the user is allowed to perform *all* of the given actions
3552 public function isAllowedAll() {
3553 $permissions = func_get_args();
3554 foreach ( $permissions as $permission ) {
3555 if ( !$this->isAllowed( $permission ) ) {
3563 * Internal mechanics of testing a permission
3564 * @param string $action
3567 public function isAllowed( $action = '' ) {
3568 if ( $action === '' ) {
3569 return true; // In the spirit of DWIM
3571 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3572 // by misconfiguration: 0 == 'foo'
3573 return in_array( $action, $this->getRights(), true );
3577 * Check whether to enable recent changes patrol features for this user
3578 * @return bool True or false
3580 public function useRCPatrol() {
3581 global $wgUseRCPatrol;
3582 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3586 * Check whether to enable new pages patrol features for this user
3587 * @return bool True or false
3589 public function useNPPatrol() {
3590 global $wgUseRCPatrol, $wgUseNPPatrol;
3592 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3593 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3598 * Check whether to enable new files patrol features for this user
3599 * @return bool True or false
3601 public function useFilePatrol() {
3602 global $wgUseRCPatrol, $wgUseFilePatrol;
3604 ( $wgUseRCPatrol ||
$wgUseFilePatrol )
3605 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3610 * Get the WebRequest object to use with this object
3612 * @return WebRequest
3614 public function getRequest() {
3615 if ( $this->mRequest
) {
3616 return $this->mRequest
;
3624 * Check the watched status of an article.
3625 * @since 1.22 $checkRights parameter added
3626 * @param Title $title Title of the article to look at
3627 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3628 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3631 public function isWatched( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3632 if ( $title->isWatchable() && ( !$checkRights ||
$this->isAllowed( 'viewmywatchlist' ) ) ) {
3633 return MediaWikiServices
::getInstance()->getWatchedItemStore()->isWatched( $this, $title );
3640 * @since 1.22 $checkRights parameter added
3641 * @param Title $title Title of the article to look at
3642 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3643 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3645 public function addWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3646 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3647 MediaWikiServices
::getInstance()->getWatchedItemStore()->addWatchBatchForUser(
3649 [ $title->getSubjectPage(), $title->getTalkPage() ]
3652 $this->invalidateCache();
3656 * Stop watching an article.
3657 * @since 1.22 $checkRights parameter added
3658 * @param Title $title Title of the article to look at
3659 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3660 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3662 public function removeWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3663 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3664 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
3665 $store->removeWatch( $this, $title->getSubjectPage() );
3666 $store->removeWatch( $this, $title->getTalkPage() );
3668 $this->invalidateCache();
3672 * Clear the user's notification timestamp for the given title.
3673 * If e-notif e-mails are on, they will receive notification mails on
3674 * the next change of the page if it's watched etc.
3675 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3676 * @param Title &$title Title of the article to look at
3677 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3679 public function clearNotification( &$title, $oldid = 0 ) {
3680 global $wgUseEnotif, $wgShowUpdatedMarker;
3682 // Do nothing if the database is locked to writes
3683 if ( wfReadOnly() ) {
3687 // Do nothing if not allowed to edit the watchlist
3688 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3692 // If we're working on user's talk page, we should update the talk page message indicator
3693 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3694 // Avoid PHP 7.1 warning of passing $this by reference
3696 if ( !Hooks
::run( 'UserClearNewTalkNotification', [ &$user, $oldid ] ) ) {
3700 // Try to update the DB post-send and only if needed...
3701 DeferredUpdates
::addCallableUpdate( function () use ( $title, $oldid ) {
3702 if ( !$this->getNewtalk() ) {
3703 return; // no notifications to clear
3706 // Delete the last notifications (they stack up)
3707 $this->setNewtalk( false );
3709 // If there is a new, unseen, revision, use its timestamp
3711 ?
$title->getNextRevisionID( $oldid, Title
::GAID_FOR_UPDATE
)
3714 $this->setNewtalk( true, Revision
::newFromId( $nextid ) );
3719 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3723 if ( $this->isAnon() ) {
3724 // Nothing else to do...
3728 // Only update the timestamp if the page is being watched.
3729 // The query to find out if it is watched is cached both in memcached and per-invocation,
3730 // and when it does have to be executed, it can be on a replica DB
3731 // If this is the user's newtalk page, we always update the timestamp
3733 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3737 MediaWikiServices
::getInstance()->getWatchedItemStore()
3738 ->resetNotificationTimestamp( $this, $title, $force, $oldid );
3742 * Resets all of the given user's page-change notification timestamps.
3743 * If e-notif e-mails are on, they will receive notification mails on
3744 * the next change of any watched page.
3745 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3747 public function clearAllNotifications() {
3748 global $wgUseEnotif, $wgShowUpdatedMarker;
3749 // Do nothing if not allowed to edit the watchlist
3750 if ( wfReadOnly() ||
!$this->isAllowed( 'editmywatchlist' ) ) {
3754 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3755 $this->setNewtalk( false );
3759 $id = $this->getId();
3764 $dbw = wfGetDB( DB_MASTER
);
3765 $asOfTimes = array_unique( $dbw->selectFieldValues(
3767 'wl_notificationtimestamp',
3768 [ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ],
3770 [ 'ORDER BY' => 'wl_notificationtimestamp DESC', 'LIMIT' => 500 ]
3772 if ( !$asOfTimes ) {
3775 // Immediately update the most recent touched rows, which hopefully covers what
3776 // the user sees on the watchlist page before pressing "mark all pages visited"....
3779 [ 'wl_notificationtimestamp' => null ],
3780 [ 'wl_user' => $id, 'wl_notificationtimestamp' => $asOfTimes ],
3783 // ...and finish the older ones in a post-send update with lag checks...
3784 DeferredUpdates
::addUpdate( new AutoCommitUpdate(
3787 function () use ( $dbw, $id ) {
3788 global $wgUpdateRowsPerQuery;
3790 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
3791 $ticket = $lbFactory->getEmptyTransactionTicket( __METHOD__
);
3792 $asOfTimes = array_unique( $dbw->selectFieldValues(
3794 'wl_notificationtimestamp',
3795 [ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ],
3798 foreach ( array_chunk( $asOfTimes, $wgUpdateRowsPerQuery ) as $asOfTimeBatch ) {
3801 [ 'wl_notificationtimestamp' => null ],
3802 [ 'wl_user' => $id, 'wl_notificationtimestamp' => $asOfTimeBatch ],
3805 $lbFactory->commitAndWaitForReplication( __METHOD__
, $ticket );
3809 // We also need to clear here the "you have new message" notification for the own
3810 // user_talk page; it's cleared one page view later in WikiPage::doViewUpdates().
3814 * Compute experienced level based on edit count and registration date.
3816 * @return string 'newcomer', 'learner', or 'experienced'
3818 public function getExperienceLevel() {
3819 global $wgLearnerEdits,
3820 $wgExperiencedUserEdits,
3821 $wgLearnerMemberSince,
3822 $wgExperiencedUserMemberSince;
3824 if ( $this->isAnon() ) {
3828 $editCount = $this->getEditCount();
3829 $registration = $this->getRegistration();
3831 $learnerRegistration = wfTimestamp( TS_MW
, $now - $wgLearnerMemberSince * 86400 );
3832 $experiencedRegistration = wfTimestamp( TS_MW
, $now - $wgExperiencedUserMemberSince * 86400 );
3835 $editCount < $wgLearnerEdits ||
3836 $registration > $learnerRegistration
3840 $editCount > $wgExperiencedUserEdits &&
3841 $registration <= $experiencedRegistration
3843 return 'experienced';
3850 * Set a cookie on the user's client. Wrapper for
3851 * WebResponse::setCookie
3852 * @deprecated since 1.27
3853 * @param string $name Name of the cookie to set
3854 * @param string $value Value to set
3855 * @param int $exp Expiration time, as a UNIX time value;
3856 * if 0 or not specified, use the default $wgCookieExpiration
3857 * @param bool $secure
3858 * true: Force setting the secure attribute when setting the cookie
3859 * false: Force NOT setting the secure attribute when setting the cookie
3860 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3861 * @param array $params Array of options sent passed to WebResponse::setcookie()
3862 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3865 protected function setCookie(
3866 $name, $value, $exp = 0, $secure = null, $params = [], $request = null
3868 wfDeprecated( __METHOD__
, '1.27' );
3869 if ( $request === null ) {
3870 $request = $this->getRequest();
3872 $params['secure'] = $secure;
3873 $request->response()->setCookie( $name, $value, $exp, $params );
3877 * Clear a cookie on the user's client
3878 * @deprecated since 1.27
3879 * @param string $name Name of the cookie to clear
3880 * @param bool $secure
3881 * true: Force setting the secure attribute when setting the cookie
3882 * false: Force NOT setting the secure attribute when setting the cookie
3883 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3884 * @param array $params Array of options sent passed to WebResponse::setcookie()
3886 protected function clearCookie( $name, $secure = null, $params = [] ) {
3887 wfDeprecated( __METHOD__
, '1.27' );
3888 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3892 * Set an extended login cookie on the user's client. The expiry of the cookie
3893 * is controlled by the $wgExtendedLoginCookieExpiration configuration
3896 * @see User::setCookie
3898 * @deprecated since 1.27
3899 * @param string $name Name of the cookie to set
3900 * @param string $value Value to set
3901 * @param bool $secure
3902 * true: Force setting the secure attribute when setting the cookie
3903 * false: Force NOT setting the secure attribute when setting the cookie
3904 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3906 protected function setExtendedLoginCookie( $name, $value, $secure ) {
3907 global $wgExtendedLoginCookieExpiration, $wgCookieExpiration;
3909 wfDeprecated( __METHOD__
, '1.27' );
3912 $exp +
= $wgExtendedLoginCookieExpiration !== null
3913 ?
$wgExtendedLoginCookieExpiration
3914 : $wgCookieExpiration;
3916 $this->setCookie( $name, $value, $exp, $secure );
3920 * Persist this user's session (e.g. set cookies)
3922 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3924 * @param bool $secure Whether to force secure/insecure cookies or use default
3925 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3927 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3929 if ( 0 == $this->mId
) {
3933 $session = $this->getRequest()->getSession();
3934 if ( $request && $session->getRequest() !== $request ) {
3935 $session = $session->sessionWithRequest( $request );
3937 $delay = $session->delaySave();
3939 if ( !$session->getUser()->equals( $this ) ) {
3940 if ( !$session->canSetUser() ) {
3941 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3942 ->warning( __METHOD__
.
3943 ": Cannot save user \"$this\" to a user \"{$session->getUser()}\"'s immutable session"
3947 $session->setUser( $this );
3950 $session->setRememberUser( $rememberMe );
3951 if ( $secure !== null ) {
3952 $session->setForceHTTPS( $secure );
3955 $session->persist();
3957 ScopedCallback
::consume( $delay );
3961 * Log this user out.
3963 public function logout() {
3964 // Avoid PHP 7.1 warning of passing $this by reference
3966 if ( Hooks
::run( 'UserLogout', [ &$user ] ) ) {
3972 * Clear the user's session, and reset the instance cache.
3975 public function doLogout() {
3976 $session = $this->getRequest()->getSession();
3977 if ( !$session->canSetUser() ) {
3978 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3979 ->warning( __METHOD__
. ": Cannot log out of an immutable session" );
3980 $error = 'immutable';
3981 } elseif ( !$session->getUser()->equals( $this ) ) {
3982 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3983 ->warning( __METHOD__
.
3984 ": Cannot log user \"$this\" out of a user \"{$session->getUser()}\"'s session"
3986 // But we still may as well make this user object anon
3987 $this->clearInstanceCache( 'defaults' );
3988 $error = 'wronguser';
3990 $this->clearInstanceCache( 'defaults' );
3991 $delay = $session->delaySave();
3992 $session->unpersist(); // Clear cookies (T127436)
3993 $session->setLoggedOutTimestamp( time() );
3994 $session->setUser( new User
);
3995 $session->set( 'wsUserID', 0 ); // Other code expects this
3996 $session->resetAllTokens();
3997 ScopedCallback
::consume( $delay );
4000 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authevents' )->info( 'Logout', [
4001 'event' => 'logout',
4002 'successful' => $error === false,
4003 'status' => $error ?
: 'success',
4008 * Save this user's settings into the database.
4009 * @todo Only rarely do all these fields need to be set!
4011 public function saveSettings() {
4012 if ( wfReadOnly() ) {
4013 // @TODO: caller should deal with this instead!
4014 // This should really just be an exception.
4015 MWExceptionHandler
::logException( new DBExpectedError(
4017 "Could not update user with ID '{$this->mId}'; DB is read-only."
4023 if ( 0 == $this->mId
) {
4027 // Get a new user_touched that is higher than the old one.
4028 // This will be used for a CAS check as a last-resort safety
4029 // check against race conditions and replica DB lag.
4030 $newTouched = $this->newTouchedTimestamp();
4032 $dbw = wfGetDB( DB_MASTER
);
4033 $dbw->update( 'user',
4035 'user_name' => $this->mName
,
4036 'user_real_name' => $this->mRealName
,
4037 'user_email' => $this->mEmail
,
4038 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
4039 'user_touched' => $dbw->timestamp( $newTouched ),
4040 'user_token' => strval( $this->mToken
),
4041 'user_email_token' => $this->mEmailToken
,
4042 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
4043 ], $this->makeUpdateConditions( $dbw, [ /* WHERE */
4044 'user_id' => $this->mId
,
4048 if ( !$dbw->affectedRows() ) {
4049 // Maybe the problem was a missed cache update; clear it to be safe
4050 $this->clearSharedCache( 'refresh' );
4051 // User was changed in the meantime or loaded with stale data
4052 $from = ( $this->queryFlagsUsed
& self
::READ_LATEST
) ?
'master' : 'replica';
4053 throw new MWException(
4054 "CAS update failed on user_touched for user ID '{$this->mId}' (read from $from);" .
4055 " the version of the user to be saved is older than the current version."
4059 $this->mTouched
= $newTouched;
4060 $this->saveOptions();
4062 Hooks
::run( 'UserSaveSettings', [ $this ] );
4063 $this->clearSharedCache();
4064 $this->getUserPage()->invalidateCache();
4068 * If only this user's username is known, and it exists, return the user ID.
4070 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
4073 public function idForName( $flags = 0 ) {
4074 $s = trim( $this->getName() );
4079 $db = ( ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
)
4080 ?
wfGetDB( DB_MASTER
)
4081 : wfGetDB( DB_REPLICA
);
4083 $options = ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
)
4084 ?
[ 'LOCK IN SHARE MODE' ]
4087 $id = $db->selectField( 'user',
4088 'user_id', [ 'user_name' => $s ], __METHOD__
, $options );
4094 * Add a user to the database, return the user object
4096 * @param string $name Username to add
4097 * @param array $params Array of Strings Non-default parameters to save to
4098 * the database as user_* fields:
4099 * - email: The user's email address.
4100 * - email_authenticated: The email authentication timestamp.
4101 * - real_name: The user's real name.
4102 * - options: An associative array of non-default options.
4103 * - token: Random authentication token. Do not set.
4104 * - registration: Registration timestamp. Do not set.
4106 * @return User|null User object, or null if the username already exists.
4108 public static function createNew( $name, $params = [] ) {
4109 foreach ( [ 'password', 'newpassword', 'newpass_time', 'password_expires' ] as $field ) {
4110 if ( isset( $params[$field] ) ) {
4111 wfDeprecated( __METHOD__
. " with param '$field'", '1.27' );
4112 unset( $params[$field] );
4118 $user->setToken(); // init token
4119 if ( isset( $params['options'] ) ) {
4120 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
4121 unset( $params['options'] );
4123 $dbw = wfGetDB( DB_MASTER
);
4125 $noPass = PasswordFactory
::newInvalidPassword()->toString();
4128 'user_name' => $name,
4129 'user_password' => $noPass,
4130 'user_newpassword' => $noPass,
4131 'user_email' => $user->mEmail
,
4132 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
4133 'user_real_name' => $user->mRealName
,
4134 'user_token' => strval( $user->mToken
),
4135 'user_registration' => $dbw->timestamp( $user->mRegistration
),
4136 'user_editcount' => 0,
4137 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
4139 foreach ( $params as $name => $value ) {
4140 $fields["user_$name"] = $value;
4142 $dbw->insert( 'user', $fields, __METHOD__
, [ 'IGNORE' ] );
4143 if ( $dbw->affectedRows() ) {
4144 $newUser = self
::newFromId( $dbw->insertId() );
4152 * Add this existing user object to the database. If the user already
4153 * exists, a fatal status object is returned, and the user object is
4154 * initialised with the data from the database.
4156 * Previously, this function generated a DB error due to a key conflict
4157 * if the user already existed. Many extension callers use this function
4158 * in code along the lines of:
4160 * $user = User::newFromName( $name );
4161 * if ( !$user->isLoggedIn() ) {
4162 * $user->addToDatabase();
4164 * // do something with $user...
4166 * However, this was vulnerable to a race condition (T18020). By
4167 * initialising the user object if the user exists, we aim to support this
4168 * calling sequence as far as possible.
4170 * Note that if the user exists, this function will acquire a write lock,
4171 * so it is still advisable to make the call conditional on isLoggedIn(),
4172 * and to commit the transaction after calling.
4174 * @throws MWException
4177 public function addToDatabase() {
4179 if ( !$this->mToken
) {
4180 $this->setToken(); // init token
4183 if ( !is_string( $this->mName
) ) {
4184 throw new RuntimeException( "User name field is not set." );
4187 $this->mTouched
= $this->newTouchedTimestamp();
4189 $noPass = PasswordFactory
::newInvalidPassword()->toString();
4191 $dbw = wfGetDB( DB_MASTER
);
4192 $dbw->insert( 'user',
4194 'user_name' => $this->mName
,
4195 'user_password' => $noPass,
4196 'user_newpassword' => $noPass,
4197 'user_email' => $this->mEmail
,
4198 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
4199 'user_real_name' => $this->mRealName
,
4200 'user_token' => strval( $this->mToken
),
4201 'user_registration' => $dbw->timestamp( $this->mRegistration
),
4202 'user_editcount' => 0,
4203 'user_touched' => $dbw->timestamp( $this->mTouched
),
4207 if ( !$dbw->affectedRows() ) {
4208 // Use locking reads to bypass any REPEATABLE-READ snapshot.
4209 $this->mId
= $dbw->selectField(
4212 [ 'user_name' => $this->mName
],
4214 [ 'LOCK IN SHARE MODE' ]
4218 if ( $this->loadFromDatabase( self
::READ_LOCKING
) ) {
4223 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
4224 "to insert user '{$this->mName}' row, but it was not present in select!" );
4226 return Status
::newFatal( 'userexists' );
4228 $this->mId
= $dbw->insertId();
4229 self
::$idCacheByName[$this->mName
] = $this->mId
;
4231 // Clear instance cache other than user table data, which is already accurate
4232 $this->clearInstanceCache();
4234 $this->saveOptions();
4235 return Status
::newGood();
4239 * If this user is logged-in and blocked,
4240 * block any IP address they've successfully logged in from.
4241 * @return bool A block was spread
4243 public function spreadAnyEditBlock() {
4244 if ( $this->isLoggedIn() && $this->isBlocked() ) {
4245 return $this->spreadBlock();
4252 * If this (non-anonymous) user is blocked,
4253 * block the IP address they've successfully logged in from.
4254 * @return bool A block was spread
4256 protected function spreadBlock() {
4257 wfDebug( __METHOD__
. "()\n" );
4259 if ( $this->mId
== 0 ) {
4263 $userblock = Block
::newFromTarget( $this->getName() );
4264 if ( !$userblock ) {
4268 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
4272 * Get whether the user is explicitly blocked from account creation.
4273 * @return bool|Block
4275 public function isBlockedFromCreateAccount() {
4276 $this->getBlockedStatus();
4277 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
4278 return $this->mBlock
;
4281 # T15611: if the IP address the user is trying to create an account from is
4282 # blocked with createaccount disabled, prevent new account creation there even
4283 # when the user is logged in
4284 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
4285 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
4287 return $this->mBlockedFromCreateAccount
instanceof Block
4288 && $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
4289 ?
$this->mBlockedFromCreateAccount
4294 * Get whether the user is blocked from using Special:Emailuser.
4297 public function isBlockedFromEmailuser() {
4298 $this->getBlockedStatus();
4299 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
4303 * Get whether the user is allowed to create an account.
4306 public function isAllowedToCreateAccount() {
4307 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
4311 * Get this user's personal page title.
4313 * @return Title User's personal page title
4315 public function getUserPage() {
4316 return Title
::makeTitle( NS_USER
, $this->getName() );
4320 * Get this user's talk page title.
4322 * @return Title User's talk page title
4324 public function getTalkPage() {
4325 $title = $this->getUserPage();
4326 return $title->getTalkPage();
4330 * Determine whether the user is a newbie. Newbies are either
4331 * anonymous IPs, or the most recently created accounts.
4334 public function isNewbie() {
4335 return !$this->isAllowed( 'autoconfirmed' );
4339 * Check to see if the given clear-text password is one of the accepted passwords
4340 * @deprecated since 1.27, use AuthManager instead
4341 * @param string $password User password
4342 * @return bool True if the given password is correct, otherwise False
4344 public function checkPassword( $password ) {
4345 $manager = AuthManager
::singleton();
4346 $reqs = AuthenticationRequest
::loadRequestsFromSubmission(
4347 $manager->getAuthenticationRequests( AuthManager
::ACTION_LOGIN
),
4349 'username' => $this->getName(),
4350 'password' => $password,
4353 $res = AuthManager
::singleton()->beginAuthentication( $reqs, 'null:' );
4354 switch ( $res->status
) {
4355 case AuthenticationResponse
::PASS
:
4357 case AuthenticationResponse
::FAIL
:
4358 // Hope it's not a PreAuthenticationProvider that failed...
4359 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
4360 ->info( __METHOD__
. ': Authentication failed: ' . $res->message
->plain() );
4363 throw new BadMethodCallException(
4364 'AuthManager returned a response unsupported by ' . __METHOD__
4370 * Check if the given clear-text password matches the temporary password
4371 * sent by e-mail for password reset operations.
4373 * @deprecated since 1.27, use AuthManager instead
4374 * @param string $plaintext
4375 * @return bool True if matches, false otherwise
4377 public function checkTemporaryPassword( $plaintext ) {
4378 // Can't check the temporary password individually.
4379 return $this->checkPassword( $plaintext );
4383 * Initialize (if necessary) and return a session token value
4384 * which can be used in edit forms to show that the user's
4385 * login credentials aren't being hijacked with a foreign form
4389 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4390 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4391 * @return MediaWiki\Session\Token The new edit token
4393 public function getEditTokenObject( $salt = '', $request = null ) {
4394 if ( $this->isAnon() ) {
4395 return new LoggedOutEditToken();
4399 $request = $this->getRequest();
4401 return $request->getSession()->getToken( $salt );
4405 * Initialize (if necessary) and return a session token value
4406 * which can be used in edit forms to show that the user's
4407 * login credentials aren't being hijacked with a foreign form
4410 * The $salt for 'edit' and 'csrf' tokens is the default (empty string).
4413 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4414 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4415 * @return string The new edit token
4417 public function getEditToken( $salt = '', $request = null ) {
4418 return $this->getEditTokenObject( $salt, $request )->toString();
4422 * Get the embedded timestamp from a token.
4423 * @deprecated since 1.27, use \MediaWiki\Session\Token::getTimestamp instead.
4424 * @param string $val Input token
4427 public static function getEditTokenTimestamp( $val ) {
4428 wfDeprecated( __METHOD__
, '1.27' );
4429 return MediaWiki\Session\Token
::getTimestamp( $val );
4433 * Check given value against the token value stored in the session.
4434 * A match should confirm that the form was submitted from the
4435 * user's own login session, not a form submission from a third-party
4438 * @param string $val Input value to compare
4439 * @param string $salt Optional function-specific data for hashing
4440 * @param WebRequest|null $request Object to use or null to use $wgRequest
4441 * @param int $maxage Fail tokens older than this, in seconds
4442 * @return bool Whether the token matches
4444 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4445 return $this->getEditTokenObject( $salt, $request )->match( $val, $maxage );
4449 * Check given value against the token value stored in the session,
4450 * ignoring the suffix.
4452 * @param string $val Input value to compare
4453 * @param string $salt Optional function-specific data for hashing
4454 * @param WebRequest|null $request Object to use or null to use $wgRequest
4455 * @param int $maxage Fail tokens older than this, in seconds
4456 * @return bool Whether the token matches
4458 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4459 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . Token
::SUFFIX
;
4460 return $this->matchEditToken( $val, $salt, $request, $maxage );
4464 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4465 * mail to the user's given address.
4467 * @param string $type Message to send, either "created", "changed" or "set"
4470 public function sendConfirmationMail( $type = 'created' ) {
4472 $expiration = null; // gets passed-by-ref and defined in next line.
4473 $token = $this->confirmationToken( $expiration );
4474 $url = $this->confirmationTokenUrl( $token );
4475 $invalidateURL = $this->invalidationTokenUrl( $token );
4476 $this->saveSettings();
4478 if ( $type == 'created' ||
$type === false ) {
4479 $message = 'confirmemail_body';
4480 } elseif ( $type === true ) {
4481 $message = 'confirmemail_body_changed';
4483 // Messages: confirmemail_body_changed, confirmemail_body_set
4484 $message = 'confirmemail_body_' . $type;
4487 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4488 wfMessage( $message,
4489 $this->getRequest()->getIP(),
4492 $wgLang->userTimeAndDate( $expiration, $this ),
4494 $wgLang->userDate( $expiration, $this ),
4495 $wgLang->userTime( $expiration, $this ) )->text() );
4499 * Send an e-mail to this user's account. Does not check for
4500 * confirmed status or validity.
4502 * @param string $subject Message subject
4503 * @param string $body Message body
4504 * @param User|null $from Optional sending user; if unspecified, default
4505 * $wgPasswordSender will be used.
4506 * @param string $replyto Reply-To address
4509 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4510 global $wgPasswordSender;
4512 if ( $from instanceof User
) {
4513 $sender = MailAddress
::newFromUser( $from );
4515 $sender = new MailAddress( $wgPasswordSender,
4516 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4518 $to = MailAddress
::newFromUser( $this );
4520 return UserMailer
::send( $to, $sender, $subject, $body, [
4521 'replyTo' => $replyto,
4526 * Generate, store, and return a new e-mail confirmation code.
4527 * A hash (unsalted, since it's used as a key) is stored.
4529 * @note Call saveSettings() after calling this function to commit
4530 * this change to the database.
4532 * @param string &$expiration Accepts the expiration time
4533 * @return string New token
4535 protected function confirmationToken( &$expiration ) {
4536 global $wgUserEmailConfirmationTokenExpiry;
4538 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4539 $expiration = wfTimestamp( TS_MW
, $expires );
4541 $token = MWCryptRand
::generateHex( 32 );
4542 $hash = md5( $token );
4543 $this->mEmailToken
= $hash;
4544 $this->mEmailTokenExpires
= $expiration;
4549 * Return a URL the user can use to confirm their email address.
4550 * @param string $token Accepts the email confirmation token
4551 * @return string New token URL
4553 protected function confirmationTokenUrl( $token ) {
4554 return $this->getTokenUrl( 'ConfirmEmail', $token );
4558 * Return a URL the user can use to invalidate their email address.
4559 * @param string $token Accepts the email confirmation token
4560 * @return string New token URL
4562 protected function invalidationTokenUrl( $token ) {
4563 return $this->getTokenUrl( 'InvalidateEmail', $token );
4567 * Internal function to format the e-mail validation/invalidation URLs.
4568 * This uses a quickie hack to use the
4569 * hardcoded English names of the Special: pages, for ASCII safety.
4571 * @note Since these URLs get dropped directly into emails, using the
4572 * short English names avoids insanely long URL-encoded links, which
4573 * also sometimes can get corrupted in some browsers/mailers
4574 * (T8957 with Gmail and Internet Explorer).
4576 * @param string $page Special page
4577 * @param string $token Token
4578 * @return string Formatted URL
4580 protected function getTokenUrl( $page, $token ) {
4581 // Hack to bypass localization of 'Special:'
4582 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4583 return $title->getCanonicalURL();
4587 * Mark the e-mail address confirmed.
4589 * @note Call saveSettings() after calling this function to commit the change.
4593 public function confirmEmail() {
4594 // Check if it's already confirmed, so we don't touch the database
4595 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4596 if ( !$this->isEmailConfirmed() ) {
4597 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4598 Hooks
::run( 'ConfirmEmailComplete', [ $this ] );
4604 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4605 * address if it was already confirmed.
4607 * @note Call saveSettings() after calling this function to commit the change.
4608 * @return bool Returns true
4610 public function invalidateEmail() {
4612 $this->mEmailToken
= null;
4613 $this->mEmailTokenExpires
= null;
4614 $this->setEmailAuthenticationTimestamp( null );
4616 Hooks
::run( 'InvalidateEmailComplete', [ $this ] );
4621 * Set the e-mail authentication timestamp.
4622 * @param string $timestamp TS_MW timestamp
4624 public function setEmailAuthenticationTimestamp( $timestamp ) {
4626 $this->mEmailAuthenticated
= $timestamp;
4627 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
4631 * Is this user allowed to send e-mails within limits of current
4632 * site configuration?
4635 public function canSendEmail() {
4636 global $wgEnableEmail, $wgEnableUserEmail;
4637 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4640 $canSend = $this->isEmailConfirmed();
4641 // Avoid PHP 7.1 warning of passing $this by reference
4643 Hooks
::run( 'UserCanSendEmail', [ &$user, &$canSend ] );
4648 * Is this user allowed to receive e-mails within limits of current
4649 * site configuration?
4652 public function canReceiveEmail() {
4653 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4657 * Is this user's e-mail address valid-looking and confirmed within
4658 * limits of the current site configuration?
4660 * @note If $wgEmailAuthentication is on, this may require the user to have
4661 * confirmed their address by returning a code or using a password
4662 * sent to the address from the wiki.
4666 public function isEmailConfirmed() {
4667 global $wgEmailAuthentication;
4669 // Avoid PHP 7.1 warning of passing $this by reference
4672 if ( Hooks
::run( 'EmailConfirmed', [ &$user, &$confirmed ] ) ) {
4673 if ( $this->isAnon() ) {
4676 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4679 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4689 * Check whether there is an outstanding request for e-mail confirmation.
4692 public function isEmailConfirmationPending() {
4693 global $wgEmailAuthentication;
4694 return $wgEmailAuthentication &&
4695 !$this->isEmailConfirmed() &&
4696 $this->mEmailToken
&&
4697 $this->mEmailTokenExpires
> wfTimestamp();
4701 * Get the timestamp of account creation.
4703 * @return string|bool|null Timestamp of account creation, false for
4704 * non-existent/anonymous user accounts, or null if existing account
4705 * but information is not in database.
4707 public function getRegistration() {
4708 if ( $this->isAnon() ) {
4712 return $this->mRegistration
;
4716 * Get the timestamp of the first edit
4718 * @return string|bool Timestamp of first edit, or false for
4719 * non-existent/anonymous user accounts.
4721 public function getFirstEditTimestamp() {
4722 if ( $this->getId() == 0 ) {
4723 return false; // anons
4725 $dbr = wfGetDB( DB_REPLICA
);
4726 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4727 [ 'rev_user' => $this->getId() ],
4729 [ 'ORDER BY' => 'rev_timestamp ASC' ]
4732 return false; // no edits
4734 return wfTimestamp( TS_MW
, $time );
4738 * Get the permissions associated with a given list of groups
4740 * @param array $groups Array of Strings List of internal group names
4741 * @return array Array of Strings List of permission key names for given groups combined
4743 public static function getGroupPermissions( $groups ) {
4744 global $wgGroupPermissions, $wgRevokePermissions;
4746 // grant every granted permission first
4747 foreach ( $groups as $group ) {
4748 if ( isset( $wgGroupPermissions[$group] ) ) {
4749 $rights = array_merge( $rights,
4750 // array_filter removes empty items
4751 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4754 // now revoke the revoked permissions
4755 foreach ( $groups as $group ) {
4756 if ( isset( $wgRevokePermissions[$group] ) ) {
4757 $rights = array_diff( $rights,
4758 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4761 return array_unique( $rights );
4765 * Get all the groups who have a given permission
4767 * @param string $role Role to check
4768 * @return array Array of Strings List of internal group names with the given permission
4770 public static function getGroupsWithPermission( $role ) {
4771 global $wgGroupPermissions;
4772 $allowedGroups = [];
4773 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4774 if ( self
::groupHasPermission( $group, $role ) ) {
4775 $allowedGroups[] = $group;
4778 return $allowedGroups;
4782 * Check, if the given group has the given permission
4784 * If you're wanting to check whether all users have a permission, use
4785 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4789 * @param string $group Group to check
4790 * @param string $role Role to check
4793 public static function groupHasPermission( $group, $role ) {
4794 global $wgGroupPermissions, $wgRevokePermissions;
4795 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4796 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4800 * Check if all users may be assumed to have the given permission
4802 * We generally assume so if the right is granted to '*' and isn't revoked
4803 * on any group. It doesn't attempt to take grants or other extension
4804 * limitations on rights into account in the general case, though, as that
4805 * would require it to always return false and defeat the purpose.
4806 * Specifically, session-based rights restrictions (such as OAuth or bot
4807 * passwords) are applied based on the current session.
4810 * @param string $right Right to check
4813 public static function isEveryoneAllowed( $right ) {
4814 global $wgGroupPermissions, $wgRevokePermissions;
4817 // Use the cached results, except in unit tests which rely on
4818 // being able change the permission mid-request
4819 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4820 return $cache[$right];
4823 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4824 $cache[$right] = false;
4828 // If it's revoked anywhere, then everyone doesn't have it
4829 foreach ( $wgRevokePermissions as $rights ) {
4830 if ( isset( $rights[$right] ) && $rights[$right] ) {
4831 $cache[$right] = false;
4836 // Remove any rights that aren't allowed to the global-session user,
4837 // unless there are no sessions for this endpoint.
4838 if ( !defined( 'MW_NO_SESSION' ) ) {
4839 $allowedRights = SessionManager
::getGlobalSession()->getAllowedUserRights();
4840 if ( $allowedRights !== null && !in_array( $right, $allowedRights, true ) ) {
4841 $cache[$right] = false;
4846 // Allow extensions to say false
4847 if ( !Hooks
::run( 'UserIsEveryoneAllowed', [ $right ] ) ) {
4848 $cache[$right] = false;
4852 $cache[$right] = true;
4857 * Get the localized descriptive name for a group, if it exists
4858 * @deprecated since 1.29 Use UserGroupMembership::getGroupName instead
4860 * @param string $group Internal group name
4861 * @return string Localized descriptive group name
4863 public static function getGroupName( $group ) {
4864 wfDeprecated( __METHOD__
, '1.29' );
4865 return UserGroupMembership
::getGroupName( $group );
4869 * Get the localized descriptive name for a member of a group, if it exists
4870 * @deprecated since 1.29 Use UserGroupMembership::getGroupMemberName instead
4872 * @param string $group Internal group name
4873 * @param string $username Username for gender (since 1.19)
4874 * @return string Localized name for group member
4876 public static function getGroupMember( $group, $username = '#' ) {
4877 wfDeprecated( __METHOD__
, '1.29' );
4878 return UserGroupMembership
::getGroupMemberName( $group, $username );
4882 * Return the set of defined explicit groups.
4883 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4884 * are not included, as they are defined automatically, not in the database.
4885 * @return array Array of internal group names
4887 public static function getAllGroups() {
4888 global $wgGroupPermissions, $wgRevokePermissions;
4890 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4891 self
::getImplicitGroups()
4896 * Get a list of all available permissions.
4897 * @return string[] Array of permission names
4899 public static function getAllRights() {
4900 if ( self
::$mAllRights === false ) {
4901 global $wgAvailableRights;
4902 if ( count( $wgAvailableRights ) ) {
4903 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
4905 self
::$mAllRights = self
::$mCoreRights;
4907 Hooks
::run( 'UserGetAllRights', [ &self
::$mAllRights ] );
4909 return self
::$mAllRights;
4913 * Get a list of implicit groups
4914 * @return array Array of Strings Array of internal group names
4916 public static function getImplicitGroups() {
4917 global $wgImplicitGroups;
4919 $groups = $wgImplicitGroups;
4920 # Deprecated, use $wgImplicitGroups instead
4921 Hooks
::run( 'UserGetImplicitGroups', [ &$groups ], '1.25' );
4927 * Get the title of a page describing a particular group
4928 * @deprecated since 1.29 Use UserGroupMembership::getGroupPage instead
4930 * @param string $group Internal group name
4931 * @return Title|bool Title of the page if it exists, false otherwise
4933 public static function getGroupPage( $group ) {
4934 wfDeprecated( __METHOD__
, '1.29' );
4935 return UserGroupMembership
::getGroupPage( $group );
4939 * Create a link to the group in HTML, if available;
4940 * else return the group name.
4941 * @deprecated since 1.29 Use UserGroupMembership::getLink instead, or
4942 * make the link yourself if you need custom text
4944 * @param string $group Internal name of the group
4945 * @param string $text The text of the link
4946 * @return string HTML link to the group
4948 public static function makeGroupLinkHTML( $group, $text = '' ) {
4949 wfDeprecated( __METHOD__
, '1.29' );
4951 if ( $text == '' ) {
4952 $text = UserGroupMembership
::getGroupName( $group );
4954 $title = UserGroupMembership
::getGroupPage( $group );
4956 return MediaWikiServices
::getInstance()
4957 ->getLinkRenderer()->makeLink( $title, $text );
4959 return htmlspecialchars( $text );
4964 * Create a link to the group in Wikitext, if available;
4965 * else return the group name.
4966 * @deprecated since 1.29 Use UserGroupMembership::getLink instead, or
4967 * make the link yourself if you need custom text
4969 * @param string $group Internal name of the group
4970 * @param string $text The text of the link
4971 * @return string Wikilink to the group
4973 public static function makeGroupLinkWiki( $group, $text = '' ) {
4974 wfDeprecated( __METHOD__
, '1.29' );
4976 if ( $text == '' ) {
4977 $text = UserGroupMembership
::getGroupName( $group );
4979 $title = UserGroupMembership
::getGroupPage( $group );
4981 $page = $title->getFullText();
4982 return "[[$page|$text]]";
4989 * Returns an array of the groups that a particular group can add/remove.
4991 * @param string $group The group to check for whether it can add/remove
4992 * @return array Array( 'add' => array( addablegroups ),
4993 * 'remove' => array( removablegroups ),
4994 * 'add-self' => array( addablegroups to self),
4995 * 'remove-self' => array( removable groups from self) )
4997 public static function changeableByGroup( $group ) {
4998 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
5007 if ( empty( $wgAddGroups[$group] ) ) {
5008 // Don't add anything to $groups
5009 } elseif ( $wgAddGroups[$group] === true ) {
5010 // You get everything
5011 $groups['add'] = self
::getAllGroups();
5012 } elseif ( is_array( $wgAddGroups[$group] ) ) {
5013 $groups['add'] = $wgAddGroups[$group];
5016 // Same thing for remove
5017 if ( empty( $wgRemoveGroups[$group] ) ) {
5019 } elseif ( $wgRemoveGroups[$group] === true ) {
5020 $groups['remove'] = self
::getAllGroups();
5021 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
5022 $groups['remove'] = $wgRemoveGroups[$group];
5025 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
5026 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
5027 foreach ( $wgGroupsAddToSelf as $key => $value ) {
5028 if ( is_int( $key ) ) {
5029 $wgGroupsAddToSelf['user'][] = $value;
5034 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
5035 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
5036 if ( is_int( $key ) ) {
5037 $wgGroupsRemoveFromSelf['user'][] = $value;
5042 // Now figure out what groups the user can add to him/herself
5043 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
5045 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
5046 // No idea WHY this would be used, but it's there
5047 $groups['add-self'] = self
::getAllGroups();
5048 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
5049 $groups['add-self'] = $wgGroupsAddToSelf[$group];
5052 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
5054 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
5055 $groups['remove-self'] = self
::getAllGroups();
5056 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
5057 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
5064 * Returns an array of groups that this user can add and remove
5065 * @return array Array( 'add' => array( addablegroups ),
5066 * 'remove' => array( removablegroups ),
5067 * 'add-self' => array( addablegroups to self),
5068 * 'remove-self' => array( removable groups from self) )
5070 public function changeableGroups() {
5071 if ( $this->isAllowed( 'userrights' ) ) {
5072 // This group gives the right to modify everything (reverse-
5073 // compatibility with old "userrights lets you change
5075 // Using array_merge to make the groups reindexed
5076 $all = array_merge( self
::getAllGroups() );
5085 // Okay, it's not so simple, we will have to go through the arrays
5092 $addergroups = $this->getEffectiveGroups();
5094 foreach ( $addergroups as $addergroup ) {
5095 $groups = array_merge_recursive(
5096 $groups, $this->changeableByGroup( $addergroup )
5098 $groups['add'] = array_unique( $groups['add'] );
5099 $groups['remove'] = array_unique( $groups['remove'] );
5100 $groups['add-self'] = array_unique( $groups['add-self'] );
5101 $groups['remove-self'] = array_unique( $groups['remove-self'] );
5107 * Deferred version of incEditCountImmediate()
5109 * This function, rather than incEditCountImmediate(), should be used for
5110 * most cases as it avoids potential deadlocks caused by concurrent editing.
5112 public function incEditCount() {
5113 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle(
5115 $this->incEditCountImmediate();
5122 * Increment the user's edit-count field.
5123 * Will have no effect for anonymous users.
5126 public function incEditCountImmediate() {
5127 if ( $this->isAnon() ) {
5131 $dbw = wfGetDB( DB_MASTER
);
5132 // No rows will be "affected" if user_editcount is NULL
5135 [ 'user_editcount=user_editcount+1' ],
5136 [ 'user_id' => $this->getId(), 'user_editcount IS NOT NULL' ],
5139 // Lazy initialization check...
5140 if ( $dbw->affectedRows() == 0 ) {
5141 // Now here's a goddamn hack...
5142 $dbr = wfGetDB( DB_REPLICA
);
5143 if ( $dbr !== $dbw ) {
5144 // If we actually have a replica DB server, the count is
5145 // at least one behind because the current transaction
5146 // has not been committed and replicated.
5147 $this->mEditCount
= $this->initEditCount( 1 );
5149 // But if DB_REPLICA is selecting the master, then the
5150 // count we just read includes the revision that was
5151 // just added in the working transaction.
5152 $this->mEditCount
= $this->initEditCount();
5155 if ( $this->mEditCount
=== null ) {
5156 $this->getEditCount();
5157 $dbr = wfGetDB( DB_REPLICA
);
5158 $this->mEditCount +
= ( $dbr !== $dbw ) ?
1 : 0;
5160 $this->mEditCount++
;
5163 // Edit count in user cache too
5164 $this->invalidateCache();
5168 * Initialize user_editcount from data out of the revision table
5170 * @param int $add Edits to add to the count from the revision table
5171 * @return int Number of edits
5173 protected function initEditCount( $add = 0 ) {
5174 // Pull from a replica DB to be less cruel to servers
5175 // Accuracy isn't the point anyway here
5176 $dbr = wfGetDB( DB_REPLICA
);
5177 $count = (int)$dbr->selectField(
5180 [ 'rev_user' => $this->getId() ],
5183 $count = $count +
$add;
5185 $dbw = wfGetDB( DB_MASTER
);
5188 [ 'user_editcount' => $count ],
5189 [ 'user_id' => $this->getId() ],
5197 * Get the description of a given right
5200 * @param string $right Right to query
5201 * @return string Localized description of the right
5203 public static function getRightDescription( $right ) {
5204 $key = "right-$right";
5205 $msg = wfMessage( $key );
5206 return $msg->isDisabled() ?
$right : $msg->text();
5210 * Get the name of a given grant
5213 * @param string $grant Grant to query
5214 * @return string Localized name of the grant
5216 public static function getGrantName( $grant ) {
5217 $key = "grant-$grant";
5218 $msg = wfMessage( $key );
5219 return $msg->isDisabled() ?
$grant : $msg->text();
5223 * Add a newuser log entry for this user.
5224 * Before 1.19 the return value was always true.
5226 * @deprecated since 1.27, AuthManager handles logging
5227 * @param string|bool $action Account creation type.
5228 * - String, one of the following values:
5229 * - 'create' for an anonymous user creating an account for himself.
5230 * This will force the action's performer to be the created user itself,
5231 * no matter the value of $wgUser
5232 * - 'create2' for a logged in user creating an account for someone else
5233 * - 'byemail' when the created user will receive its password by e-mail
5234 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
5235 * - Boolean means whether the account was created by e-mail (deprecated):
5236 * - true will be converted to 'byemail'
5237 * - false will be converted to 'create' if this object is the same as
5238 * $wgUser and to 'create2' otherwise
5239 * @param string $reason User supplied reason
5242 public function addNewUserLogEntry( $action = false, $reason = '' ) {
5243 return true; // disabled
5247 * Add an autocreate newuser log entry for this user
5248 * Used by things like CentralAuth and perhaps other authplugins.
5249 * Consider calling addNewUserLogEntry() directly instead.
5251 * @deprecated since 1.27, AuthManager handles logging
5254 public function addNewUserLogEntryAutoCreate() {
5255 $this->addNewUserLogEntry( 'autocreate' );
5261 * Load the user options either from cache, the database or an array
5263 * @param array $data Rows for the current user out of the user_properties table
5265 protected function loadOptions( $data = null ) {
5270 if ( $this->mOptionsLoaded
) {
5274 $this->mOptions
= self
::getDefaultOptions();
5276 if ( !$this->getId() ) {
5277 // For unlogged-in users, load language/variant options from request.
5278 // There's no need to do it for logged-in users: they can set preferences,
5279 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5280 // so don't override user's choice (especially when the user chooses site default).
5281 $variant = $wgContLang->getDefaultVariant();
5282 $this->mOptions
['variant'] = $variant;
5283 $this->mOptions
['language'] = $variant;
5284 $this->mOptionsLoaded
= true;
5288 // Maybe load from the object
5289 if ( !is_null( $this->mOptionOverrides
) ) {
5290 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5291 foreach ( $this->mOptionOverrides
as $key => $value ) {
5292 $this->mOptions
[$key] = $value;
5295 if ( !is_array( $data ) ) {
5296 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5297 // Load from database
5298 $dbr = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
5299 ?
wfGetDB( DB_MASTER
)
5300 : wfGetDB( DB_REPLICA
);
5302 $res = $dbr->select(
5304 [ 'up_property', 'up_value' ],
5305 [ 'up_user' => $this->getId() ],
5309 $this->mOptionOverrides
= [];
5311 foreach ( $res as $row ) {
5312 // Convert '0' to 0. PHP's boolean conversion considers them both
5313 // false, but e.g. JavaScript considers the former as true.
5314 // @todo: T54542 Somehow determine the desired type (string/int/bool)
5315 // and convert all values here.
5316 if ( $row->up_value
=== '0' ) {
5319 $data[$row->up_property
] = $row->up_value
;
5323 // Convert the email blacklist from a new line delimited string
5324 // to an array of ids.
5325 if ( isset( $data['email-blacklist'] ) && $data['email-blacklist'] ) {
5326 $data['email-blacklist'] = array_map( 'intval', explode( "\n", $data['email-blacklist'] ) );
5329 foreach ( $data as $property => $value ) {
5330 $this->mOptionOverrides
[$property] = $value;
5331 $this->mOptions
[$property] = $value;
5335 $this->mOptionsLoaded
= true;
5337 Hooks
::run( 'UserLoadOptions', [ $this, &$this->mOptions
] );
5341 * Saves the non-default options for this user, as previously set e.g. via
5342 * setOption(), in the database's "user_properties" (preferences) table.
5343 * Usually used via saveSettings().
5345 protected function saveOptions() {
5346 $this->loadOptions();
5348 // Not using getOptions(), to keep hidden preferences in database
5349 $saveOptions = $this->mOptions
;
5351 // Convert usernames to ids.
5352 if ( isset( $this->mOptions
['email-blacklist'] ) ) {
5353 if ( $this->mOptions
['email-blacklist'] ) {
5354 $value = $this->mOptions
['email-blacklist'];
5355 // Email Blacklist may be an array of ids or a string of new line
5356 // delimnated user names.
5357 if ( is_array( $value ) ) {
5358 $ids = array_filter( $value, 'is_numeric' );
5360 $lookup = CentralIdLookup
::factory();
5361 $ids = $lookup->centralIdsFromNames( explode( "\n", $value ), $this );
5363 $this->mOptions
['email-blacklist'] = $ids;
5364 $saveOptions['email-blacklist'] = implode( "\n", $this->mOptions
['email-blacklist'] );
5366 // If the blacklist is empty, set it to null rather than an empty string.
5367 $this->mOptions
['email-blacklist'] = null;
5371 // Allow hooks to abort, for instance to save to a global profile.
5372 // Reset options to default state before saving.
5373 if ( !Hooks
::run( 'UserSaveOptions', [ $this, &$saveOptions ] ) ) {
5377 $userId = $this->getId();
5379 $insert_rows = []; // all the new preference rows
5380 foreach ( $saveOptions as $key => $value ) {
5381 // Don't bother storing default values
5382 $defaultOption = self
::getDefaultOption( $key );
5383 if ( ( $defaultOption === null && $value !== false && $value !== null )
5384 ||
$value != $defaultOption
5387 'up_user' => $userId,
5388 'up_property' => $key,
5389 'up_value' => $value,
5394 $dbw = wfGetDB( DB_MASTER
);
5396 $res = $dbw->select( 'user_properties',
5397 [ 'up_property', 'up_value' ], [ 'up_user' => $userId ], __METHOD__
);
5399 // Find prior rows that need to be removed or updated. These rows will
5400 // all be deleted (the latter so that INSERT IGNORE applies the new values).
5402 foreach ( $res as $row ) {
5403 if ( !isset( $saveOptions[$row->up_property
] )
5404 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
5406 $keysDelete[] = $row->up_property
;
5410 if ( count( $keysDelete ) ) {
5411 // Do the DELETE by PRIMARY KEY for prior rows.
5412 // In the past a very large portion of calls to this function are for setting
5413 // 'rememberpassword' for new accounts (a preference that has since been removed).
5414 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5415 // caused gap locks on [max user ID,+infinity) which caused high contention since
5416 // updates would pile up on each other as they are for higher (newer) user IDs.
5417 // It might not be necessary these days, but it shouldn't hurt either.
5418 $dbw->delete( 'user_properties',
5419 [ 'up_user' => $userId, 'up_property' => $keysDelete ], __METHOD__
);
5421 // Insert the new preference rows
5422 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, [ 'IGNORE' ] );
5426 * Lazily instantiate and return a factory object for making passwords
5428 * @deprecated since 1.27, create a PasswordFactory directly instead
5429 * @return PasswordFactory
5431 public static function getPasswordFactory() {
5432 wfDeprecated( __METHOD__
, '1.27' );
5433 $ret = new PasswordFactory();
5434 $ret->init( RequestContext
::getMain()->getConfig() );
5439 * Provide an array of HTML5 attributes to put on an input element
5440 * intended for the user to enter a new password. This may include
5441 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
5443 * Do *not* use this when asking the user to enter his current password!
5444 * Regardless of configuration, users may have invalid passwords for whatever
5445 * reason (e.g., they were set before requirements were tightened up).
5446 * Only use it when asking for a new password, like on account creation or
5449 * Obviously, you still need to do server-side checking.
5451 * NOTE: A combination of bugs in various browsers means that this function
5452 * actually just returns array() unconditionally at the moment. May as
5453 * well keep it around for when the browser bugs get fixed, though.
5455 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
5457 * @deprecated since 1.27
5458 * @return array Array of HTML attributes suitable for feeding to
5459 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
5460 * That will get confused by the boolean attribute syntax used.)
5462 public static function passwordChangeInputAttribs() {
5463 global $wgMinimalPasswordLength;
5465 if ( $wgMinimalPasswordLength == 0 ) {
5469 # Note that the pattern requirement will always be satisfied if the
5470 # input is empty, so we need required in all cases.
5472 # @todo FIXME: T25769: This needs to not claim the password is required
5473 # if e-mail confirmation is being used. Since HTML5 input validation
5474 # is b0rked anyway in some browsers, just return nothing. When it's
5475 # re-enabled, fix this code to not output required for e-mail
5477 # $ret = array( 'required' );
5480 # We can't actually do this right now, because Opera 9.6 will print out
5481 # the entered password visibly in its error message! When other
5482 # browsers add support for this attribute, or Opera fixes its support,
5483 # we can add support with a version check to avoid doing this on Opera
5484 # versions where it will be a problem. Reported to Opera as
5485 # DSK-262266, but they don't have a public bug tracker for us to follow.
5487 if ( $wgMinimalPasswordLength > 1 ) {
5488 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
5489 $ret['title'] = wfMessage( 'passwordtooshort' )
5490 ->numParams( $wgMinimalPasswordLength )->text();
5498 * Return the list of user fields that should be selected to create
5499 * a new user object.
5502 public static function selectFields() {
5510 'user_email_authenticated',
5512 'user_email_token_expires',
5513 'user_registration',
5519 * Factory function for fatal permission-denied errors
5522 * @param string $permission User right required
5525 static function newFatalPermissionDeniedStatus( $permission ) {
5529 foreach ( self
::getGroupsWithPermission( $permission ) as $group ) {
5530 $groups[] = UserGroupMembership
::getLink( $group, RequestContext
::getMain(), 'wiki' );
5534 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5536 return Status
::newFatal( 'badaccess-group0' );
5541 * Get a new instance of this user that was loaded from the master via a locking read
5543 * Use this instead of the main context User when updating that user. This avoids races
5544 * where that user was loaded from a replica DB or even the master but without proper locks.
5546 * @return User|null Returns null if the user was not found in the DB
5549 public function getInstanceForUpdate() {
5550 if ( !$this->getId() ) {
5551 return null; // anon
5554 $user = self
::newFromId( $this->getId() );
5555 if ( !$user->loadFromId( self
::READ_EXCLUSIVE
) ) {
5563 * Checks if two user objects point to the same user.
5569 public function equals( User
$user ) {
5570 return $this->getName() === $user->getName();