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 $userQuery = self
::getQueryInfo();
692 $row = $dbr->selectRow(
693 $userQuery['tables'],
694 $userQuery['fields'],
695 [ 'user_name' => $name ],
701 // Try the master database...
702 $dbw = wfGetDB( DB_MASTER
);
703 $row = $dbw->selectRow(
704 $userQuery['tables'],
705 $userQuery['fields'],
706 [ 'user_name' => $name ],
714 // No user. Create it?
715 return $options['create']
716 ? self
::createNew( $name, [ 'token' => self
::INVALID_TOKEN
] )
720 $user = self
::newFromRow( $row );
722 // A user is considered to exist as a non-system user if it can
723 // authenticate, or has an email set, or has a non-invalid token.
724 if ( $user->mEmail ||
$user->mToken
!== self
::INVALID_TOKEN ||
725 AuthManager
::singleton()->userCanAuthenticate( $name )
727 // User exists. Steal it?
728 if ( !$options['steal'] ) {
732 AuthManager
::singleton()->revokeAccessForUser( $name );
734 $user->invalidateEmail();
735 $user->mToken
= self
::INVALID_TOKEN
;
736 $user->saveSettings();
737 SessionManager
::singleton()->preventSessionsForUser( $user->getName() );
746 * Get the username corresponding to a given user ID
747 * @param int $id User ID
748 * @return string|bool The corresponding username
750 public static function whoIs( $id ) {
751 return UserCache
::singleton()->getProp( $id, 'name' );
755 * Get the real name of a user given their user ID
757 * @param int $id User ID
758 * @return string|bool The corresponding user's real name
760 public static function whoIsReal( $id ) {
761 return UserCache
::singleton()->getProp( $id, 'real_name' );
765 * Get database id given a user name
766 * @param string $name Username
767 * @param int $flags User::READ_* constant bitfield
768 * @return int|null The corresponding user's ID, or null if user is nonexistent
770 public static function idFromName( $name, $flags = self
::READ_NORMAL
) {
771 $nt = Title
::makeTitleSafe( NS_USER
, $name );
772 if ( is_null( $nt ) ) {
777 if ( !( $flags & self
::READ_LATEST
) && isset( self
::$idCacheByName[$name] ) ) {
778 return self
::$idCacheByName[$name];
781 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
782 $db = wfGetDB( $index );
787 [ 'user_name' => $nt->getText() ],
792 if ( $s === false ) {
795 $result = $s->user_id
;
798 self
::$idCacheByName[$name] = $result;
800 if ( count( self
::$idCacheByName ) > 1000 ) {
801 self
::$idCacheByName = [];
808 * Reset the cache used in idFromName(). For use in tests.
810 public static function resetIdByNameCache() {
811 self
::$idCacheByName = [];
815 * Does the string match an anonymous IP address?
817 * This function exists for username validation, in order to reject
818 * usernames which are similar in form to IP addresses. Strings such
819 * as 300.300.300.300 will return true because it looks like an IP
820 * address, despite not being strictly valid.
822 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
823 * address because the usemod software would "cloak" anonymous IP
824 * addresses like this, if we allowed accounts like this to be created
825 * new users could get the old edits of these anonymous users.
827 * @param string $name Name to match
830 public static function isIP( $name ) {
831 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
832 || IP
::isIPv6( $name );
836 * Is the user an IP range?
841 public function isIPRange() {
842 return IP
::isValidRange( $this->mName
);
846 * Is the input a valid username?
848 * Checks if the input is a valid username, we don't want an empty string,
849 * an IP address, anything that contains slashes (would mess up subpages),
850 * is longer than the maximum allowed username size or doesn't begin with
853 * @param string $name Name to match
856 public static function isValidUserName( $name ) {
857 global $wgContLang, $wgMaxNameChars;
860 || self
::isIP( $name )
861 ||
strpos( $name, '/' ) !== false
862 ||
strlen( $name ) > $wgMaxNameChars
863 ||
$name != $wgContLang->ucfirst( $name )
868 // Ensure that the name can't be misresolved as a different title,
869 // such as with extra namespace keys at the start.
870 $parsed = Title
::newFromText( $name );
871 if ( is_null( $parsed )
872 ||
$parsed->getNamespace()
873 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
877 // Check an additional blacklist of troublemaker characters.
878 // Should these be merged into the title char list?
879 $unicodeBlacklist = '/[' .
880 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
881 '\x{00a0}' . # non-breaking space
882 '\x{2000}-\x{200f}' . # various whitespace
883 '\x{2028}-\x{202f}' . # breaks and control chars
884 '\x{3000}' . # ideographic space
885 '\x{e000}-\x{f8ff}' . # private use
887 if ( preg_match( $unicodeBlacklist, $name ) ) {
895 * Usernames which fail to pass this function will be blocked
896 * from user login and new account registrations, but may be used
897 * internally by batch processes.
899 * If an account already exists in this form, login will be blocked
900 * by a failure to pass this function.
902 * @param string $name Name to match
905 public static function isUsableName( $name ) {
906 global $wgReservedUsernames;
907 // Must be a valid username, obviously ;)
908 if ( !self
::isValidUserName( $name ) ) {
912 static $reservedUsernames = false;
913 if ( !$reservedUsernames ) {
914 $reservedUsernames = $wgReservedUsernames;
915 Hooks
::run( 'UserGetReservedNames', [ &$reservedUsernames ] );
918 // Certain names may be reserved for batch processes.
919 foreach ( $reservedUsernames as $reserved ) {
920 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
921 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
923 if ( $reserved == $name ) {
931 * Return the users who are members of the given group(s). In case of multiple groups,
932 * users who are members of at least one of them are returned.
934 * @param string|array $groups A single group name or an array of group names
935 * @param int $limit Max number of users to return. The actual limit will never exceed 5000
936 * records; larger values are ignored.
937 * @param int $after ID the user to start after
938 * @return UserArrayFromResult
940 public static function findUsersByGroup( $groups, $limit = 5000, $after = null ) {
941 if ( $groups === [] ) {
942 return UserArrayFromResult
::newFromIDs( [] );
945 $groups = array_unique( (array)$groups );
946 $limit = min( 5000, $limit );
948 $conds = [ 'ug_group' => $groups ];
949 if ( $after !== null ) {
950 $conds[] = 'ug_user > ' . (int)$after;
953 $dbr = wfGetDB( DB_REPLICA
);
954 $ids = $dbr->selectFieldValues(
961 'ORDER BY' => 'ug_user',
965 return UserArray
::newFromIDs( $ids );
969 * Usernames which fail to pass this function will be blocked
970 * from new account registrations, but may be used internally
971 * either by batch processes or by user accounts which have
972 * already been created.
974 * Additional blacklisting may be added here rather than in
975 * isValidUserName() to avoid disrupting existing accounts.
977 * @param string $name String to match
980 public static function isCreatableName( $name ) {
981 global $wgInvalidUsernameCharacters;
983 // Ensure that the username isn't longer than 235 bytes, so that
984 // (at least for the builtin skins) user javascript and css files
985 // will work. (T25080)
986 if ( strlen( $name ) > 235 ) {
987 wfDebugLog( 'username', __METHOD__
.
988 ": '$name' invalid due to length" );
992 // Preg yells if you try to give it an empty string
993 if ( $wgInvalidUsernameCharacters !== '' ) {
994 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
995 wfDebugLog( 'username', __METHOD__
.
996 ": '$name' invalid due to wgInvalidUsernameCharacters" );
1001 return self
::isUsableName( $name );
1005 * Is the input a valid password for this user?
1007 * @param string $password Desired password
1010 public function isValidPassword( $password ) {
1011 // simple boolean wrapper for getPasswordValidity
1012 return $this->getPasswordValidity( $password ) === true;
1016 * Given unvalidated password input, return error message on failure.
1018 * @param string $password Desired password
1019 * @return bool|string|array True on success, string or array of error message on failure
1021 public function getPasswordValidity( $password ) {
1022 $result = $this->checkPasswordValidity( $password );
1023 if ( $result->isGood() ) {
1027 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
1028 $messages[] = $error['message'];
1030 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
1031 $messages[] = $warning['message'];
1033 if ( count( $messages ) === 1 ) {
1034 return $messages[0];
1041 * Check if this is a valid password for this user
1043 * Create a Status object based on the password's validity.
1044 * The Status should be set to fatal if the user should not
1045 * be allowed to log in, and should have any errors that
1046 * would block changing the password.
1048 * If the return value of this is not OK, the password
1049 * should not be checked. If the return value is not Good,
1050 * the password can be checked, but the user should not be
1051 * able to set their password to this.
1053 * @param string $password Desired password
1057 public function checkPasswordValidity( $password ) {
1058 global $wgPasswordPolicy;
1060 $upp = new UserPasswordPolicy(
1061 $wgPasswordPolicy['policies'],
1062 $wgPasswordPolicy['checks']
1065 $status = Status
::newGood();
1066 $result = false; // init $result to false for the internal checks
1068 if ( !Hooks
::run( 'isValidPassword', [ $password, &$result, $this ] ) ) {
1069 $status->error( $result );
1073 if ( $result === false ) {
1074 $status->merge( $upp->checkUserPassword( $this, $password ) );
1076 } elseif ( $result === true ) {
1079 $status->error( $result );
1080 return $status; // the isValidPassword hook set a string $result and returned true
1085 * Given unvalidated user input, return a canonical username, or false if
1086 * the username is invalid.
1087 * @param string $name User input
1088 * @param string|bool $validate Type of validation to use:
1089 * - false No validation
1090 * - 'valid' Valid for batch processes
1091 * - 'usable' Valid for batch processes and login
1092 * - 'creatable' Valid for batch processes, login and account creation
1094 * @throws InvalidArgumentException
1095 * @return bool|string
1097 public static function getCanonicalName( $name, $validate = 'valid' ) {
1098 // Force usernames to capital
1100 $name = $wgContLang->ucfirst( $name );
1102 # Reject names containing '#'; these will be cleaned up
1103 # with title normalisation, but then it's too late to
1105 if ( strpos( $name, '#' ) !== false ) {
1109 // Clean up name according to title rules,
1110 // but only when validation is requested (T14654)
1111 $t = ( $validate !== false ) ?
1112 Title
::newFromText( $name, NS_USER
) : Title
::makeTitle( NS_USER
, $name );
1113 // Check for invalid titles
1114 if ( is_null( $t ) ||
$t->getNamespace() !== NS_USER ||
$t->isExternal() ) {
1118 // Reject various classes of invalid names
1119 $name = AuthManager
::callLegacyAuthPlugin(
1120 'getCanonicalName', [ $t->getText() ], $t->getText()
1123 switch ( $validate ) {
1127 if ( !self
::isValidUserName( $name ) ) {
1132 if ( !self
::isUsableName( $name ) ) {
1137 if ( !self
::isCreatableName( $name ) ) {
1142 throw new InvalidArgumentException(
1143 'Invalid parameter value for $validate in ' . __METHOD__
);
1149 * Return a random password.
1151 * @deprecated since 1.27, use PasswordFactory::generateRandomPasswordString()
1152 * @return string New random password
1154 public static function randomPassword() {
1155 global $wgMinimalPasswordLength;
1156 return PasswordFactory
::generateRandomPasswordString( $wgMinimalPasswordLength );
1160 * Set cached properties to default.
1162 * @note This no longer clears uncached lazy-initialised properties;
1163 * the constructor does that instead.
1165 * @param string|bool $name
1167 public function loadDefaults( $name = false ) {
1169 $this->mName
= $name;
1170 $this->mRealName
= '';
1172 $this->mOptionOverrides
= null;
1173 $this->mOptionsLoaded
= false;
1175 $loggedOut = $this->mRequest
&& !defined( 'MW_NO_SESSION' )
1176 ?
$this->mRequest
->getSession()->getLoggedOutTimestamp() : 0;
1177 if ( $loggedOut !== 0 ) {
1178 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1180 $this->mTouched
= '1'; # Allow any pages to be cached
1183 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1184 $this->mEmailAuthenticated
= null;
1185 $this->mEmailToken
= '';
1186 $this->mEmailTokenExpires
= null;
1187 $this->mRegistration
= wfTimestamp( TS_MW
);
1188 $this->mGroupMemberships
= [];
1190 Hooks
::run( 'UserLoadDefaults', [ $this, $name ] );
1194 * Return whether an item has been loaded.
1196 * @param string $item Item to check. Current possibilities:
1200 * @param string $all 'all' to check if the whole object has been loaded
1201 * or any other string to check if only the item is available (e.g.
1205 public function isItemLoaded( $item, $all = 'all' ) {
1206 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1207 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1211 * Set that an item has been loaded
1213 * @param string $item
1215 protected function setItemLoaded( $item ) {
1216 if ( is_array( $this->mLoadedItems
) ) {
1217 $this->mLoadedItems
[$item] = true;
1222 * Load user data from the session.
1224 * @return bool True if the user is logged in, false otherwise.
1226 private function loadFromSession() {
1229 Hooks
::run( 'UserLoadFromSession', [ $this, &$result ], '1.27' );
1230 if ( $result !== null ) {
1234 // MediaWiki\Session\Session already did the necessary authentication of the user
1235 // returned here, so just use it if applicable.
1236 $session = $this->getRequest()->getSession();
1237 $user = $session->getUser();
1238 if ( $user->isLoggedIn() ) {
1239 $this->loadFromUserObject( $user );
1241 // If this user is autoblocked, set a cookie to track the Block. This has to be done on
1242 // every session load, because an autoblocked editor might not edit again from the same
1243 // IP address after being blocked.
1244 $config = RequestContext
::getMain()->getConfig();
1245 if ( $config->get( 'CookieSetOnAutoblock' ) === true ) {
1246 $block = $this->getBlock();
1247 $shouldSetCookie = $this->getRequest()->getCookie( 'BlockID' ) === null
1249 && $block->getType() === Block
::TYPE_USER
1250 && $block->isAutoblocking();
1251 if ( $shouldSetCookie ) {
1252 wfDebug( __METHOD__
. ': User is autoblocked, setting cookie to track' );
1253 $block->setCookie( $this->getRequest()->response() );
1257 // Other code expects these to be set in the session, so set them.
1258 $session->set( 'wsUserID', $this->getId() );
1259 $session->set( 'wsUserName', $this->getName() );
1260 $session->set( 'wsToken', $this->getToken() );
1267 * Load user and user_group data from the database.
1268 * $this->mId must be set, this is how the user is identified.
1270 * @param int $flags User::READ_* constant bitfield
1271 * @return bool True if the user exists, false if the user is anonymous
1273 public function loadFromDatabase( $flags = self
::READ_LATEST
) {
1275 $this->mId
= intval( $this->mId
);
1277 if ( !$this->mId
) {
1278 // Anonymous users are not in the database
1279 $this->loadDefaults();
1283 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
1284 $db = wfGetDB( $index );
1286 $userQuery = self
::getQueryInfo();
1287 $s = $db->selectRow(
1288 $userQuery['tables'],
1289 $userQuery['fields'],
1290 [ 'user_id' => $this->mId
],
1296 $this->queryFlagsUsed
= $flags;
1297 Hooks
::run( 'UserLoadFromDatabase', [ $this, &$s ] );
1299 if ( $s !== false ) {
1300 // Initialise user table data
1301 $this->loadFromRow( $s );
1302 $this->mGroupMemberships
= null; // deferred
1303 $this->getEditCount(); // revalidation for nulls
1308 $this->loadDefaults();
1314 * Initialize this object from a row from the user table.
1316 * @param stdClass $row Row from the user table to load.
1317 * @param array $data Further user data to load into the object
1319 * user_groups Array of arrays or stdClass result rows out of the user_groups
1320 * table. Previously you were supposed to pass an array of strings
1321 * here, but we also need expiry info nowadays, so an array of
1322 * strings is ignored.
1323 * user_properties Array with properties out of the user_properties table
1325 protected function loadFromRow( $row, $data = null ) {
1328 $this->mGroupMemberships
= null; // deferred
1330 if ( isset( $row->user_name
) ) {
1331 $this->mName
= $row->user_name
;
1332 $this->mFrom
= 'name';
1333 $this->setItemLoaded( 'name' );
1338 if ( isset( $row->user_real_name
) ) {
1339 $this->mRealName
= $row->user_real_name
;
1340 $this->setItemLoaded( 'realname' );
1345 if ( isset( $row->user_id
) ) {
1346 $this->mId
= intval( $row->user_id
);
1347 $this->mFrom
= 'id';
1348 $this->setItemLoaded( 'id' );
1353 if ( isset( $row->user_id
) && isset( $row->user_name
) ) {
1354 self
::$idCacheByName[$row->user_name
] = $row->user_id
;
1357 if ( isset( $row->user_editcount
) ) {
1358 $this->mEditCount
= $row->user_editcount
;
1363 if ( isset( $row->user_touched
) ) {
1364 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1369 if ( isset( $row->user_token
) ) {
1370 // The definition for the column is binary(32), so trim the NULs
1371 // that appends. The previous definition was char(32), so trim
1373 $this->mToken
= rtrim( $row->user_token
, " \0" );
1374 if ( $this->mToken
=== '' ) {
1375 $this->mToken
= null;
1381 if ( isset( $row->user_email
) ) {
1382 $this->mEmail
= $row->user_email
;
1383 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1384 $this->mEmailToken
= $row->user_email_token
;
1385 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1386 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1392 $this->mLoadedItems
= true;
1395 if ( is_array( $data ) ) {
1396 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1397 if ( !count( $data['user_groups'] ) ) {
1398 $this->mGroupMemberships
= [];
1400 $firstGroup = reset( $data['user_groups'] );
1401 if ( is_array( $firstGroup ) ||
is_object( $firstGroup ) ) {
1402 $this->mGroupMemberships
= [];
1403 foreach ( $data['user_groups'] as $row ) {
1404 $ugm = UserGroupMembership
::newFromRow( (object)$row );
1405 $this->mGroupMemberships
[$ugm->getGroup()] = $ugm;
1410 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1411 $this->loadOptions( $data['user_properties'] );
1417 * Load the data for this user object from another user object.
1421 protected function loadFromUserObject( $user ) {
1423 foreach ( self
::$mCacheVars as $var ) {
1424 $this->$var = $user->$var;
1429 * Load the groups from the database if they aren't already loaded.
1431 private function loadGroups() {
1432 if ( is_null( $this->mGroupMemberships
) ) {
1433 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
1434 ?
wfGetDB( DB_MASTER
)
1435 : wfGetDB( DB_REPLICA
);
1436 $this->mGroupMemberships
= UserGroupMembership
::getMembershipsForUser(
1442 * Add the user to the group if he/she meets given criteria.
1444 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1445 * possible to remove manually via Special:UserRights. In such case it
1446 * will not be re-added automatically. The user will also not lose the
1447 * group if they no longer meet the criteria.
1449 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1451 * @return array Array of groups the user has been promoted to.
1453 * @see $wgAutopromoteOnce
1455 public function addAutopromoteOnceGroups( $event ) {
1456 global $wgAutopromoteOnceLogInRC;
1458 if ( wfReadOnly() ||
!$this->getId() ) {
1462 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1463 if ( !count( $toPromote ) ) {
1467 if ( !$this->checkAndSetTouched() ) {
1468 return []; // raced out (bug T48834)
1471 $oldGroups = $this->getGroups(); // previous groups
1472 $oldUGMs = $this->getGroupMemberships();
1473 foreach ( $toPromote as $group ) {
1474 $this->addGroup( $group );
1476 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1477 $newUGMs = $this->getGroupMemberships();
1479 // update groups in external authentication database
1480 Hooks
::run( 'UserGroupsChanged', [ $this, $toPromote, [], false, false, $oldUGMs, $newUGMs ] );
1481 AuthManager
::callLegacyAuthPlugin( 'updateExternalDBGroups', [ $this, $toPromote ] );
1483 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1484 $logEntry->setPerformer( $this );
1485 $logEntry->setTarget( $this->getUserPage() );
1486 $logEntry->setParameters( [
1487 '4::oldgroups' => $oldGroups,
1488 '5::newgroups' => $newGroups,
1490 $logid = $logEntry->insert();
1491 if ( $wgAutopromoteOnceLogInRC ) {
1492 $logEntry->publish( $logid );
1499 * Builds update conditions. Additional conditions may be added to $conditions to
1500 * protected against race conditions using a compare-and-set (CAS) mechanism
1501 * based on comparing $this->mTouched with the user_touched field.
1503 * @param Database $db
1504 * @param array $conditions WHERE conditions for use with Database::update
1505 * @return array WHERE conditions for use with Database::update
1507 protected function makeUpdateConditions( Database
$db, array $conditions ) {
1508 if ( $this->mTouched
) {
1509 // CAS check: only update if the row wasn't changed sicne it was loaded.
1510 $conditions['user_touched'] = $db->timestamp( $this->mTouched
);
1517 * Bump user_touched if it didn't change since this object was loaded
1519 * On success, the mTouched field is updated.
1520 * The user serialization cache is always cleared.
1522 * @return bool Whether user_touched was actually updated
1525 protected function checkAndSetTouched() {
1528 if ( !$this->mId
) {
1529 return false; // anon
1532 // Get a new user_touched that is higher than the old one
1533 $newTouched = $this->newTouchedTimestamp();
1535 $dbw = wfGetDB( DB_MASTER
);
1536 $dbw->update( 'user',
1537 [ 'user_touched' => $dbw->timestamp( $newTouched ) ],
1538 $this->makeUpdateConditions( $dbw, [
1539 'user_id' => $this->mId
,
1543 $success = ( $dbw->affectedRows() > 0 );
1546 $this->mTouched
= $newTouched;
1547 $this->clearSharedCache();
1549 // Clears on failure too since that is desired if the cache is stale
1550 $this->clearSharedCache( 'refresh' );
1557 * Clear various cached data stored in this object. The cache of the user table
1558 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1560 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1561 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1563 public function clearInstanceCache( $reloadFrom = false ) {
1564 $this->mNewtalk
= -1;
1565 $this->mDatePreference
= null;
1566 $this->mBlockedby
= -1; # Unset
1567 $this->mHash
= false;
1568 $this->mRights
= null;
1569 $this->mEffectiveGroups
= null;
1570 $this->mImplicitGroups
= null;
1571 $this->mGroupMemberships
= null;
1572 $this->mOptions
= null;
1573 $this->mOptionsLoaded
= false;
1574 $this->mEditCount
= null;
1576 if ( $reloadFrom ) {
1577 $this->mLoadedItems
= [];
1578 $this->mFrom
= $reloadFrom;
1583 * Combine the language default options with any site-specific options
1584 * and add the default language variants.
1586 * @return array Array of String options
1588 public static function getDefaultOptions() {
1589 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1591 static $defOpt = null;
1592 static $defOptLang = null;
1594 if ( $defOpt !== null && $defOptLang === $wgContLang->getCode() ) {
1595 // $wgContLang does not change (and should not change) mid-request,
1596 // but the unit tests change it anyway, and expect this method to
1597 // return values relevant to the current $wgContLang.
1601 $defOpt = $wgDefaultUserOptions;
1602 // Default language setting
1603 $defOptLang = $wgContLang->getCode();
1604 $defOpt['language'] = $defOptLang;
1605 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1606 $defOpt[$langCode == $wgContLang->getCode() ?
'variant' : "variant-$langCode"] = $langCode;
1609 // NOTE: don't use SearchEngineConfig::getSearchableNamespaces here,
1610 // since extensions may change the set of searchable namespaces depending
1611 // on user groups/permissions.
1612 foreach ( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
1613 $defOpt['searchNs' . $nsnum] = (bool)$val;
1615 $defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1617 Hooks
::run( 'UserGetDefaultOptions', [ &$defOpt ] );
1623 * Get a given default option value.
1625 * @param string $opt Name of option to retrieve
1626 * @return string Default option value
1628 public static function getDefaultOption( $opt ) {
1629 $defOpts = self
::getDefaultOptions();
1630 if ( isset( $defOpts[$opt] ) ) {
1631 return $defOpts[$opt];
1638 * Get blocking information
1639 * @param bool $bFromSlave Whether to check the replica DB first.
1640 * To improve performance, non-critical checks are done against replica DBs.
1641 * Check when actually saving should be done against master.
1643 private function getBlockedStatus( $bFromSlave = true ) {
1644 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff, $wgSoftBlockRanges;
1646 if ( -1 != $this->mBlockedby
) {
1650 wfDebug( __METHOD__
. ": checking...\n" );
1652 // Initialize data...
1653 // Otherwise something ends up stomping on $this->mBlockedby when
1654 // things get lazy-loaded later, causing false positive block hits
1655 // due to -1 !== 0. Probably session-related... Nothing should be
1656 // overwriting mBlockedby, surely?
1659 # We only need to worry about passing the IP address to the Block generator if the
1660 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1661 # know which IP address they're actually coming from
1663 if ( !$this->isAllowed( 'ipblock-exempt' ) ) {
1664 // $wgUser->getName() only works after the end of Setup.php. Until
1665 // then, assume it's a logged-out user.
1666 $globalUserName = $wgUser->isSafeToLoad()
1667 ?
$wgUser->getName()
1668 : IP
::sanitizeIP( $wgUser->getRequest()->getIP() );
1669 if ( $this->getName() === $globalUserName ) {
1670 $ip = $this->getRequest()->getIP();
1675 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1678 if ( !$block instanceof Block
) {
1679 $block = $this->getBlockFromCookieValue( $this->getRequest()->getCookie( 'BlockID' ) );
1683 if ( !$block instanceof Block
&& $ip !== null && !in_array( $ip, $wgProxyWhitelist ) ) {
1685 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1686 $block = new Block( [
1687 'byText' => wfMessage( 'proxyblocker' )->text(),
1688 'reason' => wfMessage( 'proxyblockreason' )->text(),
1690 'systemBlock' => 'proxy',
1692 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1693 $block = new Block( [
1694 'byText' => wfMessage( 'sorbs' )->text(),
1695 'reason' => wfMessage( 'sorbsreason' )->text(),
1697 'systemBlock' => 'dnsbl',
1702 // (T25343) Apply IP blocks to the contents of XFF headers, if enabled
1703 if ( !$block instanceof Block
1704 && $wgApplyIpBlocksToXff
1706 && !in_array( $ip, $wgProxyWhitelist )
1708 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1709 $xff = array_map( 'trim', explode( ',', $xff ) );
1710 $xff = array_diff( $xff, [ $ip ] );
1711 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1712 $block = Block
::chooseBlock( $xffblocks, $xff );
1713 if ( $block instanceof Block
) {
1714 # Mangle the reason to alert the user that the block
1715 # originated from matching the X-Forwarded-For header.
1716 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->text();
1720 if ( !$block instanceof Block
1723 && IP
::isInRanges( $ip, $wgSoftBlockRanges )
1725 $block = new Block( [
1727 'byText' => 'MediaWiki default',
1728 'reason' => wfMessage( 'softblockrangesreason', $ip )->text(),
1730 'systemBlock' => 'wgSoftBlockRanges',
1734 if ( $block instanceof Block
) {
1735 wfDebug( __METHOD__
. ": Found block.\n" );
1736 $this->mBlock
= $block;
1737 $this->mBlockedby
= $block->getByName();
1738 $this->mBlockreason
= $block->mReason
;
1739 $this->mHideName
= $block->mHideName
;
1740 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1742 $this->mBlockedby
= '';
1743 $this->mHideName
= 0;
1744 $this->mAllowUsertalk
= false;
1747 // Avoid PHP 7.1 warning of passing $this by reference
1750 Hooks
::run( 'GetBlockedStatus', [ &$user ] );
1754 * Try to load a Block from an ID given in a cookie value.
1755 * @param string|null $blockCookieVal The cookie value to check.
1756 * @return Block|bool The Block object, or false if none could be loaded.
1758 protected function getBlockFromCookieValue( $blockCookieVal ) {
1759 // Make sure there's something to check. The cookie value must start with a number.
1760 if ( strlen( $blockCookieVal ) < 1 ||
!is_numeric( substr( $blockCookieVal, 0, 1 ) ) ) {
1763 // Load the Block from the ID in the cookie.
1764 $blockCookieId = Block
::getIdFromCookieValue( $blockCookieVal );
1765 if ( $blockCookieId !== null ) {
1766 // An ID was found in the cookie.
1767 $tmpBlock = Block
::newFromID( $blockCookieId );
1768 if ( $tmpBlock instanceof Block
) {
1769 // Check the validity of the block.
1770 $blockIsValid = $tmpBlock->getType() == Block
::TYPE_USER
1771 && !$tmpBlock->isExpired()
1772 && $tmpBlock->isAutoblocking();
1773 $config = RequestContext
::getMain()->getConfig();
1774 $useBlockCookie = ( $config->get( 'CookieSetOnAutoblock' ) === true );
1775 if ( $blockIsValid && $useBlockCookie ) {
1779 // If the block is not valid, remove the cookie.
1780 Block
::clearCookie( $this->getRequest()->response() );
1783 // If the block doesn't exist, remove the cookie.
1784 Block
::clearCookie( $this->getRequest()->response() );
1791 * Whether the given IP is in a DNS blacklist.
1793 * @param string $ip IP to check
1794 * @param bool $checkWhitelist Whether to check the whitelist first
1795 * @return bool True if blacklisted.
1797 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1798 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1800 if ( !$wgEnableDnsBlacklist ) {
1804 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1808 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1812 * Whether the given IP is in a given DNS blacklist.
1814 * @param string $ip IP to check
1815 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1816 * @return bool True if blacklisted.
1818 public function inDnsBlacklist( $ip, $bases ) {
1820 // @todo FIXME: IPv6 ??? (https://bugs.php.net/bug.php?id=33170)
1821 if ( IP
::isIPv4( $ip ) ) {
1822 // Reverse IP, T23255
1823 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1825 foreach ( (array)$bases as $base ) {
1827 // If we have an access key, use that too (ProjectHoneypot, etc.)
1829 if ( is_array( $base ) ) {
1830 if ( count( $base ) >= 2 ) {
1831 // Access key is 1, base URL is 0
1832 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1834 $host = "$ipReversed.{$base[0]}";
1836 $basename = $base[0];
1838 $host = "$ipReversed.$base";
1842 $ipList = gethostbynamel( $host );
1845 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
1849 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
1858 * Check if an IP address is in the local proxy list
1864 public static function isLocallyBlockedProxy( $ip ) {
1865 global $wgProxyList;
1867 if ( !$wgProxyList ) {
1871 if ( !is_array( $wgProxyList ) ) {
1872 // Load values from the specified file
1873 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1876 $resultProxyList = [];
1877 $deprecatedIPEntries = [];
1879 // backward compatibility: move all ip addresses in keys to values
1880 foreach ( $wgProxyList as $key => $value ) {
1881 $keyIsIP = IP
::isIPAddress( $key );
1882 $valueIsIP = IP
::isIPAddress( $value );
1883 if ( $keyIsIP && !$valueIsIP ) {
1884 $deprecatedIPEntries[] = $key;
1885 $resultProxyList[] = $key;
1886 } elseif ( $keyIsIP && $valueIsIP ) {
1887 $deprecatedIPEntries[] = $key;
1888 $resultProxyList[] = $key;
1889 $resultProxyList[] = $value;
1891 $resultProxyList[] = $value;
1895 if ( $deprecatedIPEntries ) {
1897 'IP addresses in the keys of $wgProxyList (found the following IP addresses in keys: ' .
1898 implode( ', ', $deprecatedIPEntries ) . ', please move them to values)', '1.30' );
1901 $proxyListIPSet = new IPSet( $resultProxyList );
1902 return $proxyListIPSet->match( $ip );
1906 * Is this user subject to rate limiting?
1908 * @return bool True if rate limited
1910 public function isPingLimitable() {
1911 global $wgRateLimitsExcludedIPs;
1912 if ( IP
::isInRanges( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1913 // No other good way currently to disable rate limits
1914 // for specific IPs. :P
1915 // But this is a crappy hack and should die.
1918 return !$this->isAllowed( 'noratelimit' );
1922 * Primitive rate limits: enforce maximum actions per time period
1923 * to put a brake on flooding.
1925 * The method generates both a generic profiling point and a per action one
1926 * (suffix being "-$action".
1928 * @note When using a shared cache like memcached, IP-address
1929 * last-hit counters will be shared across wikis.
1931 * @param string $action Action to enforce; 'edit' if unspecified
1932 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1933 * @return bool True if a rate limiter was tripped
1935 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1936 // Avoid PHP 7.1 warning of passing $this by reference
1938 // Call the 'PingLimiter' hook
1940 if ( !Hooks
::run( 'PingLimiter', [ &$user, $action, &$result, $incrBy ] ) ) {
1944 global $wgRateLimits;
1945 if ( !isset( $wgRateLimits[$action] ) ) {
1949 $limits = array_merge(
1950 [ '&can-bypass' => true ],
1951 $wgRateLimits[$action]
1954 // Some groups shouldn't trigger the ping limiter, ever
1955 if ( $limits['&can-bypass'] && !$this->isPingLimitable() ) {
1960 $id = $this->getId();
1962 $isNewbie = $this->isNewbie();
1963 $cache = ObjectCache
::getLocalClusterInstance();
1967 if ( isset( $limits['anon'] ) ) {
1968 $keys[$cache->makeKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1971 // limits for logged-in users
1972 if ( isset( $limits['user'] ) ) {
1973 $userLimit = $limits['user'];
1975 // limits for newbie logged-in users
1976 if ( $isNewbie && isset( $limits['newbie'] ) ) {
1977 $keys[$cache->makeKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1981 // limits for anons and for newbie logged-in users
1984 if ( isset( $limits['ip'] ) ) {
1985 $ip = $this->getRequest()->getIP();
1986 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1988 // subnet-based limits
1989 if ( isset( $limits['subnet'] ) ) {
1990 $ip = $this->getRequest()->getIP();
1991 $subnet = IP
::getSubnet( $ip );
1992 if ( $subnet !== false ) {
1993 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1998 // Check for group-specific permissions
1999 // If more than one group applies, use the group with the highest limit ratio (max/period)
2000 foreach ( $this->getGroups() as $group ) {
2001 if ( isset( $limits[$group] ) ) {
2002 if ( $userLimit === false
2003 ||
$limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
2005 $userLimit = $limits[$group];
2010 // Set the user limit key
2011 if ( $userLimit !== false ) {
2012 list( $max, $period ) = $userLimit;
2013 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
2014 $keys[$cache->makeKey( 'limiter', $action, 'user', $id )] = $userLimit;
2017 // ip-based limits for all ping-limitable users
2018 if ( isset( $limits['ip-all'] ) ) {
2019 $ip = $this->getRequest()->getIP();
2020 // ignore if user limit is more permissive
2021 if ( $isNewbie ||
$userLimit === false
2022 ||
$limits['ip-all'][0] / $limits['ip-all'][1] > $userLimit[0] / $userLimit[1] ) {
2023 $keys["mediawiki:limiter:$action:ip-all:$ip"] = $limits['ip-all'];
2027 // subnet-based limits for all ping-limitable users
2028 if ( isset( $limits['subnet-all'] ) ) {
2029 $ip = $this->getRequest()->getIP();
2030 $subnet = IP
::getSubnet( $ip );
2031 if ( $subnet !== false ) {
2032 // ignore if user limit is more permissive
2033 if ( $isNewbie ||
$userLimit === false
2034 ||
$limits['ip-all'][0] / $limits['ip-all'][1]
2035 > $userLimit[0] / $userLimit[1] ) {
2036 $keys["mediawiki:limiter:$action:subnet-all:$subnet"] = $limits['subnet-all'];
2042 foreach ( $keys as $key => $limit ) {
2043 list( $max, $period ) = $limit;
2044 $summary = "(limit $max in {$period}s)";
2045 $count = $cache->get( $key );
2048 if ( $count >= $max ) {
2049 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
2050 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
2053 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
2056 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
2057 if ( $incrBy > 0 ) {
2058 $cache->add( $key, 0, intval( $period ) ); // first ping
2061 if ( $incrBy > 0 ) {
2062 $cache->incr( $key, $incrBy );
2070 * Check if user is blocked
2072 * @param bool $bFromSlave Whether to check the replica DB instead of
2073 * the master. Hacked from false due to horrible probs on site.
2074 * @return bool True if blocked, false otherwise
2076 public function isBlocked( $bFromSlave = true ) {
2077 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
2081 * Get the block affecting the user, or null if the user is not blocked
2083 * @param bool $bFromSlave Whether to check the replica DB instead of the master
2084 * @return Block|null
2086 public function getBlock( $bFromSlave = true ) {
2087 $this->getBlockedStatus( $bFromSlave );
2088 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
2092 * Check if user is blocked from editing a particular article
2094 * @param Title $title Title to check
2095 * @param bool $bFromSlave Whether to check the replica DB instead of the master
2098 public function isBlockedFrom( $title, $bFromSlave = false ) {
2099 global $wgBlockAllowsUTEdit;
2101 $blocked = $this->isBlocked( $bFromSlave );
2102 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
2103 // If a user's name is suppressed, they cannot make edits anywhere
2104 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName()
2105 && $title->getNamespace() == NS_USER_TALK
) {
2107 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
2110 Hooks
::run( 'UserIsBlockedFrom', [ $this, $title, &$blocked, &$allowUsertalk ] );
2116 * If user is blocked, return the name of the user who placed the block
2117 * @return string Name of blocker
2119 public function blockedBy() {
2120 $this->getBlockedStatus();
2121 return $this->mBlockedby
;
2125 * If user is blocked, return the specified reason for the block
2126 * @return string Blocking reason
2128 public function blockedFor() {
2129 $this->getBlockedStatus();
2130 return $this->mBlockreason
;
2134 * If user is blocked, return the ID for the block
2135 * @return int Block ID
2137 public function getBlockId() {
2138 $this->getBlockedStatus();
2139 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
2143 * Check if user is blocked on all wikis.
2144 * Do not use for actual edit permission checks!
2145 * This is intended for quick UI checks.
2147 * @param string $ip IP address, uses current client if none given
2148 * @return bool True if blocked, false otherwise
2150 public function isBlockedGlobally( $ip = '' ) {
2151 return $this->getGlobalBlock( $ip ) instanceof Block
;
2155 * Check if user is blocked on all wikis.
2156 * Do not use for actual edit permission checks!
2157 * This is intended for quick UI checks.
2159 * @param string $ip IP address, uses current client if none given
2160 * @return Block|null Block object if blocked, null otherwise
2161 * @throws FatalError
2162 * @throws MWException
2164 public function getGlobalBlock( $ip = '' ) {
2165 if ( $this->mGlobalBlock
!== null ) {
2166 return $this->mGlobalBlock ?
: null;
2168 // User is already an IP?
2169 if ( IP
::isIPAddress( $this->getName() ) ) {
2170 $ip = $this->getName();
2172 $ip = $this->getRequest()->getIP();
2174 // Avoid PHP 7.1 warning of passing $this by reference
2178 Hooks
::run( 'UserIsBlockedGlobally', [ &$user, $ip, &$blocked, &$block ] );
2180 if ( $blocked && $block === null ) {
2181 // back-compat: UserIsBlockedGlobally didn't have $block param first
2182 $block = new Block( [
2184 'systemBlock' => 'global-block'
2188 $this->mGlobalBlock
= $blocked ?
$block : false;
2189 return $this->mGlobalBlock ?
: null;
2193 * Check if user account is locked
2195 * @return bool True if locked, false otherwise
2197 public function isLocked() {
2198 if ( $this->mLocked
!== null ) {
2199 return $this->mLocked
;
2201 // Avoid PHP 7.1 warning of passing $this by reference
2203 $authUser = AuthManager
::callLegacyAuthPlugin( 'getUserInstance', [ &$user ], null );
2204 $this->mLocked
= $authUser && $authUser->isLocked();
2205 Hooks
::run( 'UserIsLocked', [ $this, &$this->mLocked
] );
2206 return $this->mLocked
;
2210 * Check if user account is hidden
2212 * @return bool True if hidden, false otherwise
2214 public function isHidden() {
2215 if ( $this->mHideName
!== null ) {
2216 return $this->mHideName
;
2218 $this->getBlockedStatus();
2219 if ( !$this->mHideName
) {
2220 // Avoid PHP 7.1 warning of passing $this by reference
2222 $authUser = AuthManager
::callLegacyAuthPlugin( 'getUserInstance', [ &$user ], null );
2223 $this->mHideName
= $authUser && $authUser->isHidden();
2224 Hooks
::run( 'UserIsHidden', [ $this, &$this->mHideName
] );
2226 return $this->mHideName
;
2230 * Get the user's ID.
2231 * @return int The user's ID; 0 if the user is anonymous or nonexistent
2233 public function getId() {
2234 if ( $this->mId
=== null && $this->mName
!== null && self
::isIP( $this->mName
) ) {
2235 // Special case, we know the user is anonymous
2237 } elseif ( !$this->isItemLoaded( 'id' ) ) {
2238 // Don't load if this was initialized from an ID
2242 return (int)$this->mId
;
2246 * Set the user and reload all fields according to a given ID
2247 * @param int $v User ID to reload
2249 public function setId( $v ) {
2251 $this->clearInstanceCache( 'id' );
2255 * Get the user name, or the IP of an anonymous user
2256 * @return string User's name or IP address
2258 public function getName() {
2259 if ( $this->isItemLoaded( 'name', 'only' ) ) {
2260 // Special case optimisation
2261 return $this->mName
;
2264 if ( $this->mName
=== false ) {
2266 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
2268 return $this->mName
;
2273 * Set the user name.
2275 * This does not reload fields from the database according to the given
2276 * name. Rather, it is used to create a temporary "nonexistent user" for
2277 * later addition to the database. It can also be used to set the IP
2278 * address for an anonymous user to something other than the current
2281 * @note User::newFromName() has roughly the same function, when the named user
2283 * @param string $str New user name to set
2285 public function setName( $str ) {
2287 $this->mName
= $str;
2291 * Get the user's name escaped by underscores.
2292 * @return string Username escaped by underscores.
2294 public function getTitleKey() {
2295 return str_replace( ' ', '_', $this->getName() );
2299 * Check if the user has new messages.
2300 * @return bool True if the user has new messages
2302 public function getNewtalk() {
2305 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2306 if ( $this->mNewtalk
=== -1 ) {
2307 $this->mNewtalk
= false; # reset talk page status
2309 // Check memcached separately for anons, who have no
2310 // entire User object stored in there.
2311 if ( !$this->mId
) {
2312 global $wgDisableAnonTalk;
2313 if ( $wgDisableAnonTalk ) {
2314 // Anon newtalk disabled by configuration.
2315 $this->mNewtalk
= false;
2317 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
2320 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2324 return (bool)$this->mNewtalk
;
2328 * Return the data needed to construct links for new talk page message
2329 * alerts. If there are new messages, this will return an associative array
2330 * with the following data:
2331 * wiki: The database name of the wiki
2332 * link: Root-relative link to the user's talk page
2333 * rev: The last talk page revision that the user has seen or null. This
2334 * is useful for building diff links.
2335 * If there are no new messages, it returns an empty array.
2336 * @note This function was designed to accomodate multiple talk pages, but
2337 * currently only returns a single link and revision.
2340 public function getNewMessageLinks() {
2341 // Avoid PHP 7.1 warning of passing $this by reference
2344 if ( !Hooks
::run( 'UserRetrieveNewTalks', [ &$user, &$talks ] ) ) {
2346 } elseif ( !$this->getNewtalk() ) {
2349 $utp = $this->getTalkPage();
2350 $dbr = wfGetDB( DB_REPLICA
);
2351 // Get the "last viewed rev" timestamp from the oldest message notification
2352 $timestamp = $dbr->selectField( 'user_newtalk',
2353 'MIN(user_last_timestamp)',
2354 $this->isAnon() ?
[ 'user_ip' => $this->getName() ] : [ 'user_id' => $this->getId() ],
2356 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2357 return [ [ 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ] ];
2361 * Get the revision ID for the last talk page revision viewed by the talk
2363 * @return int|null Revision ID or null
2365 public function getNewMessageRevisionId() {
2366 $newMessageRevisionId = null;
2367 $newMessageLinks = $this->getNewMessageLinks();
2368 if ( $newMessageLinks ) {
2369 // Note: getNewMessageLinks() never returns more than a single link
2370 // and it is always for the same wiki, but we double-check here in
2371 // case that changes some time in the future.
2372 if ( count( $newMessageLinks ) === 1
2373 && $newMessageLinks[0]['wiki'] === wfWikiID()
2374 && $newMessageLinks[0]['rev']
2376 /** @var Revision $newMessageRevision */
2377 $newMessageRevision = $newMessageLinks[0]['rev'];
2378 $newMessageRevisionId = $newMessageRevision->getId();
2381 return $newMessageRevisionId;
2385 * Internal uncached check for new messages
2388 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2389 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2390 * @return bool True if the user has new messages
2392 protected function checkNewtalk( $field, $id ) {
2393 $dbr = wfGetDB( DB_REPLICA
);
2395 $ok = $dbr->selectField( 'user_newtalk', $field, [ $field => $id ], __METHOD__
);
2397 return $ok !== false;
2401 * Add or update the new messages flag
2402 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2403 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2404 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2405 * @return bool True if successful, false otherwise
2407 protected function updateNewtalk( $field, $id, $curRev = null ) {
2408 // Get timestamp of the talk page revision prior to the current one
2409 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2410 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2411 // Mark the user as having new messages since this revision
2412 $dbw = wfGetDB( DB_MASTER
);
2413 $dbw->insert( 'user_newtalk',
2414 [ $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ],
2417 if ( $dbw->affectedRows() ) {
2418 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2421 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2427 * Clear the new messages flag for the given user
2428 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2429 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2430 * @return bool True if successful, false otherwise
2432 protected function deleteNewtalk( $field, $id ) {
2433 $dbw = wfGetDB( DB_MASTER
);
2434 $dbw->delete( 'user_newtalk',
2437 if ( $dbw->affectedRows() ) {
2438 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2441 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2447 * Update the 'You have new messages!' status.
2448 * @param bool $val Whether the user has new messages
2449 * @param Revision $curRev New, as yet unseen revision of the user talk
2450 * page. Ignored if null or !$val.
2452 public function setNewtalk( $val, $curRev = null ) {
2453 if ( wfReadOnly() ) {
2458 $this->mNewtalk
= $val;
2460 if ( $this->isAnon() ) {
2462 $id = $this->getName();
2465 $id = $this->getId();
2469 $changed = $this->updateNewtalk( $field, $id, $curRev );
2471 $changed = $this->deleteNewtalk( $field, $id );
2475 $this->invalidateCache();
2480 * Generate a current or new-future timestamp to be stored in the
2481 * user_touched field when we update things.
2482 * @return string Timestamp in TS_MW format
2484 private function newTouchedTimestamp() {
2485 global $wgClockSkewFudge;
2487 $time = wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2488 if ( $this->mTouched
&& $time <= $this->mTouched
) {
2489 $time = wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $this->mTouched
) +
1 );
2496 * Clear user data from memcached
2498 * Use after applying updates to the database; caller's
2499 * responsibility to update user_touched if appropriate.
2501 * Called implicitly from invalidateCache() and saveSettings().
2503 * @param string $mode Use 'refresh' to clear now; otherwise before DB commit
2505 public function clearSharedCache( $mode = 'changed' ) {
2506 if ( !$this->getId() ) {
2510 $cache = ObjectCache
::getMainWANInstance();
2511 $key = $this->getCacheKey( $cache );
2512 if ( $mode === 'refresh' ) {
2513 $cache->delete( $key, 1 );
2515 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle(
2516 function () use ( $cache, $key ) {
2517 $cache->delete( $key );
2525 * Immediately touch the user data cache for this account
2527 * Calls touch() and removes account data from memcached
2529 public function invalidateCache() {
2531 $this->clearSharedCache();
2535 * Update the "touched" timestamp for the user
2537 * This is useful on various login/logout events when making sure that
2538 * a browser or proxy that has multiple tenants does not suffer cache
2539 * pollution where the new user sees the old users content. The value
2540 * of getTouched() is checked when determining 304 vs 200 responses.
2541 * Unlike invalidateCache(), this preserves the User object cache and
2542 * avoids database writes.
2546 public function touch() {
2547 $id = $this->getId();
2549 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
2550 $key = $cache->makeKey( 'user-quicktouched', 'id', $id );
2551 $cache->touchCheckKey( $key );
2552 $this->mQuickTouched
= null;
2557 * Validate the cache for this account.
2558 * @param string $timestamp A timestamp in TS_MW format
2561 public function validateCache( $timestamp ) {
2562 return ( $timestamp >= $this->getTouched() );
2566 * Get the user touched timestamp
2568 * Use this value only to validate caches via inequalities
2569 * such as in the case of HTTP If-Modified-Since response logic
2571 * @return string TS_MW Timestamp
2573 public function getTouched() {
2577 if ( $this->mQuickTouched
=== null ) {
2578 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
2579 $key = $cache->makeKey( 'user-quicktouched', 'id', $this->mId
);
2581 $this->mQuickTouched
= wfTimestamp( TS_MW
, $cache->getCheckKeyTime( $key ) );
2584 return max( $this->mTouched
, $this->mQuickTouched
);
2587 return $this->mTouched
;
2591 * Get the user_touched timestamp field (time of last DB updates)
2592 * @return string TS_MW Timestamp
2595 public function getDBTouched() {
2598 return $this->mTouched
;
2602 * Set the password and reset the random token.
2603 * Calls through to authentication plugin if necessary;
2604 * will have no effect if the auth plugin refuses to
2605 * pass the change through or if the legal password
2608 * As a special case, setting the password to null
2609 * wipes it, so the account cannot be logged in until
2610 * a new password is set, for instance via e-mail.
2612 * @deprecated since 1.27, use AuthManager instead
2613 * @param string $str New password to set
2614 * @throws PasswordError On failure
2617 public function setPassword( $str ) {
2618 return $this->setPasswordInternal( $str );
2622 * Set the password and reset the random token unconditionally.
2624 * @deprecated since 1.27, use AuthManager instead
2625 * @param string|null $str New password to set or null to set an invalid
2626 * password hash meaning that the user will not be able to log in
2627 * through the web interface.
2629 public function setInternalPassword( $str ) {
2630 $this->setPasswordInternal( $str );
2634 * Actually set the password and such
2635 * @since 1.27 cannot set a password for a user not in the database
2636 * @param string|null $str New password to set or null to set an invalid
2637 * password hash meaning that the user will not be able to log in
2638 * through the web interface.
2639 * @return bool Success
2641 private function setPasswordInternal( $str ) {
2642 $manager = AuthManager
::singleton();
2644 // If the user doesn't exist yet, fail
2645 if ( !$manager->userExists( $this->getName() ) ) {
2646 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2649 $status = $this->changeAuthenticationData( [
2650 'username' => $this->getName(),
2654 if ( !$status->isGood() ) {
2655 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
2656 ->info( __METHOD__
. ': Password change rejected: '
2657 . $status->getWikiText( null, null, 'en' ) );
2661 $this->setOption( 'watchlisttoken', false );
2662 SessionManager
::singleton()->invalidateSessionsForUser( $this );
2668 * Changes credentials of the user.
2670 * This is a convenience wrapper around AuthManager::changeAuthenticationData.
2671 * Note that this can return a status that isOK() but not isGood() on certain types of failures,
2672 * e.g. when no provider handled the change.
2674 * @param array $data A set of authentication data in fieldname => value format. This is the
2675 * same data you would pass the changeauthenticationdata API - 'username', 'password' etc.
2679 public function changeAuthenticationData( array $data ) {
2680 $manager = AuthManager
::singleton();
2681 $reqs = $manager->getAuthenticationRequests( AuthManager
::ACTION_CHANGE
, $this );
2682 $reqs = AuthenticationRequest
::loadRequestsFromSubmission( $reqs, $data );
2684 $status = Status
::newGood( 'ignored' );
2685 foreach ( $reqs as $req ) {
2686 $status->merge( $manager->allowsAuthenticationDataChange( $req ), true );
2688 if ( $status->getValue() === 'ignored' ) {
2689 $status->warning( 'authenticationdatachange-ignored' );
2692 if ( $status->isGood() ) {
2693 foreach ( $reqs as $req ) {
2694 $manager->changeAuthenticationData( $req );
2701 * Get the user's current token.
2702 * @param bool $forceCreation Force the generation of a new token if the
2703 * user doesn't have one (default=true for backwards compatibility).
2704 * @return string|null Token
2706 public function getToken( $forceCreation = true ) {
2707 global $wgAuthenticationTokenVersion;
2710 if ( !$this->mToken
&& $forceCreation ) {
2714 if ( !$this->mToken
) {
2715 // The user doesn't have a token, return null to indicate that.
2717 } elseif ( $this->mToken
=== self
::INVALID_TOKEN
) {
2718 // We return a random value here so existing token checks are very
2720 return MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2721 } elseif ( $wgAuthenticationTokenVersion === null ) {
2722 // $wgAuthenticationTokenVersion not in use, so return the raw secret
2723 return $this->mToken
;
2725 // $wgAuthenticationTokenVersion in use, so hmac it.
2726 $ret = MWCryptHash
::hmac( $wgAuthenticationTokenVersion, $this->mToken
, false );
2728 // The raw hash can be overly long. Shorten it up.
2729 $len = max( 32, self
::TOKEN_LENGTH
);
2730 if ( strlen( $ret ) < $len ) {
2731 // Should never happen, even md5 is 128 bits
2732 throw new \
UnexpectedValueException( 'Hmac returned less than 128 bits' );
2734 return substr( $ret, -$len );
2739 * Set the random token (used for persistent authentication)
2740 * Called from loadDefaults() among other places.
2742 * @param string|bool $token If specified, set the token to this value
2744 public function setToken( $token = false ) {
2746 if ( $this->mToken
=== self
::INVALID_TOKEN
) {
2747 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
2748 ->debug( __METHOD__
. ": Ignoring attempt to set token for system user \"$this\"" );
2749 } elseif ( !$token ) {
2750 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2752 $this->mToken
= $token;
2757 * Set the password for a password reminder or new account email
2759 * @deprecated Removed in 1.27. Use PasswordReset instead.
2760 * @param string $str New password to set or null to set an invalid
2761 * password hash meaning that the user will not be able to use it
2762 * @param bool $throttle If true, reset the throttle timestamp to the present
2764 public function setNewpassword( $str, $throttle = true ) {
2765 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2769 * Get the user's e-mail address
2770 * @return string User's email address
2772 public function getEmail() {
2774 Hooks
::run( 'UserGetEmail', [ $this, &$this->mEmail
] );
2775 return $this->mEmail
;
2779 * Get the timestamp of the user's e-mail authentication
2780 * @return string TS_MW timestamp
2782 public function getEmailAuthenticationTimestamp() {
2784 Hooks
::run( 'UserGetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
2785 return $this->mEmailAuthenticated
;
2789 * Set the user's e-mail address
2790 * @param string $str New e-mail address
2792 public function setEmail( $str ) {
2794 if ( $str == $this->mEmail
) {
2797 $this->invalidateEmail();
2798 $this->mEmail
= $str;
2799 Hooks
::run( 'UserSetEmail', [ $this, &$this->mEmail
] );
2803 * Set the user's e-mail address and a confirmation mail if needed.
2806 * @param string $str New e-mail address
2809 public function setEmailWithConfirmation( $str ) {
2810 global $wgEnableEmail, $wgEmailAuthentication;
2812 if ( !$wgEnableEmail ) {
2813 return Status
::newFatal( 'emaildisabled' );
2816 $oldaddr = $this->getEmail();
2817 if ( $str === $oldaddr ) {
2818 return Status
::newGood( true );
2821 $type = $oldaddr != '' ?
'changed' : 'set';
2822 $notificationResult = null;
2824 if ( $wgEmailAuthentication ) {
2825 // Send the user an email notifying the user of the change in registered
2826 // email address on their previous email address
2827 if ( $type == 'changed' ) {
2828 $change = $str != '' ?
'changed' : 'removed';
2829 $notificationResult = $this->sendMail(
2830 wfMessage( 'notificationemail_subject_' . $change )->text(),
2831 wfMessage( 'notificationemail_body_' . $change,
2832 $this->getRequest()->getIP(),
2839 $this->setEmail( $str );
2841 if ( $str !== '' && $wgEmailAuthentication ) {
2842 // Send a confirmation request to the new address if needed
2843 $result = $this->sendConfirmationMail( $type );
2845 if ( $notificationResult !== null ) {
2846 $result->merge( $notificationResult );
2849 if ( $result->isGood() ) {
2850 // Say to the caller that a confirmation and notification mail has been sent
2851 $result->value
= 'eauth';
2854 $result = Status
::newGood( true );
2861 * Get the user's real name
2862 * @return string User's real name
2864 public function getRealName() {
2865 if ( !$this->isItemLoaded( 'realname' ) ) {
2869 return $this->mRealName
;
2873 * Set the user's real name
2874 * @param string $str New real name
2876 public function setRealName( $str ) {
2878 $this->mRealName
= $str;
2882 * Get the user's current setting for a given option.
2884 * @param string $oname The option to check
2885 * @param string $defaultOverride A default value returned if the option does not exist
2886 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2887 * @return string|null User's current value for the option
2888 * @see getBoolOption()
2889 * @see getIntOption()
2891 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2892 global $wgHiddenPrefs;
2893 $this->loadOptions();
2895 # We want 'disabled' preferences to always behave as the default value for
2896 # users, even if they have set the option explicitly in their settings (ie they
2897 # set it, and then it was disabled removing their ability to change it). But
2898 # we don't want to erase the preferences in the database in case the preference
2899 # is re-enabled again. So don't touch $mOptions, just override the returned value
2900 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2901 return self
::getDefaultOption( $oname );
2904 if ( array_key_exists( $oname, $this->mOptions
) ) {
2905 return $this->mOptions
[$oname];
2907 return $defaultOverride;
2912 * Get all user's options
2914 * @param int $flags Bitwise combination of:
2915 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2916 * to the default value. (Since 1.25)
2919 public function getOptions( $flags = 0 ) {
2920 global $wgHiddenPrefs;
2921 $this->loadOptions();
2922 $options = $this->mOptions
;
2924 # We want 'disabled' preferences to always behave as the default value for
2925 # users, even if they have set the option explicitly in their settings (ie they
2926 # set it, and then it was disabled removing their ability to change it). But
2927 # we don't want to erase the preferences in the database in case the preference
2928 # is re-enabled again. So don't touch $mOptions, just override the returned value
2929 foreach ( $wgHiddenPrefs as $pref ) {
2930 $default = self
::getDefaultOption( $pref );
2931 if ( $default !== null ) {
2932 $options[$pref] = $default;
2936 if ( $flags & self
::GETOPTIONS_EXCLUDE_DEFAULTS
) {
2937 $options = array_diff_assoc( $options, self
::getDefaultOptions() );
2944 * Get the user's current setting for a given option, as a boolean value.
2946 * @param string $oname The option to check
2947 * @return bool User's current value for the option
2950 public function getBoolOption( $oname ) {
2951 return (bool)$this->getOption( $oname );
2955 * Get the user's current setting for a given option, as an integer value.
2957 * @param string $oname The option to check
2958 * @param int $defaultOverride A default value returned if the option does not exist
2959 * @return int User's current value for the option
2962 public function getIntOption( $oname, $defaultOverride = 0 ) {
2963 $val = $this->getOption( $oname );
2965 $val = $defaultOverride;
2967 return intval( $val );
2971 * Set the given option for a user.
2973 * You need to call saveSettings() to actually write to the database.
2975 * @param string $oname The option to set
2976 * @param mixed $val New value to set
2978 public function setOption( $oname, $val ) {
2979 $this->loadOptions();
2981 // Explicitly NULL values should refer to defaults
2982 if ( is_null( $val ) ) {
2983 $val = self
::getDefaultOption( $oname );
2986 $this->mOptions
[$oname] = $val;
2990 * Get a token stored in the preferences (like the watchlist one),
2991 * resetting it if it's empty (and saving changes).
2993 * @param string $oname The option name to retrieve the token from
2994 * @return string|bool User's current value for the option, or false if this option is disabled.
2995 * @see resetTokenFromOption()
2997 * @deprecated since 1.26 Applications should use the OAuth extension
2999 public function getTokenFromOption( $oname ) {
3000 global $wgHiddenPrefs;
3002 $id = $this->getId();
3003 if ( !$id ||
in_array( $oname, $wgHiddenPrefs ) ) {
3007 $token = $this->getOption( $oname );
3009 // Default to a value based on the user token to avoid space
3010 // wasted on storing tokens for all users. When this option
3011 // is set manually by the user, only then is it stored.
3012 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
3019 * Reset a token stored in the preferences (like the watchlist one).
3020 * *Does not* save user's preferences (similarly to setOption()).
3022 * @param string $oname The option name to reset the token in
3023 * @return string|bool New token value, or false if this option is disabled.
3024 * @see getTokenFromOption()
3027 public function resetTokenFromOption( $oname ) {
3028 global $wgHiddenPrefs;
3029 if ( in_array( $oname, $wgHiddenPrefs ) ) {
3033 $token = MWCryptRand
::generateHex( 40 );
3034 $this->setOption( $oname, $token );
3039 * Return a list of the types of user options currently returned by
3040 * User::getOptionKinds().
3042 * Currently, the option kinds are:
3043 * - 'registered' - preferences which are registered in core MediaWiki or
3044 * by extensions using the UserGetDefaultOptions hook.
3045 * - 'registered-multiselect' - as above, using the 'multiselect' type.
3046 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
3047 * - 'userjs' - preferences with names starting with 'userjs-', intended to
3048 * be used by user scripts.
3049 * - 'special' - "preferences" that are not accessible via User::getOptions
3050 * or User::setOptions.
3051 * - 'unused' - preferences about which MediaWiki doesn't know anything.
3052 * These are usually legacy options, removed in newer versions.
3054 * The API (and possibly others) use this function to determine the possible
3055 * option types for validation purposes, so make sure to update this when a
3056 * new option kind is added.
3058 * @see User::getOptionKinds
3059 * @return array Option kinds
3061 public static function listOptionKinds() {
3064 'registered-multiselect',
3065 'registered-checkmatrix',
3073 * Return an associative array mapping preferences keys to the kind of a preference they're
3074 * used for. Different kinds are handled differently when setting or reading preferences.
3076 * See User::listOptionKinds for the list of valid option types that can be provided.
3078 * @see User::listOptionKinds
3079 * @param IContextSource $context
3080 * @param array $options Assoc. array with options keys to check as keys.
3081 * Defaults to $this->mOptions.
3082 * @return array The key => kind mapping data
3084 public function getOptionKinds( IContextSource
$context, $options = null ) {
3085 $this->loadOptions();
3086 if ( $options === null ) {
3087 $options = $this->mOptions
;
3090 $prefs = Preferences
::getPreferences( $this, $context );
3093 // Pull out the "special" options, so they don't get converted as
3094 // multiselect or checkmatrix.
3095 $specialOptions = array_fill_keys( Preferences
::getSaveBlacklist(), true );
3096 foreach ( $specialOptions as $name => $value ) {
3097 unset( $prefs[$name] );
3100 // Multiselect and checkmatrix options are stored in the database with
3101 // one key per option, each having a boolean value. Extract those keys.
3102 $multiselectOptions = [];
3103 foreach ( $prefs as $name => $info ) {
3104 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
3105 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
3106 $opts = HTMLFormField
::flattenOptions( $info['options'] );
3107 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
3109 foreach ( $opts as $value ) {
3110 $multiselectOptions["$prefix$value"] = true;
3113 unset( $prefs[$name] );
3116 $checkmatrixOptions = [];
3117 foreach ( $prefs as $name => $info ) {
3118 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
3119 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
3120 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
3121 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
3122 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
3124 foreach ( $columns as $column ) {
3125 foreach ( $rows as $row ) {
3126 $checkmatrixOptions["$prefix$column-$row"] = true;
3130 unset( $prefs[$name] );
3134 // $value is ignored
3135 foreach ( $options as $key => $value ) {
3136 if ( isset( $prefs[$key] ) ) {
3137 $mapping[$key] = 'registered';
3138 } elseif ( isset( $multiselectOptions[$key] ) ) {
3139 $mapping[$key] = 'registered-multiselect';
3140 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
3141 $mapping[$key] = 'registered-checkmatrix';
3142 } elseif ( isset( $specialOptions[$key] ) ) {
3143 $mapping[$key] = 'special';
3144 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
3145 $mapping[$key] = 'userjs';
3147 $mapping[$key] = 'unused';
3155 * Reset certain (or all) options to the site defaults
3157 * The optional parameter determines which kinds of preferences will be reset.
3158 * Supported values are everything that can be reported by getOptionKinds()
3159 * and 'all', which forces a reset of *all* preferences and overrides everything else.
3161 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
3162 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
3163 * for backwards-compatibility.
3164 * @param IContextSource|null $context Context source used when $resetKinds
3165 * does not contain 'all', passed to getOptionKinds().
3166 * Defaults to RequestContext::getMain() when null.
3168 public function resetOptions(
3169 $resetKinds = [ 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ],
3170 IContextSource
$context = null
3173 $defaultOptions = self
::getDefaultOptions();
3175 if ( !is_array( $resetKinds ) ) {
3176 $resetKinds = [ $resetKinds ];
3179 if ( in_array( 'all', $resetKinds ) ) {
3180 $newOptions = $defaultOptions;
3182 if ( $context === null ) {
3183 $context = RequestContext
::getMain();
3186 $optionKinds = $this->getOptionKinds( $context );
3187 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
3190 // Use default values for the options that should be deleted, and
3191 // copy old values for the ones that shouldn't.
3192 foreach ( $this->mOptions
as $key => $value ) {
3193 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
3194 if ( array_key_exists( $key, $defaultOptions ) ) {
3195 $newOptions[$key] = $defaultOptions[$key];
3198 $newOptions[$key] = $value;
3203 Hooks
::run( 'UserResetAllOptions', [ $this, &$newOptions, $this->mOptions
, $resetKinds ] );
3205 $this->mOptions
= $newOptions;
3206 $this->mOptionsLoaded
= true;
3210 * Get the user's preferred date format.
3211 * @return string User's preferred date format
3213 public function getDatePreference() {
3214 // Important migration for old data rows
3215 if ( is_null( $this->mDatePreference
) ) {
3217 $value = $this->getOption( 'date' );
3218 $map = $wgLang->getDatePreferenceMigrationMap();
3219 if ( isset( $map[$value] ) ) {
3220 $value = $map[$value];
3222 $this->mDatePreference
= $value;
3224 return $this->mDatePreference
;
3228 * Determine based on the wiki configuration and the user's options,
3229 * whether this user must be over HTTPS no matter what.
3233 public function requiresHTTPS() {
3234 global $wgSecureLogin;
3235 if ( !$wgSecureLogin ) {
3238 $https = $this->getBoolOption( 'prefershttps' );
3239 Hooks
::run( 'UserRequiresHTTPS', [ $this, &$https ] );
3241 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
3248 * Get the user preferred stub threshold
3252 public function getStubThreshold() {
3253 global $wgMaxArticleSize; # Maximum article size, in Kb
3254 $threshold = $this->getIntOption( 'stubthreshold' );
3255 if ( $threshold > $wgMaxArticleSize * 1024 ) {
3256 // If they have set an impossible value, disable the preference
3257 // so we can use the parser cache again.
3264 * Get the permissions this user has.
3265 * @return string[] permission names
3267 public function getRights() {
3268 if ( is_null( $this->mRights
) ) {
3269 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
3270 Hooks
::run( 'UserGetRights', [ $this, &$this->mRights
] );
3272 // Deny any rights denied by the user's session, unless this
3273 // endpoint has no sessions.
3274 if ( !defined( 'MW_NO_SESSION' ) ) {
3275 $allowedRights = $this->getRequest()->getSession()->getAllowedUserRights();
3276 if ( $allowedRights !== null ) {
3277 $this->mRights
= array_intersect( $this->mRights
, $allowedRights );
3281 // Force reindexation of rights when a hook has unset one of them
3282 $this->mRights
= array_values( array_unique( $this->mRights
) );
3284 // If block disables login, we should also remove any
3285 // extra rights blocked users might have, in case the
3286 // blocked user has a pre-existing session (T129738).
3287 // This is checked here for cases where people only call
3288 // $user->isAllowed(). It is also checked in Title::checkUserBlock()
3289 // to give a better error message in the common case.
3290 $config = RequestContext
::getMain()->getConfig();
3292 $this->isLoggedIn() &&
3293 $config->get( 'BlockDisablesLogin' ) &&
3297 $this->mRights
= array_intersect( $this->mRights
, $anon->getRights() );
3300 return $this->mRights
;
3304 * Get the list of explicit group memberships this user has.
3305 * The implicit * and user groups are not included.
3306 * @return array Array of String internal group names
3308 public function getGroups() {
3310 $this->loadGroups();
3311 return array_keys( $this->mGroupMemberships
);
3315 * Get the list of explicit group memberships this user has, stored as
3316 * UserGroupMembership objects. Implicit groups are not included.
3318 * @return array Associative array of (group name as string => UserGroupMembership object)
3321 public function getGroupMemberships() {
3323 $this->loadGroups();
3324 return $this->mGroupMemberships
;
3328 * Get the list of implicit group memberships this user has.
3329 * This includes all explicit groups, plus 'user' if logged in,
3330 * '*' for all accounts, and autopromoted groups
3331 * @param bool $recache Whether to avoid the cache
3332 * @return array Array of String internal group names
3334 public function getEffectiveGroups( $recache = false ) {
3335 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
3336 $this->mEffectiveGroups
= array_unique( array_merge(
3337 $this->getGroups(), // explicit groups
3338 $this->getAutomaticGroups( $recache ) // implicit groups
3340 // Avoid PHP 7.1 warning of passing $this by reference
3342 // Hook for additional groups
3343 Hooks
::run( 'UserEffectiveGroups', [ &$user, &$this->mEffectiveGroups
] );
3344 // Force reindexation of groups when a hook has unset one of them
3345 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
3347 return $this->mEffectiveGroups
;
3351 * Get the list of implicit group memberships this user has.
3352 * This includes 'user' if logged in, '*' for all accounts,
3353 * and autopromoted groups
3354 * @param bool $recache Whether to avoid the cache
3355 * @return array Array of String internal group names
3357 public function getAutomaticGroups( $recache = false ) {
3358 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
3359 $this->mImplicitGroups
= [ '*' ];
3360 if ( $this->getId() ) {
3361 $this->mImplicitGroups
[] = 'user';
3363 $this->mImplicitGroups
= array_unique( array_merge(
3364 $this->mImplicitGroups
,
3365 Autopromote
::getAutopromoteGroups( $this )
3369 // Assure data consistency with rights/groups,
3370 // as getEffectiveGroups() depends on this function
3371 $this->mEffectiveGroups
= null;
3374 return $this->mImplicitGroups
;
3378 * Returns the groups the user has belonged to.
3380 * The user may still belong to the returned groups. Compare with getGroups().
3382 * The function will not return groups the user had belonged to before MW 1.17
3384 * @return array Names of the groups the user has belonged to.
3386 public function getFormerGroups() {
3389 if ( is_null( $this->mFormerGroups
) ) {
3390 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3391 ?
wfGetDB( DB_MASTER
)
3392 : wfGetDB( DB_REPLICA
);
3393 $res = $db->select( 'user_former_groups',
3395 [ 'ufg_user' => $this->mId
],
3397 $this->mFormerGroups
= [];
3398 foreach ( $res as $row ) {
3399 $this->mFormerGroups
[] = $row->ufg_group
;
3403 return $this->mFormerGroups
;
3407 * Get the user's edit count.
3408 * @return int|null Null for anonymous users
3410 public function getEditCount() {
3411 if ( !$this->getId() ) {
3415 if ( $this->mEditCount
=== null ) {
3416 /* Populate the count, if it has not been populated yet */
3417 $dbr = wfGetDB( DB_REPLICA
);
3418 // check if the user_editcount field has been initialized
3419 $count = $dbr->selectField(
3420 'user', 'user_editcount',
3421 [ 'user_id' => $this->mId
],
3425 if ( $count === null ) {
3426 // it has not been initialized. do so.
3427 $count = $this->initEditCount();
3429 $this->mEditCount
= $count;
3431 return (int)$this->mEditCount
;
3435 * Add the user to the given group. This takes immediate effect.
3436 * If the user is already in the group, the expiry time will be updated to the new
3437 * expiry time. (If $expiry is omitted or null, the membership will be altered to
3440 * @param string $group Name of the group to add
3441 * @param string $expiry Optional expiry timestamp in any format acceptable to
3442 * wfTimestamp(), or null if the group assignment should not expire
3445 public function addGroup( $group, $expiry = null ) {
3447 $this->loadGroups();
3450 $expiry = wfTimestamp( TS_MW
, $expiry );
3453 if ( !Hooks
::run( 'UserAddGroup', [ $this, &$group, &$expiry ] ) ) {
3457 // create the new UserGroupMembership and put it in the DB
3458 $ugm = new UserGroupMembership( $this->mId
, $group, $expiry );
3459 if ( !$ugm->insert( true ) ) {
3463 $this->mGroupMemberships
[$group] = $ugm;
3465 // Refresh the groups caches, and clear the rights cache so it will be
3466 // refreshed on the next call to $this->getRights().
3467 $this->getEffectiveGroups( true );
3468 $this->mRights
= null;
3470 $this->invalidateCache();
3476 * Remove the user from the given group.
3477 * This takes immediate effect.
3478 * @param string $group Name of the group to remove
3481 public function removeGroup( $group ) {
3484 if ( !Hooks
::run( 'UserRemoveGroup', [ $this, &$group ] ) ) {
3488 $ugm = UserGroupMembership
::getMembership( $this->mId
, $group );
3489 // delete the membership entry
3490 if ( !$ugm ||
!$ugm->delete() ) {
3494 $this->loadGroups();
3495 unset( $this->mGroupMemberships
[$group] );
3497 // Refresh the groups caches, and clear the rights cache so it will be
3498 // refreshed on the next call to $this->getRights().
3499 $this->getEffectiveGroups( true );
3500 $this->mRights
= null;
3502 $this->invalidateCache();
3508 * Get whether the user is logged in
3511 public function isLoggedIn() {
3512 return $this->getId() != 0;
3516 * Get whether the user is anonymous
3519 public function isAnon() {
3520 return !$this->isLoggedIn();
3524 * @return bool Whether this user is flagged as being a bot role account
3527 public function isBot() {
3528 if ( in_array( 'bot', $this->getGroups() ) && $this->isAllowed( 'bot' ) ) {
3533 Hooks
::run( "UserIsBot", [ $this, &$isBot ] );
3539 * Check if user is allowed to access a feature / make an action
3541 * @param string $permissions,... Permissions to test
3542 * @return bool True if user is allowed to perform *any* of the given actions
3544 public function isAllowedAny() {
3545 $permissions = func_get_args();
3546 foreach ( $permissions as $permission ) {
3547 if ( $this->isAllowed( $permission ) ) {
3556 * @param string $permissions,... Permissions to test
3557 * @return bool True if the user is allowed to perform *all* of the given actions
3559 public function isAllowedAll() {
3560 $permissions = func_get_args();
3561 foreach ( $permissions as $permission ) {
3562 if ( !$this->isAllowed( $permission ) ) {
3570 * Internal mechanics of testing a permission
3571 * @param string $action
3574 public function isAllowed( $action = '' ) {
3575 if ( $action === '' ) {
3576 return true; // In the spirit of DWIM
3578 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3579 // by misconfiguration: 0 == 'foo'
3580 return in_array( $action, $this->getRights(), true );
3584 * Check whether to enable recent changes patrol features for this user
3585 * @return bool True or false
3587 public function useRCPatrol() {
3588 global $wgUseRCPatrol;
3589 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3593 * Check whether to enable new pages patrol features for this user
3594 * @return bool True or false
3596 public function useNPPatrol() {
3597 global $wgUseRCPatrol, $wgUseNPPatrol;
3599 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3600 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3605 * Check whether to enable new files patrol features for this user
3606 * @return bool True or false
3608 public function useFilePatrol() {
3609 global $wgUseRCPatrol, $wgUseFilePatrol;
3611 ( $wgUseRCPatrol ||
$wgUseFilePatrol )
3612 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3617 * Get the WebRequest object to use with this object
3619 * @return WebRequest
3621 public function getRequest() {
3622 if ( $this->mRequest
) {
3623 return $this->mRequest
;
3631 * Check the watched status of an article.
3632 * @since 1.22 $checkRights parameter added
3633 * @param Title $title Title of the article to look at
3634 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3635 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3638 public function isWatched( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3639 if ( $title->isWatchable() && ( !$checkRights ||
$this->isAllowed( 'viewmywatchlist' ) ) ) {
3640 return MediaWikiServices
::getInstance()->getWatchedItemStore()->isWatched( $this, $title );
3647 * @since 1.22 $checkRights parameter added
3648 * @param Title $title Title of the article to look at
3649 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3650 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3652 public function addWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3653 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3654 MediaWikiServices
::getInstance()->getWatchedItemStore()->addWatchBatchForUser(
3656 [ $title->getSubjectPage(), $title->getTalkPage() ]
3659 $this->invalidateCache();
3663 * Stop watching an article.
3664 * @since 1.22 $checkRights parameter added
3665 * @param Title $title Title of the article to look at
3666 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3667 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3669 public function removeWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3670 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3671 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
3672 $store->removeWatch( $this, $title->getSubjectPage() );
3673 $store->removeWatch( $this, $title->getTalkPage() );
3675 $this->invalidateCache();
3679 * Clear the user's notification timestamp for the given title.
3680 * If e-notif e-mails are on, they will receive notification mails on
3681 * the next change of the page if it's watched etc.
3682 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3683 * @param Title &$title Title of the article to look at
3684 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3686 public function clearNotification( &$title, $oldid = 0 ) {
3687 global $wgUseEnotif, $wgShowUpdatedMarker;
3689 // Do nothing if the database is locked to writes
3690 if ( wfReadOnly() ) {
3694 // Do nothing if not allowed to edit the watchlist
3695 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3699 // If we're working on user's talk page, we should update the talk page message indicator
3700 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3701 // Avoid PHP 7.1 warning of passing $this by reference
3703 if ( !Hooks
::run( 'UserClearNewTalkNotification', [ &$user, $oldid ] ) ) {
3707 // Try to update the DB post-send and only if needed...
3708 DeferredUpdates
::addCallableUpdate( function () use ( $title, $oldid ) {
3709 if ( !$this->getNewtalk() ) {
3710 return; // no notifications to clear
3713 // Delete the last notifications (they stack up)
3714 $this->setNewtalk( false );
3716 // If there is a new, unseen, revision, use its timestamp
3718 ?
$title->getNextRevisionID( $oldid, Title
::GAID_FOR_UPDATE
)
3721 $this->setNewtalk( true, Revision
::newFromId( $nextid ) );
3726 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3730 if ( $this->isAnon() ) {
3731 // Nothing else to do...
3735 // Only update the timestamp if the page is being watched.
3736 // The query to find out if it is watched is cached both in memcached and per-invocation,
3737 // and when it does have to be executed, it can be on a replica DB
3738 // If this is the user's newtalk page, we always update the timestamp
3740 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3744 MediaWikiServices
::getInstance()->getWatchedItemStore()
3745 ->resetNotificationTimestamp( $this, $title, $force, $oldid );
3749 * Resets all of the given user's page-change notification timestamps.
3750 * If e-notif e-mails are on, they will receive notification mails on
3751 * the next change of any watched page.
3752 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3754 public function clearAllNotifications() {
3755 global $wgUseEnotif, $wgShowUpdatedMarker;
3756 // Do nothing if not allowed to edit the watchlist
3757 if ( wfReadOnly() ||
!$this->isAllowed( 'editmywatchlist' ) ) {
3761 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3762 $this->setNewtalk( false );
3766 $id = $this->getId();
3771 $dbw = wfGetDB( DB_MASTER
);
3772 $asOfTimes = array_unique( $dbw->selectFieldValues(
3774 'wl_notificationtimestamp',
3775 [ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ],
3777 [ 'ORDER BY' => 'wl_notificationtimestamp DESC', 'LIMIT' => 500 ]
3779 if ( !$asOfTimes ) {
3782 // Immediately update the most recent touched rows, which hopefully covers what
3783 // the user sees on the watchlist page before pressing "mark all pages visited"....
3786 [ 'wl_notificationtimestamp' => null ],
3787 [ 'wl_user' => $id, 'wl_notificationtimestamp' => $asOfTimes ],
3790 // ...and finish the older ones in a post-send update with lag checks...
3791 DeferredUpdates
::addUpdate( new AutoCommitUpdate(
3794 function () use ( $dbw, $id ) {
3795 global $wgUpdateRowsPerQuery;
3797 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
3798 $ticket = $lbFactory->getEmptyTransactionTicket( __METHOD__
);
3799 $asOfTimes = array_unique( $dbw->selectFieldValues(
3801 'wl_notificationtimestamp',
3802 [ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ],
3805 foreach ( array_chunk( $asOfTimes, $wgUpdateRowsPerQuery ) as $asOfTimeBatch ) {
3808 [ 'wl_notificationtimestamp' => null ],
3809 [ 'wl_user' => $id, 'wl_notificationtimestamp' => $asOfTimeBatch ],
3812 $lbFactory->commitAndWaitForReplication( __METHOD__
, $ticket );
3816 // We also need to clear here the "you have new message" notification for the own
3817 // user_talk page; it's cleared one page view later in WikiPage::doViewUpdates().
3821 * Compute experienced level based on edit count and registration date.
3823 * @return string 'newcomer', 'learner', or 'experienced'
3825 public function getExperienceLevel() {
3826 global $wgLearnerEdits,
3827 $wgExperiencedUserEdits,
3828 $wgLearnerMemberSince,
3829 $wgExperiencedUserMemberSince;
3831 if ( $this->isAnon() ) {
3835 $editCount = $this->getEditCount();
3836 $registration = $this->getRegistration();
3838 $learnerRegistration = wfTimestamp( TS_MW
, $now - $wgLearnerMemberSince * 86400 );
3839 $experiencedRegistration = wfTimestamp( TS_MW
, $now - $wgExperiencedUserMemberSince * 86400 );
3842 $editCount < $wgLearnerEdits ||
3843 $registration > $learnerRegistration
3847 $editCount > $wgExperiencedUserEdits &&
3848 $registration <= $experiencedRegistration
3850 return 'experienced';
3857 * Set a cookie on the user's client. Wrapper for
3858 * WebResponse::setCookie
3859 * @deprecated since 1.27
3860 * @param string $name Name of the cookie to set
3861 * @param string $value Value to set
3862 * @param int $exp Expiration time, as a UNIX time value;
3863 * if 0 or not specified, use the default $wgCookieExpiration
3864 * @param bool $secure
3865 * true: Force setting the secure attribute when setting the cookie
3866 * false: Force NOT setting the secure attribute when setting the cookie
3867 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3868 * @param array $params Array of options sent passed to WebResponse::setcookie()
3869 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3872 protected function setCookie(
3873 $name, $value, $exp = 0, $secure = null, $params = [], $request = null
3875 wfDeprecated( __METHOD__
, '1.27' );
3876 if ( $request === null ) {
3877 $request = $this->getRequest();
3879 $params['secure'] = $secure;
3880 $request->response()->setCookie( $name, $value, $exp, $params );
3884 * Clear a cookie on the user's client
3885 * @deprecated since 1.27
3886 * @param string $name Name of the cookie to clear
3887 * @param bool $secure
3888 * true: Force setting the secure attribute when setting the cookie
3889 * false: Force NOT setting the secure attribute when setting the cookie
3890 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3891 * @param array $params Array of options sent passed to WebResponse::setcookie()
3893 protected function clearCookie( $name, $secure = null, $params = [] ) {
3894 wfDeprecated( __METHOD__
, '1.27' );
3895 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3899 * Set an extended login cookie on the user's client. The expiry of the cookie
3900 * is controlled by the $wgExtendedLoginCookieExpiration configuration
3903 * @see User::setCookie
3905 * @deprecated since 1.27
3906 * @param string $name Name of the cookie to set
3907 * @param string $value Value to set
3908 * @param bool $secure
3909 * true: Force setting the secure attribute when setting the cookie
3910 * false: Force NOT setting the secure attribute when setting the cookie
3911 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3913 protected function setExtendedLoginCookie( $name, $value, $secure ) {
3914 global $wgExtendedLoginCookieExpiration, $wgCookieExpiration;
3916 wfDeprecated( __METHOD__
, '1.27' );
3919 $exp +
= $wgExtendedLoginCookieExpiration !== null
3920 ?
$wgExtendedLoginCookieExpiration
3921 : $wgCookieExpiration;
3923 $this->setCookie( $name, $value, $exp, $secure );
3927 * Persist this user's session (e.g. set cookies)
3929 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3931 * @param bool $secure Whether to force secure/insecure cookies or use default
3932 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3934 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3936 if ( 0 == $this->mId
) {
3940 $session = $this->getRequest()->getSession();
3941 if ( $request && $session->getRequest() !== $request ) {
3942 $session = $session->sessionWithRequest( $request );
3944 $delay = $session->delaySave();
3946 if ( !$session->getUser()->equals( $this ) ) {
3947 if ( !$session->canSetUser() ) {
3948 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3949 ->warning( __METHOD__
.
3950 ": Cannot save user \"$this\" to a user \"{$session->getUser()}\"'s immutable session"
3954 $session->setUser( $this );
3957 $session->setRememberUser( $rememberMe );
3958 if ( $secure !== null ) {
3959 $session->setForceHTTPS( $secure );
3962 $session->persist();
3964 ScopedCallback
::consume( $delay );
3968 * Log this user out.
3970 public function logout() {
3971 // Avoid PHP 7.1 warning of passing $this by reference
3973 if ( Hooks
::run( 'UserLogout', [ &$user ] ) ) {
3979 * Clear the user's session, and reset the instance cache.
3982 public function doLogout() {
3983 $session = $this->getRequest()->getSession();
3984 if ( !$session->canSetUser() ) {
3985 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3986 ->warning( __METHOD__
. ": Cannot log out of an immutable session" );
3987 $error = 'immutable';
3988 } elseif ( !$session->getUser()->equals( $this ) ) {
3989 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3990 ->warning( __METHOD__
.
3991 ": Cannot log user \"$this\" out of a user \"{$session->getUser()}\"'s session"
3993 // But we still may as well make this user object anon
3994 $this->clearInstanceCache( 'defaults' );
3995 $error = 'wronguser';
3997 $this->clearInstanceCache( 'defaults' );
3998 $delay = $session->delaySave();
3999 $session->unpersist(); // Clear cookies (T127436)
4000 $session->setLoggedOutTimestamp( time() );
4001 $session->setUser( new User
);
4002 $session->set( 'wsUserID', 0 ); // Other code expects this
4003 $session->resetAllTokens();
4004 ScopedCallback
::consume( $delay );
4007 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authevents' )->info( 'Logout', [
4008 'event' => 'logout',
4009 'successful' => $error === false,
4010 'status' => $error ?
: 'success',
4015 * Save this user's settings into the database.
4016 * @todo Only rarely do all these fields need to be set!
4018 public function saveSettings() {
4019 if ( wfReadOnly() ) {
4020 // @TODO: caller should deal with this instead!
4021 // This should really just be an exception.
4022 MWExceptionHandler
::logException( new DBExpectedError(
4024 "Could not update user with ID '{$this->mId}'; DB is read-only."
4030 if ( 0 == $this->mId
) {
4034 // Get a new user_touched that is higher than the old one.
4035 // This will be used for a CAS check as a last-resort safety
4036 // check against race conditions and replica DB lag.
4037 $newTouched = $this->newTouchedTimestamp();
4039 $dbw = wfGetDB( DB_MASTER
);
4040 $dbw->update( 'user',
4042 'user_name' => $this->mName
,
4043 'user_real_name' => $this->mRealName
,
4044 'user_email' => $this->mEmail
,
4045 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
4046 'user_touched' => $dbw->timestamp( $newTouched ),
4047 'user_token' => strval( $this->mToken
),
4048 'user_email_token' => $this->mEmailToken
,
4049 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
4050 ], $this->makeUpdateConditions( $dbw, [ /* WHERE */
4051 'user_id' => $this->mId
,
4055 if ( !$dbw->affectedRows() ) {
4056 // Maybe the problem was a missed cache update; clear it to be safe
4057 $this->clearSharedCache( 'refresh' );
4058 // User was changed in the meantime or loaded with stale data
4059 $from = ( $this->queryFlagsUsed
& self
::READ_LATEST
) ?
'master' : 'replica';
4060 throw new MWException(
4061 "CAS update failed on user_touched for user ID '{$this->mId}' (read from $from);" .
4062 " the version of the user to be saved is older than the current version."
4066 $this->mTouched
= $newTouched;
4067 $this->saveOptions();
4069 Hooks
::run( 'UserSaveSettings', [ $this ] );
4070 $this->clearSharedCache();
4071 $this->getUserPage()->invalidateCache();
4075 * If only this user's username is known, and it exists, return the user ID.
4077 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
4080 public function idForName( $flags = 0 ) {
4081 $s = trim( $this->getName() );
4086 $db = ( ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
)
4087 ?
wfGetDB( DB_MASTER
)
4088 : wfGetDB( DB_REPLICA
);
4090 $options = ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
)
4091 ?
[ 'LOCK IN SHARE MODE' ]
4094 $id = $db->selectField( 'user',
4095 'user_id', [ 'user_name' => $s ], __METHOD__
, $options );
4101 * Add a user to the database, return the user object
4103 * @param string $name Username to add
4104 * @param array $params Array of Strings Non-default parameters to save to
4105 * the database as user_* fields:
4106 * - email: The user's email address.
4107 * - email_authenticated: The email authentication timestamp.
4108 * - real_name: The user's real name.
4109 * - options: An associative array of non-default options.
4110 * - token: Random authentication token. Do not set.
4111 * - registration: Registration timestamp. Do not set.
4113 * @return User|null User object, or null if the username already exists.
4115 public static function createNew( $name, $params = [] ) {
4116 foreach ( [ 'password', 'newpassword', 'newpass_time', 'password_expires' ] as $field ) {
4117 if ( isset( $params[$field] ) ) {
4118 wfDeprecated( __METHOD__
. " with param '$field'", '1.27' );
4119 unset( $params[$field] );
4125 $user->setToken(); // init token
4126 if ( isset( $params['options'] ) ) {
4127 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
4128 unset( $params['options'] );
4130 $dbw = wfGetDB( DB_MASTER
);
4132 $noPass = PasswordFactory
::newInvalidPassword()->toString();
4135 'user_name' => $name,
4136 'user_password' => $noPass,
4137 'user_newpassword' => $noPass,
4138 'user_email' => $user->mEmail
,
4139 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
4140 'user_real_name' => $user->mRealName
,
4141 'user_token' => strval( $user->mToken
),
4142 'user_registration' => $dbw->timestamp( $user->mRegistration
),
4143 'user_editcount' => 0,
4144 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
4146 foreach ( $params as $name => $value ) {
4147 $fields["user_$name"] = $value;
4149 $dbw->insert( 'user', $fields, __METHOD__
, [ 'IGNORE' ] );
4150 if ( $dbw->affectedRows() ) {
4151 $newUser = self
::newFromId( $dbw->insertId() );
4159 * Add this existing user object to the database. If the user already
4160 * exists, a fatal status object is returned, and the user object is
4161 * initialised with the data from the database.
4163 * Previously, this function generated a DB error due to a key conflict
4164 * if the user already existed. Many extension callers use this function
4165 * in code along the lines of:
4167 * $user = User::newFromName( $name );
4168 * if ( !$user->isLoggedIn() ) {
4169 * $user->addToDatabase();
4171 * // do something with $user...
4173 * However, this was vulnerable to a race condition (T18020). By
4174 * initialising the user object if the user exists, we aim to support this
4175 * calling sequence as far as possible.
4177 * Note that if the user exists, this function will acquire a write lock,
4178 * so it is still advisable to make the call conditional on isLoggedIn(),
4179 * and to commit the transaction after calling.
4181 * @throws MWException
4184 public function addToDatabase() {
4186 if ( !$this->mToken
) {
4187 $this->setToken(); // init token
4190 if ( !is_string( $this->mName
) ) {
4191 throw new RuntimeException( "User name field is not set." );
4194 $this->mTouched
= $this->newTouchedTimestamp();
4196 $noPass = PasswordFactory
::newInvalidPassword()->toString();
4198 $dbw = wfGetDB( DB_MASTER
);
4199 $dbw->insert( 'user',
4201 'user_name' => $this->mName
,
4202 'user_password' => $noPass,
4203 'user_newpassword' => $noPass,
4204 'user_email' => $this->mEmail
,
4205 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
4206 'user_real_name' => $this->mRealName
,
4207 'user_token' => strval( $this->mToken
),
4208 'user_registration' => $dbw->timestamp( $this->mRegistration
),
4209 'user_editcount' => 0,
4210 'user_touched' => $dbw->timestamp( $this->mTouched
),
4214 if ( !$dbw->affectedRows() ) {
4215 // Use locking reads to bypass any REPEATABLE-READ snapshot.
4216 $this->mId
= $dbw->selectField(
4219 [ 'user_name' => $this->mName
],
4221 [ 'LOCK IN SHARE MODE' ]
4225 if ( $this->loadFromDatabase( self
::READ_LOCKING
) ) {
4230 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
4231 "to insert user '{$this->mName}' row, but it was not present in select!" );
4233 return Status
::newFatal( 'userexists' );
4235 $this->mId
= $dbw->insertId();
4236 self
::$idCacheByName[$this->mName
] = $this->mId
;
4238 // Clear instance cache other than user table data, which is already accurate
4239 $this->clearInstanceCache();
4241 $this->saveOptions();
4242 return Status
::newGood();
4246 * If this user is logged-in and blocked,
4247 * block any IP address they've successfully logged in from.
4248 * @return bool A block was spread
4250 public function spreadAnyEditBlock() {
4251 if ( $this->isLoggedIn() && $this->isBlocked() ) {
4252 return $this->spreadBlock();
4259 * If this (non-anonymous) user is blocked,
4260 * block the IP address they've successfully logged in from.
4261 * @return bool A block was spread
4263 protected function spreadBlock() {
4264 wfDebug( __METHOD__
. "()\n" );
4266 if ( $this->mId
== 0 ) {
4270 $userblock = Block
::newFromTarget( $this->getName() );
4271 if ( !$userblock ) {
4275 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
4279 * Get whether the user is explicitly blocked from account creation.
4280 * @return bool|Block
4282 public function isBlockedFromCreateAccount() {
4283 $this->getBlockedStatus();
4284 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
4285 return $this->mBlock
;
4288 # T15611: if the IP address the user is trying to create an account from is
4289 # blocked with createaccount disabled, prevent new account creation there even
4290 # when the user is logged in
4291 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
4292 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
4294 return $this->mBlockedFromCreateAccount
instanceof Block
4295 && $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
4296 ?
$this->mBlockedFromCreateAccount
4301 * Get whether the user is blocked from using Special:Emailuser.
4304 public function isBlockedFromEmailuser() {
4305 $this->getBlockedStatus();
4306 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
4310 * Get whether the user is allowed to create an account.
4313 public function isAllowedToCreateAccount() {
4314 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
4318 * Get this user's personal page title.
4320 * @return Title User's personal page title
4322 public function getUserPage() {
4323 return Title
::makeTitle( NS_USER
, $this->getName() );
4327 * Get this user's talk page title.
4329 * @return Title User's talk page title
4331 public function getTalkPage() {
4332 $title = $this->getUserPage();
4333 return $title->getTalkPage();
4337 * Determine whether the user is a newbie. Newbies are either
4338 * anonymous IPs, or the most recently created accounts.
4341 public function isNewbie() {
4342 return !$this->isAllowed( 'autoconfirmed' );
4346 * Check to see if the given clear-text password is one of the accepted passwords
4347 * @deprecated since 1.27, use AuthManager instead
4348 * @param string $password User password
4349 * @return bool True if the given password is correct, otherwise False
4351 public function checkPassword( $password ) {
4352 $manager = AuthManager
::singleton();
4353 $reqs = AuthenticationRequest
::loadRequestsFromSubmission(
4354 $manager->getAuthenticationRequests( AuthManager
::ACTION_LOGIN
),
4356 'username' => $this->getName(),
4357 'password' => $password,
4360 $res = AuthManager
::singleton()->beginAuthentication( $reqs, 'null:' );
4361 switch ( $res->status
) {
4362 case AuthenticationResponse
::PASS
:
4364 case AuthenticationResponse
::FAIL
:
4365 // Hope it's not a PreAuthenticationProvider that failed...
4366 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
4367 ->info( __METHOD__
. ': Authentication failed: ' . $res->message
->plain() );
4370 throw new BadMethodCallException(
4371 'AuthManager returned a response unsupported by ' . __METHOD__
4377 * Check if the given clear-text password matches the temporary password
4378 * sent by e-mail for password reset operations.
4380 * @deprecated since 1.27, use AuthManager instead
4381 * @param string $plaintext
4382 * @return bool True if matches, false otherwise
4384 public function checkTemporaryPassword( $plaintext ) {
4385 // Can't check the temporary password individually.
4386 return $this->checkPassword( $plaintext );
4390 * Initialize (if necessary) and return a session token value
4391 * which can be used in edit forms to show that the user's
4392 * login credentials aren't being hijacked with a foreign form
4396 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4397 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4398 * @return MediaWiki\Session\Token The new edit token
4400 public function getEditTokenObject( $salt = '', $request = null ) {
4401 if ( $this->isAnon() ) {
4402 return new LoggedOutEditToken();
4406 $request = $this->getRequest();
4408 return $request->getSession()->getToken( $salt );
4412 * Initialize (if necessary) and return a session token value
4413 * which can be used in edit forms to show that the user's
4414 * login credentials aren't being hijacked with a foreign form
4417 * The $salt for 'edit' and 'csrf' tokens is the default (empty string).
4420 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4421 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4422 * @return string The new edit token
4424 public function getEditToken( $salt = '', $request = null ) {
4425 return $this->getEditTokenObject( $salt, $request )->toString();
4429 * Get the embedded timestamp from a token.
4430 * @deprecated since 1.27, use \MediaWiki\Session\Token::getTimestamp instead.
4431 * @param string $val Input token
4434 public static function getEditTokenTimestamp( $val ) {
4435 wfDeprecated( __METHOD__
, '1.27' );
4436 return MediaWiki\Session\Token
::getTimestamp( $val );
4440 * Check given value against the token value stored in the session.
4441 * A match should confirm that the form was submitted from the
4442 * user's own login session, not a form submission from a third-party
4445 * @param string $val Input value to compare
4446 * @param string $salt Optional function-specific data for hashing
4447 * @param WebRequest|null $request Object to use or null to use $wgRequest
4448 * @param int $maxage Fail tokens older than this, in seconds
4449 * @return bool Whether the token matches
4451 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4452 return $this->getEditTokenObject( $salt, $request )->match( $val, $maxage );
4456 * Check given value against the token value stored in the session,
4457 * ignoring the suffix.
4459 * @param string $val Input value to compare
4460 * @param string $salt Optional function-specific data for hashing
4461 * @param WebRequest|null $request Object to use or null to use $wgRequest
4462 * @param int $maxage Fail tokens older than this, in seconds
4463 * @return bool Whether the token matches
4465 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4466 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . Token
::SUFFIX
;
4467 return $this->matchEditToken( $val, $salt, $request, $maxage );
4471 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4472 * mail to the user's given address.
4474 * @param string $type Message to send, either "created", "changed" or "set"
4477 public function sendConfirmationMail( $type = 'created' ) {
4479 $expiration = null; // gets passed-by-ref and defined in next line.
4480 $token = $this->confirmationToken( $expiration );
4481 $url = $this->confirmationTokenUrl( $token );
4482 $invalidateURL = $this->invalidationTokenUrl( $token );
4483 $this->saveSettings();
4485 if ( $type == 'created' ||
$type === false ) {
4486 $message = 'confirmemail_body';
4487 } elseif ( $type === true ) {
4488 $message = 'confirmemail_body_changed';
4490 // Messages: confirmemail_body_changed, confirmemail_body_set
4491 $message = 'confirmemail_body_' . $type;
4494 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4495 wfMessage( $message,
4496 $this->getRequest()->getIP(),
4499 $wgLang->userTimeAndDate( $expiration, $this ),
4501 $wgLang->userDate( $expiration, $this ),
4502 $wgLang->userTime( $expiration, $this ) )->text() );
4506 * Send an e-mail to this user's account. Does not check for
4507 * confirmed status or validity.
4509 * @param string $subject Message subject
4510 * @param string $body Message body
4511 * @param User|null $from Optional sending user; if unspecified, default
4512 * $wgPasswordSender will be used.
4513 * @param string $replyto Reply-To address
4516 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4517 global $wgPasswordSender;
4519 if ( $from instanceof User
) {
4520 $sender = MailAddress
::newFromUser( $from );
4522 $sender = new MailAddress( $wgPasswordSender,
4523 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4525 $to = MailAddress
::newFromUser( $this );
4527 return UserMailer
::send( $to, $sender, $subject, $body, [
4528 'replyTo' => $replyto,
4533 * Generate, store, and return a new e-mail confirmation code.
4534 * A hash (unsalted, since it's used as a key) is stored.
4536 * @note Call saveSettings() after calling this function to commit
4537 * this change to the database.
4539 * @param string &$expiration Accepts the expiration time
4540 * @return string New token
4542 protected function confirmationToken( &$expiration ) {
4543 global $wgUserEmailConfirmationTokenExpiry;
4545 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4546 $expiration = wfTimestamp( TS_MW
, $expires );
4548 $token = MWCryptRand
::generateHex( 32 );
4549 $hash = md5( $token );
4550 $this->mEmailToken
= $hash;
4551 $this->mEmailTokenExpires
= $expiration;
4556 * Return a URL the user can use to confirm their email address.
4557 * @param string $token Accepts the email confirmation token
4558 * @return string New token URL
4560 protected function confirmationTokenUrl( $token ) {
4561 return $this->getTokenUrl( 'ConfirmEmail', $token );
4565 * Return a URL the user can use to invalidate their email address.
4566 * @param string $token Accepts the email confirmation token
4567 * @return string New token URL
4569 protected function invalidationTokenUrl( $token ) {
4570 return $this->getTokenUrl( 'InvalidateEmail', $token );
4574 * Internal function to format the e-mail validation/invalidation URLs.
4575 * This uses a quickie hack to use the
4576 * hardcoded English names of the Special: pages, for ASCII safety.
4578 * @note Since these URLs get dropped directly into emails, using the
4579 * short English names avoids insanely long URL-encoded links, which
4580 * also sometimes can get corrupted in some browsers/mailers
4581 * (T8957 with Gmail and Internet Explorer).
4583 * @param string $page Special page
4584 * @param string $token Token
4585 * @return string Formatted URL
4587 protected function getTokenUrl( $page, $token ) {
4588 // Hack to bypass localization of 'Special:'
4589 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4590 return $title->getCanonicalURL();
4594 * Mark the e-mail address confirmed.
4596 * @note Call saveSettings() after calling this function to commit the change.
4600 public function confirmEmail() {
4601 // Check if it's already confirmed, so we don't touch the database
4602 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4603 if ( !$this->isEmailConfirmed() ) {
4604 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4605 Hooks
::run( 'ConfirmEmailComplete', [ $this ] );
4611 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4612 * address if it was already confirmed.
4614 * @note Call saveSettings() after calling this function to commit the change.
4615 * @return bool Returns true
4617 public function invalidateEmail() {
4619 $this->mEmailToken
= null;
4620 $this->mEmailTokenExpires
= null;
4621 $this->setEmailAuthenticationTimestamp( null );
4623 Hooks
::run( 'InvalidateEmailComplete', [ $this ] );
4628 * Set the e-mail authentication timestamp.
4629 * @param string $timestamp TS_MW timestamp
4631 public function setEmailAuthenticationTimestamp( $timestamp ) {
4633 $this->mEmailAuthenticated
= $timestamp;
4634 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
4638 * Is this user allowed to send e-mails within limits of current
4639 * site configuration?
4642 public function canSendEmail() {
4643 global $wgEnableEmail, $wgEnableUserEmail;
4644 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4647 $canSend = $this->isEmailConfirmed();
4648 // Avoid PHP 7.1 warning of passing $this by reference
4650 Hooks
::run( 'UserCanSendEmail', [ &$user, &$canSend ] );
4655 * Is this user allowed to receive e-mails within limits of current
4656 * site configuration?
4659 public function canReceiveEmail() {
4660 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4664 * Is this user's e-mail address valid-looking and confirmed within
4665 * limits of the current site configuration?
4667 * @note If $wgEmailAuthentication is on, this may require the user to have
4668 * confirmed their address by returning a code or using a password
4669 * sent to the address from the wiki.
4673 public function isEmailConfirmed() {
4674 global $wgEmailAuthentication;
4676 // Avoid PHP 7.1 warning of passing $this by reference
4679 if ( Hooks
::run( 'EmailConfirmed', [ &$user, &$confirmed ] ) ) {
4680 if ( $this->isAnon() ) {
4683 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4686 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4696 * Check whether there is an outstanding request for e-mail confirmation.
4699 public function isEmailConfirmationPending() {
4700 global $wgEmailAuthentication;
4701 return $wgEmailAuthentication &&
4702 !$this->isEmailConfirmed() &&
4703 $this->mEmailToken
&&
4704 $this->mEmailTokenExpires
> wfTimestamp();
4708 * Get the timestamp of account creation.
4710 * @return string|bool|null Timestamp of account creation, false for
4711 * non-existent/anonymous user accounts, or null if existing account
4712 * but information is not in database.
4714 public function getRegistration() {
4715 if ( $this->isAnon() ) {
4719 return $this->mRegistration
;
4723 * Get the timestamp of the first edit
4725 * @return string|bool Timestamp of first edit, or false for
4726 * non-existent/anonymous user accounts.
4728 public function getFirstEditTimestamp() {
4729 if ( $this->getId() == 0 ) {
4730 return false; // anons
4732 $dbr = wfGetDB( DB_REPLICA
);
4733 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4734 [ 'rev_user' => $this->getId() ],
4736 [ 'ORDER BY' => 'rev_timestamp ASC' ]
4739 return false; // no edits
4741 return wfTimestamp( TS_MW
, $time );
4745 * Get the permissions associated with a given list of groups
4747 * @param array $groups Array of Strings List of internal group names
4748 * @return array Array of Strings List of permission key names for given groups combined
4750 public static function getGroupPermissions( $groups ) {
4751 global $wgGroupPermissions, $wgRevokePermissions;
4753 // grant every granted permission first
4754 foreach ( $groups as $group ) {
4755 if ( isset( $wgGroupPermissions[$group] ) ) {
4756 $rights = array_merge( $rights,
4757 // array_filter removes empty items
4758 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4761 // now revoke the revoked permissions
4762 foreach ( $groups as $group ) {
4763 if ( isset( $wgRevokePermissions[$group] ) ) {
4764 $rights = array_diff( $rights,
4765 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4768 return array_unique( $rights );
4772 * Get all the groups who have a given permission
4774 * @param string $role Role to check
4775 * @return array Array of Strings List of internal group names with the given permission
4777 public static function getGroupsWithPermission( $role ) {
4778 global $wgGroupPermissions;
4779 $allowedGroups = [];
4780 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4781 if ( self
::groupHasPermission( $group, $role ) ) {
4782 $allowedGroups[] = $group;
4785 return $allowedGroups;
4789 * Check, if the given group has the given permission
4791 * If you're wanting to check whether all users have a permission, use
4792 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4796 * @param string $group Group to check
4797 * @param string $role Role to check
4800 public static function groupHasPermission( $group, $role ) {
4801 global $wgGroupPermissions, $wgRevokePermissions;
4802 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4803 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4807 * Check if all users may be assumed to have the given permission
4809 * We generally assume so if the right is granted to '*' and isn't revoked
4810 * on any group. It doesn't attempt to take grants or other extension
4811 * limitations on rights into account in the general case, though, as that
4812 * would require it to always return false and defeat the purpose.
4813 * Specifically, session-based rights restrictions (such as OAuth or bot
4814 * passwords) are applied based on the current session.
4817 * @param string $right Right to check
4820 public static function isEveryoneAllowed( $right ) {
4821 global $wgGroupPermissions, $wgRevokePermissions;
4824 // Use the cached results, except in unit tests which rely on
4825 // being able change the permission mid-request
4826 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4827 return $cache[$right];
4830 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4831 $cache[$right] = false;
4835 // If it's revoked anywhere, then everyone doesn't have it
4836 foreach ( $wgRevokePermissions as $rights ) {
4837 if ( isset( $rights[$right] ) && $rights[$right] ) {
4838 $cache[$right] = false;
4843 // Remove any rights that aren't allowed to the global-session user,
4844 // unless there are no sessions for this endpoint.
4845 if ( !defined( 'MW_NO_SESSION' ) ) {
4846 $allowedRights = SessionManager
::getGlobalSession()->getAllowedUserRights();
4847 if ( $allowedRights !== null && !in_array( $right, $allowedRights, true ) ) {
4848 $cache[$right] = false;
4853 // Allow extensions to say false
4854 if ( !Hooks
::run( 'UserIsEveryoneAllowed', [ $right ] ) ) {
4855 $cache[$right] = false;
4859 $cache[$right] = true;
4864 * Get the localized descriptive name for a group, if it exists
4865 * @deprecated since 1.29 Use UserGroupMembership::getGroupName instead
4867 * @param string $group Internal group name
4868 * @return string Localized descriptive group name
4870 public static function getGroupName( $group ) {
4871 wfDeprecated( __METHOD__
, '1.29' );
4872 return UserGroupMembership
::getGroupName( $group );
4876 * Get the localized descriptive name for a member of a group, if it exists
4877 * @deprecated since 1.29 Use UserGroupMembership::getGroupMemberName instead
4879 * @param string $group Internal group name
4880 * @param string $username Username for gender (since 1.19)
4881 * @return string Localized name for group member
4883 public static function getGroupMember( $group, $username = '#' ) {
4884 wfDeprecated( __METHOD__
, '1.29' );
4885 return UserGroupMembership
::getGroupMemberName( $group, $username );
4889 * Return the set of defined explicit groups.
4890 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4891 * are not included, as they are defined automatically, not in the database.
4892 * @return array Array of internal group names
4894 public static function getAllGroups() {
4895 global $wgGroupPermissions, $wgRevokePermissions;
4897 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4898 self
::getImplicitGroups()
4903 * Get a list of all available permissions.
4904 * @return string[] Array of permission names
4906 public static function getAllRights() {
4907 if ( self
::$mAllRights === false ) {
4908 global $wgAvailableRights;
4909 if ( count( $wgAvailableRights ) ) {
4910 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
4912 self
::$mAllRights = self
::$mCoreRights;
4914 Hooks
::run( 'UserGetAllRights', [ &self
::$mAllRights ] );
4916 return self
::$mAllRights;
4920 * Get a list of implicit groups
4921 * @return array Array of Strings Array of internal group names
4923 public static function getImplicitGroups() {
4924 global $wgImplicitGroups;
4926 $groups = $wgImplicitGroups;
4927 # Deprecated, use $wgImplicitGroups instead
4928 Hooks
::run( 'UserGetImplicitGroups', [ &$groups ], '1.25' );
4934 * Get the title of a page describing a particular group
4935 * @deprecated since 1.29 Use UserGroupMembership::getGroupPage instead
4937 * @param string $group Internal group name
4938 * @return Title|bool Title of the page if it exists, false otherwise
4940 public static function getGroupPage( $group ) {
4941 wfDeprecated( __METHOD__
, '1.29' );
4942 return UserGroupMembership
::getGroupPage( $group );
4946 * Create a link to the group in HTML, if available;
4947 * else return the group name.
4948 * @deprecated since 1.29 Use UserGroupMembership::getLink instead, or
4949 * make the link yourself if you need custom text
4951 * @param string $group Internal name of the group
4952 * @param string $text The text of the link
4953 * @return string HTML link to the group
4955 public static function makeGroupLinkHTML( $group, $text = '' ) {
4956 wfDeprecated( __METHOD__
, '1.29' );
4958 if ( $text == '' ) {
4959 $text = UserGroupMembership
::getGroupName( $group );
4961 $title = UserGroupMembership
::getGroupPage( $group );
4963 return MediaWikiServices
::getInstance()
4964 ->getLinkRenderer()->makeLink( $title, $text );
4966 return htmlspecialchars( $text );
4971 * Create a link to the group in Wikitext, if available;
4972 * else return the group name.
4973 * @deprecated since 1.29 Use UserGroupMembership::getLink instead, or
4974 * make the link yourself if you need custom text
4976 * @param string $group Internal name of the group
4977 * @param string $text The text of the link
4978 * @return string Wikilink to the group
4980 public static function makeGroupLinkWiki( $group, $text = '' ) {
4981 wfDeprecated( __METHOD__
, '1.29' );
4983 if ( $text == '' ) {
4984 $text = UserGroupMembership
::getGroupName( $group );
4986 $title = UserGroupMembership
::getGroupPage( $group );
4988 $page = $title->getFullText();
4989 return "[[$page|$text]]";
4996 * Returns an array of the groups that a particular group can add/remove.
4998 * @param string $group The group to check for whether it can add/remove
4999 * @return array Array( 'add' => array( addablegroups ),
5000 * 'remove' => array( removablegroups ),
5001 * 'add-self' => array( addablegroups to self),
5002 * 'remove-self' => array( removable groups from self) )
5004 public static function changeableByGroup( $group ) {
5005 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
5014 if ( empty( $wgAddGroups[$group] ) ) {
5015 // Don't add anything to $groups
5016 } elseif ( $wgAddGroups[$group] === true ) {
5017 // You get everything
5018 $groups['add'] = self
::getAllGroups();
5019 } elseif ( is_array( $wgAddGroups[$group] ) ) {
5020 $groups['add'] = $wgAddGroups[$group];
5023 // Same thing for remove
5024 if ( empty( $wgRemoveGroups[$group] ) ) {
5026 } elseif ( $wgRemoveGroups[$group] === true ) {
5027 $groups['remove'] = self
::getAllGroups();
5028 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
5029 $groups['remove'] = $wgRemoveGroups[$group];
5032 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
5033 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
5034 foreach ( $wgGroupsAddToSelf as $key => $value ) {
5035 if ( is_int( $key ) ) {
5036 $wgGroupsAddToSelf['user'][] = $value;
5041 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
5042 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
5043 if ( is_int( $key ) ) {
5044 $wgGroupsRemoveFromSelf['user'][] = $value;
5049 // Now figure out what groups the user can add to him/herself
5050 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
5052 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
5053 // No idea WHY this would be used, but it's there
5054 $groups['add-self'] = self
::getAllGroups();
5055 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
5056 $groups['add-self'] = $wgGroupsAddToSelf[$group];
5059 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
5061 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
5062 $groups['remove-self'] = self
::getAllGroups();
5063 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
5064 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
5071 * Returns an array of groups that this user can add and remove
5072 * @return array Array( 'add' => array( addablegroups ),
5073 * 'remove' => array( removablegroups ),
5074 * 'add-self' => array( addablegroups to self),
5075 * 'remove-self' => array( removable groups from self) )
5077 public function changeableGroups() {
5078 if ( $this->isAllowed( 'userrights' ) ) {
5079 // This group gives the right to modify everything (reverse-
5080 // compatibility with old "userrights lets you change
5082 // Using array_merge to make the groups reindexed
5083 $all = array_merge( self
::getAllGroups() );
5092 // Okay, it's not so simple, we will have to go through the arrays
5099 $addergroups = $this->getEffectiveGroups();
5101 foreach ( $addergroups as $addergroup ) {
5102 $groups = array_merge_recursive(
5103 $groups, $this->changeableByGroup( $addergroup )
5105 $groups['add'] = array_unique( $groups['add'] );
5106 $groups['remove'] = array_unique( $groups['remove'] );
5107 $groups['add-self'] = array_unique( $groups['add-self'] );
5108 $groups['remove-self'] = array_unique( $groups['remove-self'] );
5114 * Deferred version of incEditCountImmediate()
5116 * This function, rather than incEditCountImmediate(), should be used for
5117 * most cases as it avoids potential deadlocks caused by concurrent editing.
5119 public function incEditCount() {
5120 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle(
5122 $this->incEditCountImmediate();
5129 * Increment the user's edit-count field.
5130 * Will have no effect for anonymous users.
5133 public function incEditCountImmediate() {
5134 if ( $this->isAnon() ) {
5138 $dbw = wfGetDB( DB_MASTER
);
5139 // No rows will be "affected" if user_editcount is NULL
5142 [ 'user_editcount=user_editcount+1' ],
5143 [ 'user_id' => $this->getId(), 'user_editcount IS NOT NULL' ],
5146 // Lazy initialization check...
5147 if ( $dbw->affectedRows() == 0 ) {
5148 // Now here's a goddamn hack...
5149 $dbr = wfGetDB( DB_REPLICA
);
5150 if ( $dbr !== $dbw ) {
5151 // If we actually have a replica DB server, the count is
5152 // at least one behind because the current transaction
5153 // has not been committed and replicated.
5154 $this->mEditCount
= $this->initEditCount( 1 );
5156 // But if DB_REPLICA is selecting the master, then the
5157 // count we just read includes the revision that was
5158 // just added in the working transaction.
5159 $this->mEditCount
= $this->initEditCount();
5162 if ( $this->mEditCount
=== null ) {
5163 $this->getEditCount();
5164 $dbr = wfGetDB( DB_REPLICA
);
5165 $this->mEditCount +
= ( $dbr !== $dbw ) ?
1 : 0;
5167 $this->mEditCount++
;
5170 // Edit count in user cache too
5171 $this->invalidateCache();
5175 * Initialize user_editcount from data out of the revision table
5177 * @param int $add Edits to add to the count from the revision table
5178 * @return int Number of edits
5180 protected function initEditCount( $add = 0 ) {
5181 // Pull from a replica DB to be less cruel to servers
5182 // Accuracy isn't the point anyway here
5183 $dbr = wfGetDB( DB_REPLICA
);
5184 $count = (int)$dbr->selectField(
5187 [ 'rev_user' => $this->getId() ],
5190 $count = $count +
$add;
5192 $dbw = wfGetDB( DB_MASTER
);
5195 [ 'user_editcount' => $count ],
5196 [ 'user_id' => $this->getId() ],
5204 * Get the description of a given right
5207 * @param string $right Right to query
5208 * @return string Localized description of the right
5210 public static function getRightDescription( $right ) {
5211 $key = "right-$right";
5212 $msg = wfMessage( $key );
5213 return $msg->isDisabled() ?
$right : $msg->text();
5217 * Get the name of a given grant
5220 * @param string $grant Grant to query
5221 * @return string Localized name of the grant
5223 public static function getGrantName( $grant ) {
5224 $key = "grant-$grant";
5225 $msg = wfMessage( $key );
5226 return $msg->isDisabled() ?
$grant : $msg->text();
5230 * Add a newuser log entry for this user.
5231 * Before 1.19 the return value was always true.
5233 * @deprecated since 1.27, AuthManager handles logging
5234 * @param string|bool $action Account creation type.
5235 * - String, one of the following values:
5236 * - 'create' for an anonymous user creating an account for himself.
5237 * This will force the action's performer to be the created user itself,
5238 * no matter the value of $wgUser
5239 * - 'create2' for a logged in user creating an account for someone else
5240 * - 'byemail' when the created user will receive its password by e-mail
5241 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
5242 * - Boolean means whether the account was created by e-mail (deprecated):
5243 * - true will be converted to 'byemail'
5244 * - false will be converted to 'create' if this object is the same as
5245 * $wgUser and to 'create2' otherwise
5246 * @param string $reason User supplied reason
5249 public function addNewUserLogEntry( $action = false, $reason = '' ) {
5250 return true; // disabled
5254 * Add an autocreate newuser log entry for this user
5255 * Used by things like CentralAuth and perhaps other authplugins.
5256 * Consider calling addNewUserLogEntry() directly instead.
5258 * @deprecated since 1.27, AuthManager handles logging
5261 public function addNewUserLogEntryAutoCreate() {
5262 $this->addNewUserLogEntry( 'autocreate' );
5268 * Load the user options either from cache, the database or an array
5270 * @param array $data Rows for the current user out of the user_properties table
5272 protected function loadOptions( $data = null ) {
5277 if ( $this->mOptionsLoaded
) {
5281 $this->mOptions
= self
::getDefaultOptions();
5283 if ( !$this->getId() ) {
5284 // For unlogged-in users, load language/variant options from request.
5285 // There's no need to do it for logged-in users: they can set preferences,
5286 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5287 // so don't override user's choice (especially when the user chooses site default).
5288 $variant = $wgContLang->getDefaultVariant();
5289 $this->mOptions
['variant'] = $variant;
5290 $this->mOptions
['language'] = $variant;
5291 $this->mOptionsLoaded
= true;
5295 // Maybe load from the object
5296 if ( !is_null( $this->mOptionOverrides
) ) {
5297 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5298 foreach ( $this->mOptionOverrides
as $key => $value ) {
5299 $this->mOptions
[$key] = $value;
5302 if ( !is_array( $data ) ) {
5303 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5304 // Load from database
5305 $dbr = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
5306 ?
wfGetDB( DB_MASTER
)
5307 : wfGetDB( DB_REPLICA
);
5309 $res = $dbr->select(
5311 [ 'up_property', 'up_value' ],
5312 [ 'up_user' => $this->getId() ],
5316 $this->mOptionOverrides
= [];
5318 foreach ( $res as $row ) {
5319 // Convert '0' to 0. PHP's boolean conversion considers them both
5320 // false, but e.g. JavaScript considers the former as true.
5321 // @todo: T54542 Somehow determine the desired type (string/int/bool)
5322 // and convert all values here.
5323 if ( $row->up_value
=== '0' ) {
5326 $data[$row->up_property
] = $row->up_value
;
5330 // Convert the email blacklist from a new line delimited string
5331 // to an array of ids.
5332 if ( isset( $data['email-blacklist'] ) && $data['email-blacklist'] ) {
5333 $data['email-blacklist'] = array_map( 'intval', explode( "\n", $data['email-blacklist'] ) );
5336 foreach ( $data as $property => $value ) {
5337 $this->mOptionOverrides
[$property] = $value;
5338 $this->mOptions
[$property] = $value;
5342 $this->mOptionsLoaded
= true;
5344 Hooks
::run( 'UserLoadOptions', [ $this, &$this->mOptions
] );
5348 * Saves the non-default options for this user, as previously set e.g. via
5349 * setOption(), in the database's "user_properties" (preferences) table.
5350 * Usually used via saveSettings().
5352 protected function saveOptions() {
5353 $this->loadOptions();
5355 // Not using getOptions(), to keep hidden preferences in database
5356 $saveOptions = $this->mOptions
;
5358 // Convert usernames to ids.
5359 if ( isset( $this->mOptions
['email-blacklist'] ) ) {
5360 if ( $this->mOptions
['email-blacklist'] ) {
5361 $value = $this->mOptions
['email-blacklist'];
5362 // Email Blacklist may be an array of ids or a string of new line
5363 // delimnated user names.
5364 if ( is_array( $value ) ) {
5365 $ids = array_filter( $value, 'is_numeric' );
5367 $lookup = CentralIdLookup
::factory();
5368 $ids = $lookup->centralIdsFromNames( explode( "\n", $value ), $this );
5370 $this->mOptions
['email-blacklist'] = $ids;
5371 $saveOptions['email-blacklist'] = implode( "\n", $this->mOptions
['email-blacklist'] );
5373 // If the blacklist is empty, set it to null rather than an empty string.
5374 $this->mOptions
['email-blacklist'] = null;
5378 // Allow hooks to abort, for instance to save to a global profile.
5379 // Reset options to default state before saving.
5380 if ( !Hooks
::run( 'UserSaveOptions', [ $this, &$saveOptions ] ) ) {
5384 $userId = $this->getId();
5386 $insert_rows = []; // all the new preference rows
5387 foreach ( $saveOptions as $key => $value ) {
5388 // Don't bother storing default values
5389 $defaultOption = self
::getDefaultOption( $key );
5390 if ( ( $defaultOption === null && $value !== false && $value !== null )
5391 ||
$value != $defaultOption
5394 'up_user' => $userId,
5395 'up_property' => $key,
5396 'up_value' => $value,
5401 $dbw = wfGetDB( DB_MASTER
);
5403 $res = $dbw->select( 'user_properties',
5404 [ 'up_property', 'up_value' ], [ 'up_user' => $userId ], __METHOD__
);
5406 // Find prior rows that need to be removed or updated. These rows will
5407 // all be deleted (the latter so that INSERT IGNORE applies the new values).
5409 foreach ( $res as $row ) {
5410 if ( !isset( $saveOptions[$row->up_property
] )
5411 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
5413 $keysDelete[] = $row->up_property
;
5417 if ( count( $keysDelete ) ) {
5418 // Do the DELETE by PRIMARY KEY for prior rows.
5419 // In the past a very large portion of calls to this function are for setting
5420 // 'rememberpassword' for new accounts (a preference that has since been removed).
5421 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5422 // caused gap locks on [max user ID,+infinity) which caused high contention since
5423 // updates would pile up on each other as they are for higher (newer) user IDs.
5424 // It might not be necessary these days, but it shouldn't hurt either.
5425 $dbw->delete( 'user_properties',
5426 [ 'up_user' => $userId, 'up_property' => $keysDelete ], __METHOD__
);
5428 // Insert the new preference rows
5429 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, [ 'IGNORE' ] );
5433 * Lazily instantiate and return a factory object for making passwords
5435 * @deprecated since 1.27, create a PasswordFactory directly instead
5436 * @return PasswordFactory
5438 public static function getPasswordFactory() {
5439 wfDeprecated( __METHOD__
, '1.27' );
5440 $ret = new PasswordFactory();
5441 $ret->init( RequestContext
::getMain()->getConfig() );
5446 * Provide an array of HTML5 attributes to put on an input element
5447 * intended for the user to enter a new password. This may include
5448 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
5450 * Do *not* use this when asking the user to enter his current password!
5451 * Regardless of configuration, users may have invalid passwords for whatever
5452 * reason (e.g., they were set before requirements were tightened up).
5453 * Only use it when asking for a new password, like on account creation or
5456 * Obviously, you still need to do server-side checking.
5458 * NOTE: A combination of bugs in various browsers means that this function
5459 * actually just returns array() unconditionally at the moment. May as
5460 * well keep it around for when the browser bugs get fixed, though.
5462 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
5464 * @deprecated since 1.27
5465 * @return array Array of HTML attributes suitable for feeding to
5466 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
5467 * That will get confused by the boolean attribute syntax used.)
5469 public static function passwordChangeInputAttribs() {
5470 global $wgMinimalPasswordLength;
5472 if ( $wgMinimalPasswordLength == 0 ) {
5476 # Note that the pattern requirement will always be satisfied if the
5477 # input is empty, so we need required in all cases.
5479 # @todo FIXME: T25769: This needs to not claim the password is required
5480 # if e-mail confirmation is being used. Since HTML5 input validation
5481 # is b0rked anyway in some browsers, just return nothing. When it's
5482 # re-enabled, fix this code to not output required for e-mail
5484 # $ret = array( 'required' );
5487 # We can't actually do this right now, because Opera 9.6 will print out
5488 # the entered password visibly in its error message! When other
5489 # browsers add support for this attribute, or Opera fixes its support,
5490 # we can add support with a version check to avoid doing this on Opera
5491 # versions where it will be a problem. Reported to Opera as
5492 # DSK-262266, but they don't have a public bug tracker for us to follow.
5494 if ( $wgMinimalPasswordLength > 1 ) {
5495 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
5496 $ret['title'] = wfMessage( 'passwordtooshort' )
5497 ->numParams( $wgMinimalPasswordLength )->text();
5505 * Return the list of user fields that should be selected to create
5506 * a new user object.
5507 * @deprecated since 1.31, use self::getQueryInfo() instead.
5510 public static function selectFields() {
5518 'user_email_authenticated',
5520 'user_email_token_expires',
5521 'user_registration',
5527 * Return the tables, fields, and join conditions to be selected to create
5528 * a new user object.
5530 * @return array With three keys:
5531 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
5532 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
5533 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
5535 public static function getQueryInfo() {
5537 'tables' => [ 'user' ],
5545 'user_email_authenticated',
5547 'user_email_token_expires',
5548 'user_registration',
5556 * Factory function for fatal permission-denied errors
5559 * @param string $permission User right required
5562 static function newFatalPermissionDeniedStatus( $permission ) {
5566 foreach ( self
::getGroupsWithPermission( $permission ) as $group ) {
5567 $groups[] = UserGroupMembership
::getLink( $group, RequestContext
::getMain(), 'wiki' );
5571 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5573 return Status
::newFatal( 'badaccess-group0' );
5578 * Get a new instance of this user that was loaded from the master via a locking read
5580 * Use this instead of the main context User when updating that user. This avoids races
5581 * where that user was loaded from a replica DB or even the master but without proper locks.
5583 * @return User|null Returns null if the user was not found in the DB
5586 public function getInstanceForUpdate() {
5587 if ( !$this->getId() ) {
5588 return null; // anon
5591 $user = self
::newFromId( $this->getId() );
5592 if ( !$user->loadFromId( self
::READ_EXCLUSIVE
) ) {
5600 * Checks if two user objects point to the same user.
5606 public function equals( User
$user ) {
5607 return $this->getName() === $user->getName();