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 integer 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 integer $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 integer $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
453 * @param integer $userId
455 public static function purge( $wikiId, $userId ) {
456 $cache = ObjectCache
::getMainWANInstance();
457 $key = $cache->makeGlobalKey( 'user', 'id', $wikiId, $userId );
458 $cache->delete( $key );
463 * @param WANObjectCache $cache
466 protected function getCacheKey( WANObjectCache
$cache ) {
467 return $cache->makeGlobalKey( 'user', 'id', wfWikiID(), $this->mId
);
471 * @param WANObjectCache $cache
475 public function getMutableCacheKeys( WANObjectCache
$cache ) {
476 $id = $this->getId();
478 return $id ?
[ $this->getCacheKey( $cache ) ] : [];
482 * Load user data from shared cache, given mId has already been set.
487 protected function loadFromCache() {
488 $cache = ObjectCache
::getMainWANInstance();
489 $data = $cache->getWithSetCallback(
490 $this->getCacheKey( $cache ),
492 function ( $oldValue, &$ttl, array &$setOpts ) use ( $cache ) {
493 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
494 wfDebug( "User: cache miss for user {$this->mId}\n" );
496 $this->loadFromDatabase( self
::READ_NORMAL
);
498 $this->loadOptions();
501 foreach ( self
::$mCacheVars as $name ) {
502 $data[$name] = $this->$name;
505 $ttl = $cache->adaptiveTTL( wfTimestamp( TS_UNIX
, $this->mTouched
), $ttl );
507 // if a user group membership is about to expire, the cache needs to
508 // expire at that time (T163691)
509 foreach ( $this->mGroupMemberships
as $ugm ) {
510 if ( $ugm->getExpiry() ) {
511 $secondsUntilExpiry = wfTimestamp( TS_UNIX
, $ugm->getExpiry() ) - time();
512 if ( $secondsUntilExpiry > 0 && $secondsUntilExpiry < $ttl ) {
513 $ttl = $secondsUntilExpiry;
520 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'version' => self
::VERSION
]
523 // Restore from cache
524 foreach ( self
::$mCacheVars as $name ) {
525 $this->$name = $data[$name];
531 /** @name newFrom*() static factory methods */
535 * Static factory method for creation from username.
537 * This is slightly less efficient than newFromId(), so use newFromId() if
538 * you have both an ID and a name handy.
540 * @param string $name Username, validated by Title::newFromText()
541 * @param string|bool $validate Validate username. Takes the same parameters as
542 * User::getCanonicalName(), except that true is accepted as an alias
543 * for 'valid', for BC.
545 * @return User|bool User object, or false if the username is invalid
546 * (e.g. if it contains illegal characters or is an IP address). If the
547 * username is not present in the database, the result will be a user object
548 * with a name, zero user ID and default settings.
550 public static function newFromName( $name, $validate = 'valid' ) {
551 if ( $validate === true ) {
554 $name = self
::getCanonicalName( $name, $validate );
555 if ( $name === false ) {
558 // Create unloaded user object
562 $u->setItemLoaded( 'name' );
568 * Static factory method for creation from a given user ID.
570 * @param int $id Valid user ID
571 * @return User The corresponding User object
573 public static function newFromId( $id ) {
577 $u->setItemLoaded( 'id' );
582 * Factory method to fetch whichever user has a given email confirmation code.
583 * This code is generated when an account is created or its e-mail address
586 * If the code is invalid or has expired, returns NULL.
588 * @param string $code Confirmation code
589 * @param int $flags User::READ_* bitfield
592 public static function newFromConfirmationCode( $code, $flags = 0 ) {
593 $db = ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
594 ?
wfGetDB( DB_MASTER
)
595 : wfGetDB( DB_REPLICA
);
597 $id = $db->selectField(
601 'user_email_token' => md5( $code ),
602 'user_email_token_expires > ' . $db->addQuotes( $db->timestamp() ),
606 return $id ? self
::newFromId( $id ) : null;
610 * Create a new user object using data from session. If the login
611 * credentials are invalid, the result is an anonymous user.
613 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
616 public static function newFromSession( WebRequest
$request = null ) {
618 $user->mFrom
= 'session';
619 $user->mRequest
= $request;
624 * Create a new user object from a user row.
625 * The row should have the following fields from the user table in it:
626 * - either user_name or user_id to load further data if needed (or both)
628 * - all other fields (email, etc.)
629 * It is useless to provide the remaining fields if either user_id,
630 * user_name and user_real_name are not provided because the whole row
631 * will be loaded once more from the database when accessing them.
633 * @param stdClass $row A row from the user table
634 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
637 public static function newFromRow( $row, $data = null ) {
639 $user->loadFromRow( $row, $data );
644 * Static factory method for creation of a "system" user from username.
646 * A "system" user is an account that's used to attribute logged actions
647 * taken by MediaWiki itself, as opposed to a bot or human user. Examples
648 * might include the 'Maintenance script' or 'Conversion script' accounts
649 * used by various scripts in the maintenance/ directory or accounts such
650 * as 'MediaWiki message delivery' used by the MassMessage extension.
652 * This can optionally create the user if it doesn't exist, and "steal" the
653 * account if it does exist.
655 * "Stealing" an existing user is intended to make it impossible for normal
656 * authentication processes to use the account, effectively disabling the
657 * account for normal use:
658 * - Email is invalidated, to prevent account recovery by emailing a
659 * temporary password and to disassociate the account from the existing
661 * - The token is set to a magic invalid value, to kill existing sessions
662 * and to prevent $this->setToken() calls from resetting the token to a
664 * - SessionManager is instructed to prevent new sessions for the user, to
665 * do things like deauthorizing OAuth consumers.
666 * - AuthManager is instructed to revoke access, to invalidate or remove
667 * passwords and other credentials.
669 * @param string $name Username
670 * @param array $options Options are:
671 * - validate: As for User::getCanonicalName(), default 'valid'
672 * - create: Whether to create the user if it doesn't already exist, default true
673 * - steal: Whether to "disable" the account for normal use if it already
674 * exists, default false
678 public static function newSystemUser( $name, $options = [] ) {
680 'validate' => 'valid',
685 $name = self
::getCanonicalName( $name, $options['validate'] );
686 if ( $name === false ) {
690 $dbr = wfGetDB( DB_REPLICA
);
691 $row = $dbr->selectRow(
693 self
::selectFields(),
694 [ 'user_name' => $name ],
698 // Try the master database...
699 $dbw = wfGetDB( DB_MASTER
);
700 $row = $dbw->selectRow(
702 self
::selectFields(),
703 [ 'user_name' => $name ],
709 // No user. Create it?
710 return $options['create']
711 ? self
::createNew( $name, [ 'token' => self
::INVALID_TOKEN
] )
715 $user = self
::newFromRow( $row );
717 // A user is considered to exist as a non-system user if it can
718 // authenticate, or has an email set, or has a non-invalid token.
719 if ( $user->mEmail ||
$user->mToken
!== self
::INVALID_TOKEN ||
720 AuthManager
::singleton()->userCanAuthenticate( $name )
722 // User exists. Steal it?
723 if ( !$options['steal'] ) {
727 AuthManager
::singleton()->revokeAccessForUser( $name );
729 $user->invalidateEmail();
730 $user->mToken
= self
::INVALID_TOKEN
;
731 $user->saveSettings();
732 SessionManager
::singleton()->preventSessionsForUser( $user->getName() );
741 * Get the username corresponding to a given user ID
742 * @param int $id User ID
743 * @return string|bool The corresponding username
745 public static function whoIs( $id ) {
746 return UserCache
::singleton()->getProp( $id, 'name' );
750 * Get the real name of a user given their user ID
752 * @param int $id User ID
753 * @return string|bool The corresponding user's real name
755 public static function whoIsReal( $id ) {
756 return UserCache
::singleton()->getProp( $id, 'real_name' );
760 * Get database id given a user name
761 * @param string $name Username
762 * @param integer $flags User::READ_* constant bitfield
763 * @return int|null The corresponding user's ID, or null if user is nonexistent
765 public static function idFromName( $name, $flags = self
::READ_NORMAL
) {
766 $nt = Title
::makeTitleSafe( NS_USER
, $name );
767 if ( is_null( $nt ) ) {
772 if ( !( $flags & self
::READ_LATEST
) && isset( self
::$idCacheByName[$name] ) ) {
773 return self
::$idCacheByName[$name];
776 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
777 $db = wfGetDB( $index );
782 [ 'user_name' => $nt->getText() ],
787 if ( $s === false ) {
790 $result = $s->user_id
;
793 self
::$idCacheByName[$name] = $result;
795 if ( count( self
::$idCacheByName ) > 1000 ) {
796 self
::$idCacheByName = [];
803 * Reset the cache used in idFromName(). For use in tests.
805 public static function resetIdByNameCache() {
806 self
::$idCacheByName = [];
810 * Does the string match an anonymous IP address?
812 * This function exists for username validation, in order to reject
813 * usernames which are similar in form to IP addresses. Strings such
814 * as 300.300.300.300 will return true because it looks like an IP
815 * address, despite not being strictly valid.
817 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
818 * address because the usemod software would "cloak" anonymous IP
819 * addresses like this, if we allowed accounts like this to be created
820 * new users could get the old edits of these anonymous users.
822 * @param string $name Name to match
825 public static function isIP( $name ) {
826 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
827 || IP
::isIPv6( $name );
831 * Is the input a valid username?
833 * Checks if the input is a valid username, we don't want an empty string,
834 * an IP address, anything that contains slashes (would mess up subpages),
835 * is longer than the maximum allowed username size or doesn't begin with
838 * @param string $name Name to match
841 public static function isValidUserName( $name ) {
842 global $wgContLang, $wgMaxNameChars;
845 || self
::isIP( $name )
846 ||
strpos( $name, '/' ) !== false
847 ||
strlen( $name ) > $wgMaxNameChars
848 ||
$name != $wgContLang->ucfirst( $name )
853 // Ensure that the name can't be misresolved as a different title,
854 // such as with extra namespace keys at the start.
855 $parsed = Title
::newFromText( $name );
856 if ( is_null( $parsed )
857 ||
$parsed->getNamespace()
858 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
862 // Check an additional blacklist of troublemaker characters.
863 // Should these be merged into the title char list?
864 $unicodeBlacklist = '/[' .
865 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
866 '\x{00a0}' . # non-breaking space
867 '\x{2000}-\x{200f}' . # various whitespace
868 '\x{2028}-\x{202f}' . # breaks and control chars
869 '\x{3000}' . # ideographic space
870 '\x{e000}-\x{f8ff}' . # private use
872 if ( preg_match( $unicodeBlacklist, $name ) ) {
880 * Usernames which fail to pass this function will be blocked
881 * from user login and new account registrations, but may be used
882 * internally by batch processes.
884 * If an account already exists in this form, login will be blocked
885 * by a failure to pass this function.
887 * @param string $name Name to match
890 public static function isUsableName( $name ) {
891 global $wgReservedUsernames;
892 // Must be a valid username, obviously ;)
893 if ( !self
::isValidUserName( $name ) ) {
897 static $reservedUsernames = false;
898 if ( !$reservedUsernames ) {
899 $reservedUsernames = $wgReservedUsernames;
900 Hooks
::run( 'UserGetReservedNames', [ &$reservedUsernames ] );
903 // Certain names may be reserved for batch processes.
904 foreach ( $reservedUsernames as $reserved ) {
905 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
906 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
908 if ( $reserved == $name ) {
916 * Return the users who are members of the given group(s). In case of multiple groups,
917 * users who are members of at least one of them are returned.
919 * @param string|array $groups A single group name or an array of group names
920 * @param int $limit Max number of users to return. The actual limit will never exceed 5000
921 * records; larger values are ignored.
922 * @param int $after ID the user to start after
923 * @return UserArrayFromResult
925 public static function findUsersByGroup( $groups, $limit = 5000, $after = null ) {
926 if ( $groups === [] ) {
927 return UserArrayFromResult
::newFromIDs( [] );
930 $groups = array_unique( (array)$groups );
931 $limit = min( 5000, $limit );
933 $conds = [ 'ug_group' => $groups ];
934 if ( $after !== null ) {
935 $conds[] = 'ug_user > ' . (int)$after;
938 $dbr = wfGetDB( DB_REPLICA
);
939 $ids = $dbr->selectFieldValues(
946 'ORDER BY' => 'ug_user',
950 return UserArray
::newFromIDs( $ids );
954 * Usernames which fail to pass this function will be blocked
955 * from new account registrations, but may be used internally
956 * either by batch processes or by user accounts which have
957 * already been created.
959 * Additional blacklisting may be added here rather than in
960 * isValidUserName() to avoid disrupting existing accounts.
962 * @param string $name String to match
965 public static function isCreatableName( $name ) {
966 global $wgInvalidUsernameCharacters;
968 // Ensure that the username isn't longer than 235 bytes, so that
969 // (at least for the builtin skins) user javascript and css files
970 // will work. (T25080)
971 if ( strlen( $name ) > 235 ) {
972 wfDebugLog( 'username', __METHOD__
.
973 ": '$name' invalid due to length" );
977 // Preg yells if you try to give it an empty string
978 if ( $wgInvalidUsernameCharacters !== '' ) {
979 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
980 wfDebugLog( 'username', __METHOD__
.
981 ": '$name' invalid due to wgInvalidUsernameCharacters" );
986 return self
::isUsableName( $name );
990 * Is the input a valid password for this user?
992 * @param string $password Desired password
995 public function isValidPassword( $password ) {
996 // simple boolean wrapper for getPasswordValidity
997 return $this->getPasswordValidity( $password ) === true;
1001 * Given unvalidated password input, return error message on failure.
1003 * @param string $password Desired password
1004 * @return bool|string|array True on success, string or array of error message on failure
1006 public function getPasswordValidity( $password ) {
1007 $result = $this->checkPasswordValidity( $password );
1008 if ( $result->isGood() ) {
1012 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
1013 $messages[] = $error['message'];
1015 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
1016 $messages[] = $warning['message'];
1018 if ( count( $messages ) === 1 ) {
1019 return $messages[0];
1026 * Check if this is a valid password for this user
1028 * Create a Status object based on the password's validity.
1029 * The Status should be set to fatal if the user should not
1030 * be allowed to log in, and should have any errors that
1031 * would block changing the password.
1033 * If the return value of this is not OK, the password
1034 * should not be checked. If the return value is not Good,
1035 * the password can be checked, but the user should not be
1036 * able to set their password to this.
1038 * @param string $password Desired password
1042 public function checkPasswordValidity( $password ) {
1043 global $wgPasswordPolicy;
1045 $upp = new UserPasswordPolicy(
1046 $wgPasswordPolicy['policies'],
1047 $wgPasswordPolicy['checks']
1050 $status = Status
::newGood();
1051 $result = false; // init $result to false for the internal checks
1053 if ( !Hooks
::run( 'isValidPassword', [ $password, &$result, $this ] ) ) {
1054 $status->error( $result );
1058 if ( $result === false ) {
1059 $status->merge( $upp->checkUserPassword( $this, $password ) );
1061 } elseif ( $result === true ) {
1064 $status->error( $result );
1065 return $status; // the isValidPassword hook set a string $result and returned true
1070 * Given unvalidated user input, return a canonical username, or false if
1071 * the username is invalid.
1072 * @param string $name User input
1073 * @param string|bool $validate Type of validation to use:
1074 * - false No validation
1075 * - 'valid' Valid for batch processes
1076 * - 'usable' Valid for batch processes and login
1077 * - 'creatable' Valid for batch processes, login and account creation
1079 * @throws InvalidArgumentException
1080 * @return bool|string
1082 public static function getCanonicalName( $name, $validate = 'valid' ) {
1083 // Force usernames to capital
1085 $name = $wgContLang->ucfirst( $name );
1087 # Reject names containing '#'; these will be cleaned up
1088 # with title normalisation, but then it's too late to
1090 if ( strpos( $name, '#' ) !== false ) {
1094 // Clean up name according to title rules,
1095 // but only when validation is requested (T14654)
1096 $t = ( $validate !== false ) ?
1097 Title
::newFromText( $name, NS_USER
) : Title
::makeTitle( NS_USER
, $name );
1098 // Check for invalid titles
1099 if ( is_null( $t ) ||
$t->getNamespace() !== NS_USER ||
$t->isExternal() ) {
1103 // Reject various classes of invalid names
1104 $name = AuthManager
::callLegacyAuthPlugin(
1105 'getCanonicalName', [ $t->getText() ], $t->getText()
1108 switch ( $validate ) {
1112 if ( !self
::isValidUserName( $name ) ) {
1117 if ( !self
::isUsableName( $name ) ) {
1122 if ( !self
::isCreatableName( $name ) ) {
1127 throw new InvalidArgumentException(
1128 'Invalid parameter value for $validate in ' . __METHOD__
);
1134 * Return a random password.
1136 * @deprecated since 1.27, use PasswordFactory::generateRandomPasswordString()
1137 * @return string New random password
1139 public static function randomPassword() {
1140 global $wgMinimalPasswordLength;
1141 return PasswordFactory
::generateRandomPasswordString( $wgMinimalPasswordLength );
1145 * Set cached properties to default.
1147 * @note This no longer clears uncached lazy-initialised properties;
1148 * the constructor does that instead.
1150 * @param string|bool $name
1152 public function loadDefaults( $name = false ) {
1154 $this->mName
= $name;
1155 $this->mRealName
= '';
1157 $this->mOptionOverrides
= null;
1158 $this->mOptionsLoaded
= false;
1160 $loggedOut = $this->mRequest
&& !defined( 'MW_NO_SESSION' )
1161 ?
$this->mRequest
->getSession()->getLoggedOutTimestamp() : 0;
1162 if ( $loggedOut !== 0 ) {
1163 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1165 $this->mTouched
= '1'; # Allow any pages to be cached
1168 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1169 $this->mEmailAuthenticated
= null;
1170 $this->mEmailToken
= '';
1171 $this->mEmailTokenExpires
= null;
1172 $this->mRegistration
= wfTimestamp( TS_MW
);
1173 $this->mGroupMemberships
= [];
1175 Hooks
::run( 'UserLoadDefaults', [ $this, $name ] );
1179 * Return whether an item has been loaded.
1181 * @param string $item Item to check. Current possibilities:
1185 * @param string $all 'all' to check if the whole object has been loaded
1186 * or any other string to check if only the item is available (e.g.
1190 public function isItemLoaded( $item, $all = 'all' ) {
1191 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1192 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1196 * Set that an item has been loaded
1198 * @param string $item
1200 protected function setItemLoaded( $item ) {
1201 if ( is_array( $this->mLoadedItems
) ) {
1202 $this->mLoadedItems
[$item] = true;
1207 * Load user data from the session.
1209 * @return bool True if the user is logged in, false otherwise.
1211 private function loadFromSession() {
1214 Hooks
::run( 'UserLoadFromSession', [ $this, &$result ], '1.27' );
1215 if ( $result !== null ) {
1219 // MediaWiki\Session\Session already did the necessary authentication of the user
1220 // returned here, so just use it if applicable.
1221 $session = $this->getRequest()->getSession();
1222 $user = $session->getUser();
1223 if ( $user->isLoggedIn() ) {
1224 $this->loadFromUserObject( $user );
1226 // If this user is autoblocked, set a cookie to track the Block. This has to be done on
1227 // every session load, because an autoblocked editor might not edit again from the same
1228 // IP address after being blocked.
1229 $config = RequestContext
::getMain()->getConfig();
1230 if ( $config->get( 'CookieSetOnAutoblock' ) === true ) {
1231 $block = $this->getBlock();
1232 $shouldSetCookie = $this->getRequest()->getCookie( 'BlockID' ) === null
1234 && $block->getType() === Block
::TYPE_USER
1235 && $block->isAutoblocking();
1236 if ( $shouldSetCookie ) {
1237 wfDebug( __METHOD__
. ': User is autoblocked, setting cookie to track' );
1238 $block->setCookie( $this->getRequest()->response() );
1242 // Other code expects these to be set in the session, so set them.
1243 $session->set( 'wsUserID', $this->getId() );
1244 $session->set( 'wsUserName', $this->getName() );
1245 $session->set( 'wsToken', $this->getToken() );
1252 * Load user and user_group data from the database.
1253 * $this->mId must be set, this is how the user is identified.
1255 * @param integer $flags User::READ_* constant bitfield
1256 * @return bool True if the user exists, false if the user is anonymous
1258 public function loadFromDatabase( $flags = self
::READ_LATEST
) {
1260 $this->mId
= intval( $this->mId
);
1262 if ( !$this->mId
) {
1263 // Anonymous users are not in the database
1264 $this->loadDefaults();
1268 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
1269 $db = wfGetDB( $index );
1271 $s = $db->selectRow(
1273 self
::selectFields(),
1274 [ 'user_id' => $this->mId
],
1279 $this->queryFlagsUsed
= $flags;
1280 Hooks
::run( 'UserLoadFromDatabase', [ $this, &$s ] );
1282 if ( $s !== false ) {
1283 // Initialise user table data
1284 $this->loadFromRow( $s );
1285 $this->mGroupMemberships
= null; // deferred
1286 $this->getEditCount(); // revalidation for nulls
1291 $this->loadDefaults();
1297 * Initialize this object from a row from the user table.
1299 * @param stdClass $row Row from the user table to load.
1300 * @param array $data Further user data to load into the object
1302 * user_groups Array of arrays or stdClass result rows out of the user_groups
1303 * table. Previously you were supposed to pass an array of strings
1304 * here, but we also need expiry info nowadays, so an array of
1305 * strings is ignored.
1306 * user_properties Array with properties out of the user_properties table
1308 protected function loadFromRow( $row, $data = null ) {
1311 $this->mGroupMemberships
= null; // deferred
1313 if ( isset( $row->user_name
) ) {
1314 $this->mName
= $row->user_name
;
1315 $this->mFrom
= 'name';
1316 $this->setItemLoaded( 'name' );
1321 if ( isset( $row->user_real_name
) ) {
1322 $this->mRealName
= $row->user_real_name
;
1323 $this->setItemLoaded( 'realname' );
1328 if ( isset( $row->user_id
) ) {
1329 $this->mId
= intval( $row->user_id
);
1330 $this->mFrom
= 'id';
1331 $this->setItemLoaded( 'id' );
1336 if ( isset( $row->user_id
) && isset( $row->user_name
) ) {
1337 self
::$idCacheByName[$row->user_name
] = $row->user_id
;
1340 if ( isset( $row->user_editcount
) ) {
1341 $this->mEditCount
= $row->user_editcount
;
1346 if ( isset( $row->user_touched
) ) {
1347 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1352 if ( isset( $row->user_token
) ) {
1353 // The definition for the column is binary(32), so trim the NULs
1354 // that appends. The previous definition was char(32), so trim
1356 $this->mToken
= rtrim( $row->user_token
, " \0" );
1357 if ( $this->mToken
=== '' ) {
1358 $this->mToken
= null;
1364 if ( isset( $row->user_email
) ) {
1365 $this->mEmail
= $row->user_email
;
1366 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1367 $this->mEmailToken
= $row->user_email_token
;
1368 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1369 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1375 $this->mLoadedItems
= true;
1378 if ( is_array( $data ) ) {
1379 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1380 if ( !count( $data['user_groups'] ) ) {
1381 $this->mGroupMemberships
= [];
1383 $firstGroup = reset( $data['user_groups'] );
1384 if ( is_array( $firstGroup ) ||
is_object( $firstGroup ) ) {
1385 $this->mGroupMemberships
= [];
1386 foreach ( $data['user_groups'] as $row ) {
1387 $ugm = UserGroupMembership
::newFromRow( (object)$row );
1388 $this->mGroupMemberships
[$ugm->getGroup()] = $ugm;
1393 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1394 $this->loadOptions( $data['user_properties'] );
1400 * Load the data for this user object from another user object.
1404 protected function loadFromUserObject( $user ) {
1406 foreach ( self
::$mCacheVars as $var ) {
1407 $this->$var = $user->$var;
1412 * Load the groups from the database if they aren't already loaded.
1414 private function loadGroups() {
1415 if ( is_null( $this->mGroupMemberships
) ) {
1416 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
1417 ?
wfGetDB( DB_MASTER
)
1418 : wfGetDB( DB_REPLICA
);
1419 $this->mGroupMemberships
= UserGroupMembership
::getMembershipsForUser(
1425 * Add the user to the group if he/she meets given criteria.
1427 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1428 * possible to remove manually via Special:UserRights. In such case it
1429 * will not be re-added automatically. The user will also not lose the
1430 * group if they no longer meet the criteria.
1432 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1434 * @return array Array of groups the user has been promoted to.
1436 * @see $wgAutopromoteOnce
1438 public function addAutopromoteOnceGroups( $event ) {
1439 global $wgAutopromoteOnceLogInRC;
1441 if ( wfReadOnly() ||
!$this->getId() ) {
1445 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1446 if ( !count( $toPromote ) ) {
1450 if ( !$this->checkAndSetTouched() ) {
1451 return []; // raced out (bug T48834)
1454 $oldGroups = $this->getGroups(); // previous groups
1455 foreach ( $toPromote as $group ) {
1456 $this->addGroup( $group );
1458 // update groups in external authentication database
1459 Hooks
::run( 'UserGroupsChanged', [ $this, $toPromote, [], false, false ] );
1460 AuthManager
::callLegacyAuthPlugin( 'updateExternalDBGroups', [ $this, $toPromote ] );
1462 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1464 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1465 $logEntry->setPerformer( $this );
1466 $logEntry->setTarget( $this->getUserPage() );
1467 $logEntry->setParameters( [
1468 '4::oldgroups' => $oldGroups,
1469 '5::newgroups' => $newGroups,
1471 $logid = $logEntry->insert();
1472 if ( $wgAutopromoteOnceLogInRC ) {
1473 $logEntry->publish( $logid );
1480 * Builds update conditions. Additional conditions may be added to $conditions to
1481 * protected against race conditions using a compare-and-set (CAS) mechanism
1482 * based on comparing $this->mTouched with the user_touched field.
1484 * @param Database $db
1485 * @param array $conditions WHERE conditions for use with Database::update
1486 * @return array WHERE conditions for use with Database::update
1488 protected function makeUpdateConditions( Database
$db, array $conditions ) {
1489 if ( $this->mTouched
) {
1490 // CAS check: only update if the row wasn't changed sicne it was loaded.
1491 $conditions['user_touched'] = $db->timestamp( $this->mTouched
);
1498 * Bump user_touched if it didn't change since this object was loaded
1500 * On success, the mTouched field is updated.
1501 * The user serialization cache is always cleared.
1503 * @return bool Whether user_touched was actually updated
1506 protected function checkAndSetTouched() {
1509 if ( !$this->mId
) {
1510 return false; // anon
1513 // Get a new user_touched that is higher than the old one
1514 $newTouched = $this->newTouchedTimestamp();
1516 $dbw = wfGetDB( DB_MASTER
);
1517 $dbw->update( 'user',
1518 [ 'user_touched' => $dbw->timestamp( $newTouched ) ],
1519 $this->makeUpdateConditions( $dbw, [
1520 'user_id' => $this->mId
,
1524 $success = ( $dbw->affectedRows() > 0 );
1527 $this->mTouched
= $newTouched;
1528 $this->clearSharedCache();
1530 // Clears on failure too since that is desired if the cache is stale
1531 $this->clearSharedCache( 'refresh' );
1538 * Clear various cached data stored in this object. The cache of the user table
1539 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1541 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1542 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1544 public function clearInstanceCache( $reloadFrom = false ) {
1545 $this->mNewtalk
= -1;
1546 $this->mDatePreference
= null;
1547 $this->mBlockedby
= -1; # Unset
1548 $this->mHash
= false;
1549 $this->mRights
= null;
1550 $this->mEffectiveGroups
= null;
1551 $this->mImplicitGroups
= null;
1552 $this->mGroupMemberships
= null;
1553 $this->mOptions
= null;
1554 $this->mOptionsLoaded
= false;
1555 $this->mEditCount
= null;
1557 if ( $reloadFrom ) {
1558 $this->mLoadedItems
= [];
1559 $this->mFrom
= $reloadFrom;
1564 * Combine the language default options with any site-specific options
1565 * and add the default language variants.
1567 * @return array Array of String options
1569 public static function getDefaultOptions() {
1570 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1572 static $defOpt = null;
1573 static $defOptLang = null;
1575 if ( $defOpt !== null && $defOptLang === $wgContLang->getCode() ) {
1576 // $wgContLang does not change (and should not change) mid-request,
1577 // but the unit tests change it anyway, and expect this method to
1578 // return values relevant to the current $wgContLang.
1582 $defOpt = $wgDefaultUserOptions;
1583 // Default language setting
1584 $defOptLang = $wgContLang->getCode();
1585 $defOpt['language'] = $defOptLang;
1586 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1587 $defOpt[$langCode == $wgContLang->getCode() ?
'variant' : "variant-$langCode"] = $langCode;
1590 // NOTE: don't use SearchEngineConfig::getSearchableNamespaces here,
1591 // since extensions may change the set of searchable namespaces depending
1592 // on user groups/permissions.
1593 foreach ( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
1594 $defOpt['searchNs' . $nsnum] = (bool)$val;
1596 $defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1598 Hooks
::run( 'UserGetDefaultOptions', [ &$defOpt ] );
1604 * Get a given default option value.
1606 * @param string $opt Name of option to retrieve
1607 * @return string Default option value
1609 public static function getDefaultOption( $opt ) {
1610 $defOpts = self
::getDefaultOptions();
1611 if ( isset( $defOpts[$opt] ) ) {
1612 return $defOpts[$opt];
1619 * Get blocking information
1620 * @param bool $bFromSlave Whether to check the replica DB first.
1621 * To improve performance, non-critical checks are done against replica DBs.
1622 * Check when actually saving should be done against master.
1624 private function getBlockedStatus( $bFromSlave = true ) {
1625 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff, $wgSoftBlockRanges;
1627 if ( -1 != $this->mBlockedby
) {
1631 wfDebug( __METHOD__
. ": checking...\n" );
1633 // Initialize data...
1634 // Otherwise something ends up stomping on $this->mBlockedby when
1635 // things get lazy-loaded later, causing false positive block hits
1636 // due to -1 !== 0. Probably session-related... Nothing should be
1637 // overwriting mBlockedby, surely?
1640 # We only need to worry about passing the IP address to the Block generator if the
1641 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1642 # know which IP address they're actually coming from
1644 if ( !$this->isAllowed( 'ipblock-exempt' ) ) {
1645 // $wgUser->getName() only works after the end of Setup.php. Until
1646 // then, assume it's a logged-out user.
1647 $globalUserName = $wgUser->isSafeToLoad()
1648 ?
$wgUser->getName()
1649 : IP
::sanitizeIP( $wgUser->getRequest()->getIP() );
1650 if ( $this->getName() === $globalUserName ) {
1651 $ip = $this->getRequest()->getIP();
1656 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1659 if ( !$block instanceof Block
) {
1660 $block = $this->getBlockFromCookieValue( $this->getRequest()->getCookie( 'BlockID' ) );
1664 if ( !$block instanceof Block
&& $ip !== null && !in_array( $ip, $wgProxyWhitelist ) ) {
1666 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1667 $block = new Block( [
1668 'byText' => wfMessage( 'proxyblocker' )->text(),
1669 'reason' => wfMessage( 'proxyblockreason' )->text(),
1671 'systemBlock' => 'proxy',
1673 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1674 $block = new Block( [
1675 'byText' => wfMessage( 'sorbs' )->text(),
1676 'reason' => wfMessage( 'sorbsreason' )->text(),
1678 'systemBlock' => 'dnsbl',
1683 // (T25343) Apply IP blocks to the contents of XFF headers, if enabled
1684 if ( !$block instanceof Block
1685 && $wgApplyIpBlocksToXff
1687 && !in_array( $ip, $wgProxyWhitelist )
1689 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1690 $xff = array_map( 'trim', explode( ',', $xff ) );
1691 $xff = array_diff( $xff, [ $ip ] );
1692 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1693 $block = Block
::chooseBlock( $xffblocks, $xff );
1694 if ( $block instanceof Block
) {
1695 # Mangle the reason to alert the user that the block
1696 # originated from matching the X-Forwarded-For header.
1697 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->text();
1701 if ( !$block instanceof Block
1704 && IP
::isInRanges( $ip, $wgSoftBlockRanges )
1706 $block = new Block( [
1708 'byText' => 'MediaWiki default',
1709 'reason' => wfMessage( 'softblockrangesreason', $ip )->text(),
1711 'systemBlock' => 'wgSoftBlockRanges',
1715 if ( $block instanceof Block
) {
1716 wfDebug( __METHOD__
. ": Found block.\n" );
1717 $this->mBlock
= $block;
1718 $this->mBlockedby
= $block->getByName();
1719 $this->mBlockreason
= $block->mReason
;
1720 $this->mHideName
= $block->mHideName
;
1721 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1723 $this->mBlockedby
= '';
1724 $this->mHideName
= 0;
1725 $this->mAllowUsertalk
= false;
1728 // Avoid PHP 7.1 warning of passing $this by reference
1731 Hooks
::run( 'GetBlockedStatus', [ &$user ] );
1735 * Try to load a Block from an ID given in a cookie value.
1736 * @param string|null $blockCookieVal The cookie value to check.
1737 * @return Block|bool The Block object, or false if none could be loaded.
1739 protected function getBlockFromCookieValue( $blockCookieVal ) {
1740 // Make sure there's something to check. The cookie value must start with a number.
1741 if ( strlen( $blockCookieVal ) < 1 ||
!is_numeric( substr( $blockCookieVal, 0, 1 ) ) ) {
1744 // Load the Block from the ID in the cookie.
1745 $blockCookieId = Block
::getIdFromCookieValue( $blockCookieVal );
1746 if ( $blockCookieId !== null ) {
1747 // An ID was found in the cookie.
1748 $tmpBlock = Block
::newFromID( $blockCookieId );
1749 if ( $tmpBlock instanceof Block
) {
1750 // Check the validity of the block.
1751 $blockIsValid = $tmpBlock->getType() == Block
::TYPE_USER
1752 && !$tmpBlock->isExpired()
1753 && $tmpBlock->isAutoblocking();
1754 $config = RequestContext
::getMain()->getConfig();
1755 $useBlockCookie = ( $config->get( 'CookieSetOnAutoblock' ) === true );
1756 if ( $blockIsValid && $useBlockCookie ) {
1760 // If the block is not valid, remove the cookie.
1761 Block
::clearCookie( $this->getRequest()->response() );
1764 // If the block doesn't exist, remove the cookie.
1765 Block
::clearCookie( $this->getRequest()->response() );
1772 * Whether the given IP is in a DNS blacklist.
1774 * @param string $ip IP to check
1775 * @param bool $checkWhitelist Whether to check the whitelist first
1776 * @return bool True if blacklisted.
1778 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1779 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1781 if ( !$wgEnableDnsBlacklist ) {
1785 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1789 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1793 * Whether the given IP is in a given DNS blacklist.
1795 * @param string $ip IP to check
1796 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1797 * @return bool True if blacklisted.
1799 public function inDnsBlacklist( $ip, $bases ) {
1801 // @todo FIXME: IPv6 ??? (https://bugs.php.net/bug.php?id=33170)
1802 if ( IP
::isIPv4( $ip ) ) {
1803 // Reverse IP, T23255
1804 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1806 foreach ( (array)$bases as $base ) {
1808 // If we have an access key, use that too (ProjectHoneypot, etc.)
1810 if ( is_array( $base ) ) {
1811 if ( count( $base ) >= 2 ) {
1812 // Access key is 1, base URL is 0
1813 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1815 $host = "$ipReversed.{$base[0]}";
1817 $basename = $base[0];
1819 $host = "$ipReversed.$base";
1823 $ipList = gethostbynamel( $host );
1826 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
1830 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
1839 * Check if an IP address is in the local proxy list
1845 public static function isLocallyBlockedProxy( $ip ) {
1846 global $wgProxyList;
1848 if ( !$wgProxyList ) {
1852 if ( !is_array( $wgProxyList ) ) {
1853 // Load values from the specified file
1854 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1857 $resultProxyList = [];
1858 $deprecatedIPEntries = [];
1860 // backward compatibility: move all ip addresses in keys to values
1861 foreach ( $wgProxyList as $key => $value ) {
1862 $keyIsIP = IP
::isIPAddress( $key );
1863 $valueIsIP = IP
::isIPAddress( $value );
1864 if ( $keyIsIP && !$valueIsIP ) {
1865 $deprecatedIPEntries[] = $key;
1866 $resultProxyList[] = $key;
1867 } elseif ( $keyIsIP && $valueIsIP ) {
1868 $deprecatedIPEntries[] = $key;
1869 $resultProxyList[] = $key;
1870 $resultProxyList[] = $value;
1872 $resultProxyList[] = $value;
1876 if ( $deprecatedIPEntries ) {
1878 'IP addresses in the keys of $wgProxyList (found the following IP addresses in keys: ' .
1879 implode( ', ', $deprecatedIPEntries ) . ', please move them to values)', '1.30' );
1882 $proxyListIPSet = new IPSet( $resultProxyList );
1883 return $proxyListIPSet->match( $ip );
1887 * Is this user subject to rate limiting?
1889 * @return bool True if rate limited
1891 public function isPingLimitable() {
1892 global $wgRateLimitsExcludedIPs;
1893 if ( IP
::isInRanges( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1894 // No other good way currently to disable rate limits
1895 // for specific IPs. :P
1896 // But this is a crappy hack and should die.
1899 return !$this->isAllowed( 'noratelimit' );
1903 * Primitive rate limits: enforce maximum actions per time period
1904 * to put a brake on flooding.
1906 * The method generates both a generic profiling point and a per action one
1907 * (suffix being "-$action".
1909 * @note When using a shared cache like memcached, IP-address
1910 * last-hit counters will be shared across wikis.
1912 * @param string $action Action to enforce; 'edit' if unspecified
1913 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1914 * @return bool True if a rate limiter was tripped
1916 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1917 // Avoid PHP 7.1 warning of passing $this by reference
1919 // Call the 'PingLimiter' hook
1921 if ( !Hooks
::run( 'PingLimiter', [ &$user, $action, &$result, $incrBy ] ) ) {
1925 global $wgRateLimits;
1926 if ( !isset( $wgRateLimits[$action] ) ) {
1930 $limits = array_merge(
1931 [ '&can-bypass' => true ],
1932 $wgRateLimits[$action]
1935 // Some groups shouldn't trigger the ping limiter, ever
1936 if ( $limits['&can-bypass'] && !$this->isPingLimitable() ) {
1941 $id = $this->getId();
1943 $isNewbie = $this->isNewbie();
1944 $cache = ObjectCache
::getLocalClusterInstance();
1948 if ( isset( $limits['anon'] ) ) {
1949 $keys[$cache->makeKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1952 // limits for logged-in users
1953 if ( isset( $limits['user'] ) ) {
1954 $userLimit = $limits['user'];
1956 // limits for newbie logged-in users
1957 if ( $isNewbie && isset( $limits['newbie'] ) ) {
1958 $keys[$cache->makeKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1962 // limits for anons and for newbie logged-in users
1965 if ( isset( $limits['ip'] ) ) {
1966 $ip = $this->getRequest()->getIP();
1967 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1969 // subnet-based limits
1970 if ( isset( $limits['subnet'] ) ) {
1971 $ip = $this->getRequest()->getIP();
1972 $subnet = IP
::getSubnet( $ip );
1973 if ( $subnet !== false ) {
1974 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1979 // Check for group-specific permissions
1980 // If more than one group applies, use the group with the highest limit ratio (max/period)
1981 foreach ( $this->getGroups() as $group ) {
1982 if ( isset( $limits[$group] ) ) {
1983 if ( $userLimit === false
1984 ||
$limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1986 $userLimit = $limits[$group];
1991 // Set the user limit key
1992 if ( $userLimit !== false ) {
1993 list( $max, $period ) = $userLimit;
1994 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
1995 $keys[$cache->makeKey( 'limiter', $action, 'user', $id )] = $userLimit;
1998 // ip-based limits for all ping-limitable users
1999 if ( isset( $limits['ip-all'] ) ) {
2000 $ip = $this->getRequest()->getIP();
2001 // ignore if user limit is more permissive
2002 if ( $isNewbie ||
$userLimit === false
2003 ||
$limits['ip-all'][0] / $limits['ip-all'][1] > $userLimit[0] / $userLimit[1] ) {
2004 $keys["mediawiki:limiter:$action:ip-all:$ip"] = $limits['ip-all'];
2008 // subnet-based limits for all ping-limitable users
2009 if ( isset( $limits['subnet-all'] ) ) {
2010 $ip = $this->getRequest()->getIP();
2011 $subnet = IP
::getSubnet( $ip );
2012 if ( $subnet !== false ) {
2013 // ignore if user limit is more permissive
2014 if ( $isNewbie ||
$userLimit === false
2015 ||
$limits['ip-all'][0] / $limits['ip-all'][1]
2016 > $userLimit[0] / $userLimit[1] ) {
2017 $keys["mediawiki:limiter:$action:subnet-all:$subnet"] = $limits['subnet-all'];
2023 foreach ( $keys as $key => $limit ) {
2024 list( $max, $period ) = $limit;
2025 $summary = "(limit $max in {$period}s)";
2026 $count = $cache->get( $key );
2029 if ( $count >= $max ) {
2030 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
2031 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
2034 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
2037 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
2038 if ( $incrBy > 0 ) {
2039 $cache->add( $key, 0, intval( $period ) ); // first ping
2042 if ( $incrBy > 0 ) {
2043 $cache->incr( $key, $incrBy );
2051 * Check if user is blocked
2053 * @param bool $bFromSlave Whether to check the replica DB instead of
2054 * the master. Hacked from false due to horrible probs on site.
2055 * @return bool True if blocked, false otherwise
2057 public function isBlocked( $bFromSlave = true ) {
2058 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
2062 * Get the block affecting the user, or null if the user is not blocked
2064 * @param bool $bFromSlave Whether to check the replica DB instead of the master
2065 * @return Block|null
2067 public function getBlock( $bFromSlave = true ) {
2068 $this->getBlockedStatus( $bFromSlave );
2069 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
2073 * Check if user is blocked from editing a particular article
2075 * @param Title $title Title to check
2076 * @param bool $bFromSlave Whether to check the replica DB instead of the master
2079 public function isBlockedFrom( $title, $bFromSlave = false ) {
2080 global $wgBlockAllowsUTEdit;
2082 $blocked = $this->isBlocked( $bFromSlave );
2083 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
2084 // If a user's name is suppressed, they cannot make edits anywhere
2085 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName()
2086 && $title->getNamespace() == NS_USER_TALK
) {
2088 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
2091 Hooks
::run( 'UserIsBlockedFrom', [ $this, $title, &$blocked, &$allowUsertalk ] );
2097 * If user is blocked, return the name of the user who placed the block
2098 * @return string Name of blocker
2100 public function blockedBy() {
2101 $this->getBlockedStatus();
2102 return $this->mBlockedby
;
2106 * If user is blocked, return the specified reason for the block
2107 * @return string Blocking reason
2109 public function blockedFor() {
2110 $this->getBlockedStatus();
2111 return $this->mBlockreason
;
2115 * If user is blocked, return the ID for the block
2116 * @return int Block ID
2118 public function getBlockId() {
2119 $this->getBlockedStatus();
2120 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
2124 * Check if user is blocked on all wikis.
2125 * Do not use for actual edit permission checks!
2126 * This is intended for quick UI checks.
2128 * @param string $ip IP address, uses current client if none given
2129 * @return bool True if blocked, false otherwise
2131 public function isBlockedGlobally( $ip = '' ) {
2132 return $this->getGlobalBlock( $ip ) instanceof Block
;
2136 * Check if user is blocked on all wikis.
2137 * Do not use for actual edit permission checks!
2138 * This is intended for quick UI checks.
2140 * @param string $ip IP address, uses current client if none given
2141 * @return Block|null Block object if blocked, null otherwise
2142 * @throws FatalError
2143 * @throws MWException
2145 public function getGlobalBlock( $ip = '' ) {
2146 if ( $this->mGlobalBlock
!== null ) {
2147 return $this->mGlobalBlock ?
: null;
2149 // User is already an IP?
2150 if ( IP
::isIPAddress( $this->getName() ) ) {
2151 $ip = $this->getName();
2153 $ip = $this->getRequest()->getIP();
2155 // Avoid PHP 7.1 warning of passing $this by reference
2159 Hooks
::run( 'UserIsBlockedGlobally', [ &$user, $ip, &$blocked, &$block ] );
2161 if ( $blocked && $block === null ) {
2162 // back-compat: UserIsBlockedGlobally didn't have $block param first
2163 $block = new Block( [
2165 'systemBlock' => 'global-block'
2169 $this->mGlobalBlock
= $blocked ?
$block : false;
2170 return $this->mGlobalBlock ?
: null;
2174 * Check if user account is locked
2176 * @return bool True if locked, false otherwise
2178 public function isLocked() {
2179 if ( $this->mLocked
!== null ) {
2180 return $this->mLocked
;
2182 // Avoid PHP 7.1 warning of passing $this by reference
2184 $authUser = AuthManager
::callLegacyAuthPlugin( 'getUserInstance', [ &$user ], null );
2185 $this->mLocked
= $authUser && $authUser->isLocked();
2186 Hooks
::run( 'UserIsLocked', [ $this, &$this->mLocked
] );
2187 return $this->mLocked
;
2191 * Check if user account is hidden
2193 * @return bool True if hidden, false otherwise
2195 public function isHidden() {
2196 if ( $this->mHideName
!== null ) {
2197 return $this->mHideName
;
2199 $this->getBlockedStatus();
2200 if ( !$this->mHideName
) {
2201 // Avoid PHP 7.1 warning of passing $this by reference
2203 $authUser = AuthManager
::callLegacyAuthPlugin( 'getUserInstance', [ &$user ], null );
2204 $this->mHideName
= $authUser && $authUser->isHidden();
2205 Hooks
::run( 'UserIsHidden', [ $this, &$this->mHideName
] );
2207 return $this->mHideName
;
2211 * Get the user's ID.
2212 * @return int The user's ID; 0 if the user is anonymous or nonexistent
2214 public function getId() {
2215 if ( $this->mId
=== null && $this->mName
!== null && self
::isIP( $this->mName
) ) {
2216 // Special case, we know the user is anonymous
2218 } elseif ( !$this->isItemLoaded( 'id' ) ) {
2219 // Don't load if this was initialized from an ID
2223 return (int)$this->mId
;
2227 * Set the user and reload all fields according to a given ID
2228 * @param int $v User ID to reload
2230 public function setId( $v ) {
2232 $this->clearInstanceCache( 'id' );
2236 * Get the user name, or the IP of an anonymous user
2237 * @return string User's name or IP address
2239 public function getName() {
2240 if ( $this->isItemLoaded( 'name', 'only' ) ) {
2241 // Special case optimisation
2242 return $this->mName
;
2245 if ( $this->mName
=== false ) {
2247 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
2249 return $this->mName
;
2254 * Set the user name.
2256 * This does not reload fields from the database according to the given
2257 * name. Rather, it is used to create a temporary "nonexistent user" for
2258 * later addition to the database. It can also be used to set the IP
2259 * address for an anonymous user to something other than the current
2262 * @note User::newFromName() has roughly the same function, when the named user
2264 * @param string $str New user name to set
2266 public function setName( $str ) {
2268 $this->mName
= $str;
2272 * Get the user's name escaped by underscores.
2273 * @return string Username escaped by underscores.
2275 public function getTitleKey() {
2276 return str_replace( ' ', '_', $this->getName() );
2280 * Check if the user has new messages.
2281 * @return bool True if the user has new messages
2283 public function getNewtalk() {
2286 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2287 if ( $this->mNewtalk
=== -1 ) {
2288 $this->mNewtalk
= false; # reset talk page status
2290 // Check memcached separately for anons, who have no
2291 // entire User object stored in there.
2292 if ( !$this->mId
) {
2293 global $wgDisableAnonTalk;
2294 if ( $wgDisableAnonTalk ) {
2295 // Anon newtalk disabled by configuration.
2296 $this->mNewtalk
= false;
2298 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
2301 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2305 return (bool)$this->mNewtalk
;
2309 * Return the data needed to construct links for new talk page message
2310 * alerts. If there are new messages, this will return an associative array
2311 * with the following data:
2312 * wiki: The database name of the wiki
2313 * link: Root-relative link to the user's talk page
2314 * rev: The last talk page revision that the user has seen or null. This
2315 * is useful for building diff links.
2316 * If there are no new messages, it returns an empty array.
2317 * @note This function was designed to accomodate multiple talk pages, but
2318 * currently only returns a single link and revision.
2321 public function getNewMessageLinks() {
2322 // Avoid PHP 7.1 warning of passing $this by reference
2325 if ( !Hooks
::run( 'UserRetrieveNewTalks', [ &$user, &$talks ] ) ) {
2327 } elseif ( !$this->getNewtalk() ) {
2330 $utp = $this->getTalkPage();
2331 $dbr = wfGetDB( DB_REPLICA
);
2332 // Get the "last viewed rev" timestamp from the oldest message notification
2333 $timestamp = $dbr->selectField( 'user_newtalk',
2334 'MIN(user_last_timestamp)',
2335 $this->isAnon() ?
[ 'user_ip' => $this->getName() ] : [ 'user_id' => $this->getId() ],
2337 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2338 return [ [ 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ] ];
2342 * Get the revision ID for the last talk page revision viewed by the talk
2344 * @return int|null Revision ID or null
2346 public function getNewMessageRevisionId() {
2347 $newMessageRevisionId = null;
2348 $newMessageLinks = $this->getNewMessageLinks();
2349 if ( $newMessageLinks ) {
2350 // Note: getNewMessageLinks() never returns more than a single link
2351 // and it is always for the same wiki, but we double-check here in
2352 // case that changes some time in the future.
2353 if ( count( $newMessageLinks ) === 1
2354 && $newMessageLinks[0]['wiki'] === wfWikiID()
2355 && $newMessageLinks[0]['rev']
2357 /** @var Revision $newMessageRevision */
2358 $newMessageRevision = $newMessageLinks[0]['rev'];
2359 $newMessageRevisionId = $newMessageRevision->getId();
2362 return $newMessageRevisionId;
2366 * Internal uncached check for new messages
2369 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2370 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2371 * @return bool True if the user has new messages
2373 protected function checkNewtalk( $field, $id ) {
2374 $dbr = wfGetDB( DB_REPLICA
);
2376 $ok = $dbr->selectField( 'user_newtalk', $field, [ $field => $id ], __METHOD__
);
2378 return $ok !== false;
2382 * Add or update the new messages flag
2383 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2384 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2385 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2386 * @return bool True if successful, false otherwise
2388 protected function updateNewtalk( $field, $id, $curRev = null ) {
2389 // Get timestamp of the talk page revision prior to the current one
2390 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2391 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2392 // Mark the user as having new messages since this revision
2393 $dbw = wfGetDB( DB_MASTER
);
2394 $dbw->insert( 'user_newtalk',
2395 [ $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ],
2398 if ( $dbw->affectedRows() ) {
2399 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2402 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2408 * Clear the new messages flag for the given user
2409 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2410 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2411 * @return bool True if successful, false otherwise
2413 protected function deleteNewtalk( $field, $id ) {
2414 $dbw = wfGetDB( DB_MASTER
);
2415 $dbw->delete( 'user_newtalk',
2418 if ( $dbw->affectedRows() ) {
2419 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2422 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2428 * Update the 'You have new messages!' status.
2429 * @param bool $val Whether the user has new messages
2430 * @param Revision $curRev New, as yet unseen revision of the user talk
2431 * page. Ignored if null or !$val.
2433 public function setNewtalk( $val, $curRev = null ) {
2434 if ( wfReadOnly() ) {
2439 $this->mNewtalk
= $val;
2441 if ( $this->isAnon() ) {
2443 $id = $this->getName();
2446 $id = $this->getId();
2450 $changed = $this->updateNewtalk( $field, $id, $curRev );
2452 $changed = $this->deleteNewtalk( $field, $id );
2456 $this->invalidateCache();
2461 * Generate a current or new-future timestamp to be stored in the
2462 * user_touched field when we update things.
2463 * @return string Timestamp in TS_MW format
2465 private function newTouchedTimestamp() {
2466 global $wgClockSkewFudge;
2468 $time = wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2469 if ( $this->mTouched
&& $time <= $this->mTouched
) {
2470 $time = wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $this->mTouched
) +
1 );
2477 * Clear user data from memcached
2479 * Use after applying updates to the database; caller's
2480 * responsibility to update user_touched if appropriate.
2482 * Called implicitly from invalidateCache() and saveSettings().
2484 * @param string $mode Use 'refresh' to clear now; otherwise before DB commit
2486 public function clearSharedCache( $mode = 'changed' ) {
2487 if ( !$this->getId() ) {
2491 $cache = ObjectCache
::getMainWANInstance();
2492 $key = $this->getCacheKey( $cache );
2493 if ( $mode === 'refresh' ) {
2494 $cache->delete( $key, 1 );
2496 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle(
2497 function () use ( $cache, $key ) {
2498 $cache->delete( $key );
2506 * Immediately touch the user data cache for this account
2508 * Calls touch() and removes account data from memcached
2510 public function invalidateCache() {
2512 $this->clearSharedCache();
2516 * Update the "touched" timestamp for the user
2518 * This is useful on various login/logout events when making sure that
2519 * a browser or proxy that has multiple tenants does not suffer cache
2520 * pollution where the new user sees the old users content. The value
2521 * of getTouched() is checked when determining 304 vs 200 responses.
2522 * Unlike invalidateCache(), this preserves the User object cache and
2523 * avoids database writes.
2527 public function touch() {
2528 $id = $this->getId();
2530 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
2531 $key = $cache->makeKey( 'user-quicktouched', 'id', $id );
2532 $cache->touchCheckKey( $key );
2533 $this->mQuickTouched
= null;
2538 * Validate the cache for this account.
2539 * @param string $timestamp A timestamp in TS_MW format
2542 public function validateCache( $timestamp ) {
2543 return ( $timestamp >= $this->getTouched() );
2547 * Get the user touched timestamp
2549 * Use this value only to validate caches via inequalities
2550 * such as in the case of HTTP If-Modified-Since response logic
2552 * @return string TS_MW Timestamp
2554 public function getTouched() {
2558 if ( $this->mQuickTouched
=== null ) {
2559 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
2560 $key = $cache->makeKey( 'user-quicktouched', 'id', $this->mId
);
2562 $this->mQuickTouched
= wfTimestamp( TS_MW
, $cache->getCheckKeyTime( $key ) );
2565 return max( $this->mTouched
, $this->mQuickTouched
);
2568 return $this->mTouched
;
2572 * Get the user_touched timestamp field (time of last DB updates)
2573 * @return string TS_MW Timestamp
2576 public function getDBTouched() {
2579 return $this->mTouched
;
2583 * Set the password and reset the random token.
2584 * Calls through to authentication plugin if necessary;
2585 * will have no effect if the auth plugin refuses to
2586 * pass the change through or if the legal password
2589 * As a special case, setting the password to null
2590 * wipes it, so the account cannot be logged in until
2591 * a new password is set, for instance via e-mail.
2593 * @deprecated since 1.27, use AuthManager instead
2594 * @param string $str New password to set
2595 * @throws PasswordError On failure
2598 public function setPassword( $str ) {
2599 return $this->setPasswordInternal( $str );
2603 * Set the password and reset the random token unconditionally.
2605 * @deprecated since 1.27, use AuthManager instead
2606 * @param string|null $str New password to set or null to set an invalid
2607 * password hash meaning that the user will not be able to log in
2608 * through the web interface.
2610 public function setInternalPassword( $str ) {
2611 $this->setPasswordInternal( $str );
2615 * Actually set the password and such
2616 * @since 1.27 cannot set a password for a user not in the database
2617 * @param string|null $str New password to set or null to set an invalid
2618 * password hash meaning that the user will not be able to log in
2619 * through the web interface.
2620 * @return bool Success
2622 private function setPasswordInternal( $str ) {
2623 $manager = AuthManager
::singleton();
2625 // If the user doesn't exist yet, fail
2626 if ( !$manager->userExists( $this->getName() ) ) {
2627 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2630 $status = $this->changeAuthenticationData( [
2631 'username' => $this->getName(),
2635 if ( !$status->isGood() ) {
2636 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
2637 ->info( __METHOD__
. ': Password change rejected: '
2638 . $status->getWikiText( null, null, 'en' ) );
2642 $this->setOption( 'watchlisttoken', false );
2643 SessionManager
::singleton()->invalidateSessionsForUser( $this );
2649 * Changes credentials of the user.
2651 * This is a convenience wrapper around AuthManager::changeAuthenticationData.
2652 * Note that this can return a status that isOK() but not isGood() on certain types of failures,
2653 * e.g. when no provider handled the change.
2655 * @param array $data A set of authentication data in fieldname => value format. This is the
2656 * same data you would pass the changeauthenticationdata API - 'username', 'password' etc.
2660 public function changeAuthenticationData( array $data ) {
2661 $manager = AuthManager
::singleton();
2662 $reqs = $manager->getAuthenticationRequests( AuthManager
::ACTION_CHANGE
, $this );
2663 $reqs = AuthenticationRequest
::loadRequestsFromSubmission( $reqs, $data );
2665 $status = Status
::newGood( 'ignored' );
2666 foreach ( $reqs as $req ) {
2667 $status->merge( $manager->allowsAuthenticationDataChange( $req ), true );
2669 if ( $status->getValue() === 'ignored' ) {
2670 $status->warning( 'authenticationdatachange-ignored' );
2673 if ( $status->isGood() ) {
2674 foreach ( $reqs as $req ) {
2675 $manager->changeAuthenticationData( $req );
2682 * Get the user's current token.
2683 * @param bool $forceCreation Force the generation of a new token if the
2684 * user doesn't have one (default=true for backwards compatibility).
2685 * @return string|null Token
2687 public function getToken( $forceCreation = true ) {
2688 global $wgAuthenticationTokenVersion;
2691 if ( !$this->mToken
&& $forceCreation ) {
2695 if ( !$this->mToken
) {
2696 // The user doesn't have a token, return null to indicate that.
2698 } elseif ( $this->mToken
=== self
::INVALID_TOKEN
) {
2699 // We return a random value here so existing token checks are very
2701 return MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2702 } elseif ( $wgAuthenticationTokenVersion === null ) {
2703 // $wgAuthenticationTokenVersion not in use, so return the raw secret
2704 return $this->mToken
;
2706 // $wgAuthenticationTokenVersion in use, so hmac it.
2707 $ret = MWCryptHash
::hmac( $wgAuthenticationTokenVersion, $this->mToken
, false );
2709 // The raw hash can be overly long. Shorten it up.
2710 $len = max( 32, self
::TOKEN_LENGTH
);
2711 if ( strlen( $ret ) < $len ) {
2712 // Should never happen, even md5 is 128 bits
2713 throw new \
UnexpectedValueException( 'Hmac returned less than 128 bits' );
2715 return substr( $ret, -$len );
2720 * Set the random token (used for persistent authentication)
2721 * Called from loadDefaults() among other places.
2723 * @param string|bool $token If specified, set the token to this value
2725 public function setToken( $token = false ) {
2727 if ( $this->mToken
=== self
::INVALID_TOKEN
) {
2728 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
2729 ->debug( __METHOD__
. ": Ignoring attempt to set token for system user \"$this\"" );
2730 } elseif ( !$token ) {
2731 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2733 $this->mToken
= $token;
2738 * Set the password for a password reminder or new account email
2740 * @deprecated Removed in 1.27. Use PasswordReset instead.
2741 * @param string $str New password to set or null to set an invalid
2742 * password hash meaning that the user will not be able to use it
2743 * @param bool $throttle If true, reset the throttle timestamp to the present
2745 public function setNewpassword( $str, $throttle = true ) {
2746 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2750 * Get the user's e-mail address
2751 * @return string User's email address
2753 public function getEmail() {
2755 Hooks
::run( 'UserGetEmail', [ $this, &$this->mEmail
] );
2756 return $this->mEmail
;
2760 * Get the timestamp of the user's e-mail authentication
2761 * @return string TS_MW timestamp
2763 public function getEmailAuthenticationTimestamp() {
2765 Hooks
::run( 'UserGetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
2766 return $this->mEmailAuthenticated
;
2770 * Set the user's e-mail address
2771 * @param string $str New e-mail address
2773 public function setEmail( $str ) {
2775 if ( $str == $this->mEmail
) {
2778 $this->invalidateEmail();
2779 $this->mEmail
= $str;
2780 Hooks
::run( 'UserSetEmail', [ $this, &$this->mEmail
] );
2784 * Set the user's e-mail address and a confirmation mail if needed.
2787 * @param string $str New e-mail address
2790 public function setEmailWithConfirmation( $str ) {
2791 global $wgEnableEmail, $wgEmailAuthentication;
2793 if ( !$wgEnableEmail ) {
2794 return Status
::newFatal( 'emaildisabled' );
2797 $oldaddr = $this->getEmail();
2798 if ( $str === $oldaddr ) {
2799 return Status
::newGood( true );
2802 $type = $oldaddr != '' ?
'changed' : 'set';
2803 $notificationResult = null;
2805 if ( $wgEmailAuthentication ) {
2806 // Send the user an email notifying the user of the change in registered
2807 // email address on their previous email address
2808 if ( $type == 'changed' ) {
2809 $change = $str != '' ?
'changed' : 'removed';
2810 $notificationResult = $this->sendMail(
2811 wfMessage( 'notificationemail_subject_' . $change )->text(),
2812 wfMessage( 'notificationemail_body_' . $change,
2813 $this->getRequest()->getIP(),
2820 $this->setEmail( $str );
2822 if ( $str !== '' && $wgEmailAuthentication ) {
2823 // Send a confirmation request to the new address if needed
2824 $result = $this->sendConfirmationMail( $type );
2826 if ( $notificationResult !== null ) {
2827 $result->merge( $notificationResult );
2830 if ( $result->isGood() ) {
2831 // Say to the caller that a confirmation and notification mail has been sent
2832 $result->value
= 'eauth';
2835 $result = Status
::newGood( true );
2842 * Get the user's real name
2843 * @return string User's real name
2845 public function getRealName() {
2846 if ( !$this->isItemLoaded( 'realname' ) ) {
2850 return $this->mRealName
;
2854 * Set the user's real name
2855 * @param string $str New real name
2857 public function setRealName( $str ) {
2859 $this->mRealName
= $str;
2863 * Get the user's current setting for a given option.
2865 * @param string $oname The option to check
2866 * @param string $defaultOverride A default value returned if the option does not exist
2867 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2868 * @return string|null User's current value for the option
2869 * @see getBoolOption()
2870 * @see getIntOption()
2872 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2873 global $wgHiddenPrefs;
2874 $this->loadOptions();
2876 # We want 'disabled' preferences to always behave as the default value for
2877 # users, even if they have set the option explicitly in their settings (ie they
2878 # set it, and then it was disabled removing their ability to change it). But
2879 # we don't want to erase the preferences in the database in case the preference
2880 # is re-enabled again. So don't touch $mOptions, just override the returned value
2881 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2882 return self
::getDefaultOption( $oname );
2885 if ( array_key_exists( $oname, $this->mOptions
) ) {
2886 return $this->mOptions
[$oname];
2888 return $defaultOverride;
2893 * Get all user's options
2895 * @param int $flags Bitwise combination of:
2896 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2897 * to the default value. (Since 1.25)
2900 public function getOptions( $flags = 0 ) {
2901 global $wgHiddenPrefs;
2902 $this->loadOptions();
2903 $options = $this->mOptions
;
2905 # We want 'disabled' preferences to always behave as the default value for
2906 # users, even if they have set the option explicitly in their settings (ie they
2907 # set it, and then it was disabled removing their ability to change it). But
2908 # we don't want to erase the preferences in the database in case the preference
2909 # is re-enabled again. So don't touch $mOptions, just override the returned value
2910 foreach ( $wgHiddenPrefs as $pref ) {
2911 $default = self
::getDefaultOption( $pref );
2912 if ( $default !== null ) {
2913 $options[$pref] = $default;
2917 if ( $flags & self
::GETOPTIONS_EXCLUDE_DEFAULTS
) {
2918 $options = array_diff_assoc( $options, self
::getDefaultOptions() );
2925 * Get the user's current setting for a given option, as a boolean value.
2927 * @param string $oname The option to check
2928 * @return bool User's current value for the option
2931 public function getBoolOption( $oname ) {
2932 return (bool)$this->getOption( $oname );
2936 * Get the user's current setting for a given option, as an integer value.
2938 * @param string $oname The option to check
2939 * @param int $defaultOverride A default value returned if the option does not exist
2940 * @return int User's current value for the option
2943 public function getIntOption( $oname, $defaultOverride = 0 ) {
2944 $val = $this->getOption( $oname );
2946 $val = $defaultOverride;
2948 return intval( $val );
2952 * Set the given option for a user.
2954 * You need to call saveSettings() to actually write to the database.
2956 * @param string $oname The option to set
2957 * @param mixed $val New value to set
2959 public function setOption( $oname, $val ) {
2960 $this->loadOptions();
2962 // Explicitly NULL values should refer to defaults
2963 if ( is_null( $val ) ) {
2964 $val = self
::getDefaultOption( $oname );
2967 $this->mOptions
[$oname] = $val;
2971 * Get a token stored in the preferences (like the watchlist one),
2972 * resetting it if it's empty (and saving changes).
2974 * @param string $oname The option name to retrieve the token from
2975 * @return string|bool User's current value for the option, or false if this option is disabled.
2976 * @see resetTokenFromOption()
2978 * @deprecated since 1.26 Applications should use the OAuth extension
2980 public function getTokenFromOption( $oname ) {
2981 global $wgHiddenPrefs;
2983 $id = $this->getId();
2984 if ( !$id ||
in_array( $oname, $wgHiddenPrefs ) ) {
2988 $token = $this->getOption( $oname );
2990 // Default to a value based on the user token to avoid space
2991 // wasted on storing tokens for all users. When this option
2992 // is set manually by the user, only then is it stored.
2993 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
3000 * Reset a token stored in the preferences (like the watchlist one).
3001 * *Does not* save user's preferences (similarly to setOption()).
3003 * @param string $oname The option name to reset the token in
3004 * @return string|bool New token value, or false if this option is disabled.
3005 * @see getTokenFromOption()
3008 public function resetTokenFromOption( $oname ) {
3009 global $wgHiddenPrefs;
3010 if ( in_array( $oname, $wgHiddenPrefs ) ) {
3014 $token = MWCryptRand
::generateHex( 40 );
3015 $this->setOption( $oname, $token );
3020 * Return a list of the types of user options currently returned by
3021 * User::getOptionKinds().
3023 * Currently, the option kinds are:
3024 * - 'registered' - preferences which are registered in core MediaWiki or
3025 * by extensions using the UserGetDefaultOptions hook.
3026 * - 'registered-multiselect' - as above, using the 'multiselect' type.
3027 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
3028 * - 'userjs' - preferences with names starting with 'userjs-', intended to
3029 * be used by user scripts.
3030 * - 'special' - "preferences" that are not accessible via User::getOptions
3031 * or User::setOptions.
3032 * - 'unused' - preferences about which MediaWiki doesn't know anything.
3033 * These are usually legacy options, removed in newer versions.
3035 * The API (and possibly others) use this function to determine the possible
3036 * option types for validation purposes, so make sure to update this when a
3037 * new option kind is added.
3039 * @see User::getOptionKinds
3040 * @return array Option kinds
3042 public static function listOptionKinds() {
3045 'registered-multiselect',
3046 'registered-checkmatrix',
3054 * Return an associative array mapping preferences keys to the kind of a preference they're
3055 * used for. Different kinds are handled differently when setting or reading preferences.
3057 * See User::listOptionKinds for the list of valid option types that can be provided.
3059 * @see User::listOptionKinds
3060 * @param IContextSource $context
3061 * @param array $options Assoc. array with options keys to check as keys.
3062 * Defaults to $this->mOptions.
3063 * @return array The key => kind mapping data
3065 public function getOptionKinds( IContextSource
$context, $options = null ) {
3066 $this->loadOptions();
3067 if ( $options === null ) {
3068 $options = $this->mOptions
;
3071 $prefs = Preferences
::getPreferences( $this, $context );
3074 // Pull out the "special" options, so they don't get converted as
3075 // multiselect or checkmatrix.
3076 $specialOptions = array_fill_keys( Preferences
::getSaveBlacklist(), true );
3077 foreach ( $specialOptions as $name => $value ) {
3078 unset( $prefs[$name] );
3081 // Multiselect and checkmatrix options are stored in the database with
3082 // one key per option, each having a boolean value. Extract those keys.
3083 $multiselectOptions = [];
3084 foreach ( $prefs as $name => $info ) {
3085 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
3086 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
3087 $opts = HTMLFormField
::flattenOptions( $info['options'] );
3088 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
3090 foreach ( $opts as $value ) {
3091 $multiselectOptions["$prefix$value"] = true;
3094 unset( $prefs[$name] );
3097 $checkmatrixOptions = [];
3098 foreach ( $prefs as $name => $info ) {
3099 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
3100 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
3101 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
3102 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
3103 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
3105 foreach ( $columns as $column ) {
3106 foreach ( $rows as $row ) {
3107 $checkmatrixOptions["$prefix$column-$row"] = true;
3111 unset( $prefs[$name] );
3115 // $value is ignored
3116 foreach ( $options as $key => $value ) {
3117 if ( isset( $prefs[$key] ) ) {
3118 $mapping[$key] = 'registered';
3119 } elseif ( isset( $multiselectOptions[$key] ) ) {
3120 $mapping[$key] = 'registered-multiselect';
3121 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
3122 $mapping[$key] = 'registered-checkmatrix';
3123 } elseif ( isset( $specialOptions[$key] ) ) {
3124 $mapping[$key] = 'special';
3125 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
3126 $mapping[$key] = 'userjs';
3128 $mapping[$key] = 'unused';
3136 * Reset certain (or all) options to the site defaults
3138 * The optional parameter determines which kinds of preferences will be reset.
3139 * Supported values are everything that can be reported by getOptionKinds()
3140 * and 'all', which forces a reset of *all* preferences and overrides everything else.
3142 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
3143 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
3144 * for backwards-compatibility.
3145 * @param IContextSource|null $context Context source used when $resetKinds
3146 * does not contain 'all', passed to getOptionKinds().
3147 * Defaults to RequestContext::getMain() when null.
3149 public function resetOptions(
3150 $resetKinds = [ 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ],
3151 IContextSource
$context = null
3154 $defaultOptions = self
::getDefaultOptions();
3156 if ( !is_array( $resetKinds ) ) {
3157 $resetKinds = [ $resetKinds ];
3160 if ( in_array( 'all', $resetKinds ) ) {
3161 $newOptions = $defaultOptions;
3163 if ( $context === null ) {
3164 $context = RequestContext
::getMain();
3167 $optionKinds = $this->getOptionKinds( $context );
3168 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
3171 // Use default values for the options that should be deleted, and
3172 // copy old values for the ones that shouldn't.
3173 foreach ( $this->mOptions
as $key => $value ) {
3174 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
3175 if ( array_key_exists( $key, $defaultOptions ) ) {
3176 $newOptions[$key] = $defaultOptions[$key];
3179 $newOptions[$key] = $value;
3184 Hooks
::run( 'UserResetAllOptions', [ $this, &$newOptions, $this->mOptions
, $resetKinds ] );
3186 $this->mOptions
= $newOptions;
3187 $this->mOptionsLoaded
= true;
3191 * Get the user's preferred date format.
3192 * @return string User's preferred date format
3194 public function getDatePreference() {
3195 // Important migration for old data rows
3196 if ( is_null( $this->mDatePreference
) ) {
3198 $value = $this->getOption( 'date' );
3199 $map = $wgLang->getDatePreferenceMigrationMap();
3200 if ( isset( $map[$value] ) ) {
3201 $value = $map[$value];
3203 $this->mDatePreference
= $value;
3205 return $this->mDatePreference
;
3209 * Determine based on the wiki configuration and the user's options,
3210 * whether this user must be over HTTPS no matter what.
3214 public function requiresHTTPS() {
3215 global $wgSecureLogin;
3216 if ( !$wgSecureLogin ) {
3219 $https = $this->getBoolOption( 'prefershttps' );
3220 Hooks
::run( 'UserRequiresHTTPS', [ $this, &$https ] );
3222 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
3229 * Get the user preferred stub threshold
3233 public function getStubThreshold() {
3234 global $wgMaxArticleSize; # Maximum article size, in Kb
3235 $threshold = $this->getIntOption( 'stubthreshold' );
3236 if ( $threshold > $wgMaxArticleSize * 1024 ) {
3237 // If they have set an impossible value, disable the preference
3238 // so we can use the parser cache again.
3245 * Get the permissions this user has.
3246 * @return string[] permission names
3248 public function getRights() {
3249 if ( is_null( $this->mRights
) ) {
3250 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
3251 Hooks
::run( 'UserGetRights', [ $this, &$this->mRights
] );
3253 // Deny any rights denied by the user's session, unless this
3254 // endpoint has no sessions.
3255 if ( !defined( 'MW_NO_SESSION' ) ) {
3256 $allowedRights = $this->getRequest()->getSession()->getAllowedUserRights();
3257 if ( $allowedRights !== null ) {
3258 $this->mRights
= array_intersect( $this->mRights
, $allowedRights );
3262 // Force reindexation of rights when a hook has unset one of them
3263 $this->mRights
= array_values( array_unique( $this->mRights
) );
3265 // If block disables login, we should also remove any
3266 // extra rights blocked users might have, in case the
3267 // blocked user has a pre-existing session (T129738).
3268 // This is checked here for cases where people only call
3269 // $user->isAllowed(). It is also checked in Title::checkUserBlock()
3270 // to give a better error message in the common case.
3271 $config = RequestContext
::getMain()->getConfig();
3273 $this->isLoggedIn() &&
3274 $config->get( 'BlockDisablesLogin' ) &&
3278 $this->mRights
= array_intersect( $this->mRights
, $anon->getRights() );
3281 return $this->mRights
;
3285 * Get the list of explicit group memberships this user has.
3286 * The implicit * and user groups are not included.
3287 * @return array Array of String internal group names
3289 public function getGroups() {
3291 $this->loadGroups();
3292 return array_keys( $this->mGroupMemberships
);
3296 * Get the list of explicit group memberships this user has, stored as
3297 * UserGroupMembership objects. Implicit groups are not included.
3299 * @return array Associative array of (group name as string => UserGroupMembership object)
3302 public function getGroupMemberships() {
3304 $this->loadGroups();
3305 return $this->mGroupMemberships
;
3309 * Get the list of implicit group memberships this user has.
3310 * This includes all explicit groups, plus 'user' if logged in,
3311 * '*' for all accounts, and autopromoted groups
3312 * @param bool $recache Whether to avoid the cache
3313 * @return array Array of String internal group names
3315 public function getEffectiveGroups( $recache = false ) {
3316 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
3317 $this->mEffectiveGroups
= array_unique( array_merge(
3318 $this->getGroups(), // explicit groups
3319 $this->getAutomaticGroups( $recache ) // implicit groups
3321 // Avoid PHP 7.1 warning of passing $this by reference
3323 // Hook for additional groups
3324 Hooks
::run( 'UserEffectiveGroups', [ &$user, &$this->mEffectiveGroups
] );
3325 // Force reindexation of groups when a hook has unset one of them
3326 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
3328 return $this->mEffectiveGroups
;
3332 * Get the list of implicit group memberships this user has.
3333 * This includes 'user' if logged in, '*' for all accounts,
3334 * and autopromoted groups
3335 * @param bool $recache Whether to avoid the cache
3336 * @return array Array of String internal group names
3338 public function getAutomaticGroups( $recache = false ) {
3339 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
3340 $this->mImplicitGroups
= [ '*' ];
3341 if ( $this->getId() ) {
3342 $this->mImplicitGroups
[] = 'user';
3344 $this->mImplicitGroups
= array_unique( array_merge(
3345 $this->mImplicitGroups
,
3346 Autopromote
::getAutopromoteGroups( $this )
3350 // Assure data consistency with rights/groups,
3351 // as getEffectiveGroups() depends on this function
3352 $this->mEffectiveGroups
= null;
3355 return $this->mImplicitGroups
;
3359 * Returns the groups the user has belonged to.
3361 * The user may still belong to the returned groups. Compare with getGroups().
3363 * The function will not return groups the user had belonged to before MW 1.17
3365 * @return array Names of the groups the user has belonged to.
3367 public function getFormerGroups() {
3370 if ( is_null( $this->mFormerGroups
) ) {
3371 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3372 ?
wfGetDB( DB_MASTER
)
3373 : wfGetDB( DB_REPLICA
);
3374 $res = $db->select( 'user_former_groups',
3376 [ 'ufg_user' => $this->mId
],
3378 $this->mFormerGroups
= [];
3379 foreach ( $res as $row ) {
3380 $this->mFormerGroups
[] = $row->ufg_group
;
3384 return $this->mFormerGroups
;
3388 * Get the user's edit count.
3389 * @return int|null Null for anonymous users
3391 public function getEditCount() {
3392 if ( !$this->getId() ) {
3396 if ( $this->mEditCount
=== null ) {
3397 /* Populate the count, if it has not been populated yet */
3398 $dbr = wfGetDB( DB_REPLICA
);
3399 // check if the user_editcount field has been initialized
3400 $count = $dbr->selectField(
3401 'user', 'user_editcount',
3402 [ 'user_id' => $this->mId
],
3406 if ( $count === null ) {
3407 // it has not been initialized. do so.
3408 $count = $this->initEditCount();
3410 $this->mEditCount
= $count;
3412 return (int)$this->mEditCount
;
3416 * Add the user to the given group. This takes immediate effect.
3417 * If the user is already in the group, the expiry time will be updated to the new
3418 * expiry time. (If $expiry is omitted or null, the membership will be altered to
3421 * @param string $group Name of the group to add
3422 * @param string $expiry Optional expiry timestamp in any format acceptable to
3423 * wfTimestamp(), or null if the group assignment should not expire
3426 public function addGroup( $group, $expiry = null ) {
3428 $this->loadGroups();
3431 $expiry = wfTimestamp( TS_MW
, $expiry );
3434 if ( !Hooks
::run( 'UserAddGroup', [ $this, &$group, &$expiry ] ) ) {
3438 // create the new UserGroupMembership and put it in the DB
3439 $ugm = new UserGroupMembership( $this->mId
, $group, $expiry );
3440 if ( !$ugm->insert( true ) ) {
3444 $this->mGroupMemberships
[$group] = $ugm;
3446 // Refresh the groups caches, and clear the rights cache so it will be
3447 // refreshed on the next call to $this->getRights().
3448 $this->getEffectiveGroups( true );
3449 $this->mRights
= null;
3451 $this->invalidateCache();
3457 * Remove the user from the given group.
3458 * This takes immediate effect.
3459 * @param string $group Name of the group to remove
3462 public function removeGroup( $group ) {
3465 if ( !Hooks
::run( 'UserRemoveGroup', [ $this, &$group ] ) ) {
3469 $ugm = UserGroupMembership
::getMembership( $this->mId
, $group );
3470 // delete the membership entry
3471 if ( !$ugm ||
!$ugm->delete() ) {
3475 $this->loadGroups();
3476 unset( $this->mGroupMemberships
[$group] );
3478 // Refresh the groups caches, and clear the rights cache so it will be
3479 // refreshed on the next call to $this->getRights().
3480 $this->getEffectiveGroups( true );
3481 $this->mRights
= null;
3483 $this->invalidateCache();
3489 * Get whether the user is logged in
3492 public function isLoggedIn() {
3493 return $this->getId() != 0;
3497 * Get whether the user is anonymous
3500 public function isAnon() {
3501 return !$this->isLoggedIn();
3505 * @return bool Whether this user is flagged as being a bot role account
3508 public function isBot() {
3509 if ( in_array( 'bot', $this->getGroups() ) && $this->isAllowed( 'bot' ) ) {
3514 Hooks
::run( "UserIsBot", [ $this, &$isBot ] );
3520 * Check if user is allowed to access a feature / make an action
3522 * @param string $permissions,... Permissions to test
3523 * @return bool True if user is allowed to perform *any* of the given actions
3525 public function isAllowedAny() {
3526 $permissions = func_get_args();
3527 foreach ( $permissions as $permission ) {
3528 if ( $this->isAllowed( $permission ) ) {
3537 * @param string $permissions,... Permissions to test
3538 * @return bool True if the user is allowed to perform *all* of the given actions
3540 public function isAllowedAll() {
3541 $permissions = func_get_args();
3542 foreach ( $permissions as $permission ) {
3543 if ( !$this->isAllowed( $permission ) ) {
3551 * Internal mechanics of testing a permission
3552 * @param string $action
3555 public function isAllowed( $action = '' ) {
3556 if ( $action === '' ) {
3557 return true; // In the spirit of DWIM
3559 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3560 // by misconfiguration: 0 == 'foo'
3561 return in_array( $action, $this->getRights(), true );
3565 * Check whether to enable recent changes patrol features for this user
3566 * @return bool True or false
3568 public function useRCPatrol() {
3569 global $wgUseRCPatrol;
3570 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3574 * Check whether to enable new pages patrol features for this user
3575 * @return bool True or false
3577 public function useNPPatrol() {
3578 global $wgUseRCPatrol, $wgUseNPPatrol;
3580 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3581 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3586 * Check whether to enable new files patrol features for this user
3587 * @return bool True or false
3589 public function useFilePatrol() {
3590 global $wgUseRCPatrol, $wgUseFilePatrol;
3592 ( $wgUseRCPatrol ||
$wgUseFilePatrol )
3593 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3598 * Get the WebRequest object to use with this object
3600 * @return WebRequest
3602 public function getRequest() {
3603 if ( $this->mRequest
) {
3604 return $this->mRequest
;
3612 * Check the watched status of an article.
3613 * @since 1.22 $checkRights parameter added
3614 * @param Title $title Title of the article to look at
3615 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3616 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3619 public function isWatched( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3620 if ( $title->isWatchable() && ( !$checkRights ||
$this->isAllowed( 'viewmywatchlist' ) ) ) {
3621 return MediaWikiServices
::getInstance()->getWatchedItemStore()->isWatched( $this, $title );
3628 * @since 1.22 $checkRights parameter added
3629 * @param Title $title Title of the article to look at
3630 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3631 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3633 public function addWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3634 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3635 MediaWikiServices
::getInstance()->getWatchedItemStore()->addWatchBatchForUser(
3637 [ $title->getSubjectPage(), $title->getTalkPage() ]
3640 $this->invalidateCache();
3644 * Stop watching an article.
3645 * @since 1.22 $checkRights parameter added
3646 * @param Title $title Title of the article to look at
3647 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3648 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3650 public function removeWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3651 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3652 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
3653 $store->removeWatch( $this, $title->getSubjectPage() );
3654 $store->removeWatch( $this, $title->getTalkPage() );
3656 $this->invalidateCache();
3660 * Clear the user's notification timestamp for the given title.
3661 * If e-notif e-mails are on, they will receive notification mails on
3662 * the next change of the page if it's watched etc.
3663 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3664 * @param Title &$title Title of the article to look at
3665 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3667 public function clearNotification( &$title, $oldid = 0 ) {
3668 global $wgUseEnotif, $wgShowUpdatedMarker;
3670 // Do nothing if the database is locked to writes
3671 if ( wfReadOnly() ) {
3675 // Do nothing if not allowed to edit the watchlist
3676 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3680 // If we're working on user's talk page, we should update the talk page message indicator
3681 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3682 // Avoid PHP 7.1 warning of passing $this by reference
3684 if ( !Hooks
::run( 'UserClearNewTalkNotification', [ &$user, $oldid ] ) ) {
3688 // Try to update the DB post-send and only if needed...
3689 DeferredUpdates
::addCallableUpdate( function () use ( $title, $oldid ) {
3690 if ( !$this->getNewtalk() ) {
3691 return; // no notifications to clear
3694 // Delete the last notifications (they stack up)
3695 $this->setNewtalk( false );
3697 // If there is a new, unseen, revision, use its timestamp
3699 ?
$title->getNextRevisionID( $oldid, Title
::GAID_FOR_UPDATE
)
3702 $this->setNewtalk( true, Revision
::newFromId( $nextid ) );
3707 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3711 if ( $this->isAnon() ) {
3712 // Nothing else to do...
3716 // Only update the timestamp if the page is being watched.
3717 // The query to find out if it is watched is cached both in memcached and per-invocation,
3718 // and when it does have to be executed, it can be on a replica DB
3719 // If this is the user's newtalk page, we always update the timestamp
3721 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3725 MediaWikiServices
::getInstance()->getWatchedItemStore()
3726 ->resetNotificationTimestamp( $this, $title, $force, $oldid );
3730 * Resets all of the given user's page-change notification timestamps.
3731 * If e-notif e-mails are on, they will receive notification mails on
3732 * the next change of any watched page.
3733 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3735 public function clearAllNotifications() {
3736 global $wgUseEnotif, $wgShowUpdatedMarker;
3737 // Do nothing if not allowed to edit the watchlist
3738 if ( wfReadOnly() ||
!$this->isAllowed( 'editmywatchlist' ) ) {
3742 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3743 $this->setNewtalk( false );
3747 $id = $this->getId();
3752 $dbw = wfGetDB( DB_MASTER
);
3753 $asOfTimes = array_unique( $dbw->selectFieldValues(
3755 'wl_notificationtimestamp',
3756 [ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ],
3758 [ 'ORDER BY' => 'wl_notificationtimestamp DESC', 'LIMIT' => 500 ]
3760 if ( !$asOfTimes ) {
3763 // Immediately update the most recent touched rows, which hopefully covers what
3764 // the user sees on the watchlist page before pressing "mark all pages visited"....
3767 [ 'wl_notificationtimestamp' => null ],
3768 [ 'wl_user' => $id, 'wl_notificationtimestamp' => $asOfTimes ],
3771 // ...and finish the older ones in a post-send update with lag checks...
3772 DeferredUpdates
::addUpdate( new AutoCommitUpdate(
3775 function () use ( $dbw, $id ) {
3776 global $wgUpdateRowsPerQuery;
3778 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
3779 $ticket = $lbFactory->getEmptyTransactionTicket( __METHOD__
);
3780 $asOfTimes = array_unique( $dbw->selectFieldValues(
3782 'wl_notificationtimestamp',
3783 [ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ],
3786 foreach ( array_chunk( $asOfTimes, $wgUpdateRowsPerQuery ) as $asOfTimeBatch ) {
3789 [ 'wl_notificationtimestamp' => null ],
3790 [ 'wl_user' => $id, 'wl_notificationtimestamp' => $asOfTimeBatch ],
3793 $lbFactory->commitAndWaitForReplication( __METHOD__
, $ticket );
3797 // We also need to clear here the "you have new message" notification for the own
3798 // user_talk page; it's cleared one page view later in WikiPage::doViewUpdates().
3802 * Compute experienced level based on edit count and registration date.
3804 * @return string 'newcomer', 'learner', or 'experienced'
3806 public function getExperienceLevel() {
3807 global $wgLearnerEdits,
3808 $wgExperiencedUserEdits,
3809 $wgLearnerMemberSince,
3810 $wgExperiencedUserMemberSince;
3812 if ( $this->isAnon() ) {
3816 $editCount = $this->getEditCount();
3817 $registration = $this->getRegistration();
3819 $learnerRegistration = wfTimestamp( TS_MW
, $now - $wgLearnerMemberSince * 86400 );
3820 $experiencedRegistration = wfTimestamp( TS_MW
, $now - $wgExperiencedUserMemberSince * 86400 );
3823 $editCount < $wgLearnerEdits ||
3824 $registration > $learnerRegistration
3828 $editCount > $wgExperiencedUserEdits &&
3829 $registration <= $experiencedRegistration
3831 return 'experienced';
3838 * Set a cookie on the user's client. Wrapper for
3839 * WebResponse::setCookie
3840 * @deprecated since 1.27
3841 * @param string $name Name of the cookie to set
3842 * @param string $value Value to set
3843 * @param int $exp Expiration time, as a UNIX time value;
3844 * if 0 or not specified, use the default $wgCookieExpiration
3845 * @param bool $secure
3846 * true: Force setting the secure attribute when setting the cookie
3847 * false: Force NOT setting the secure attribute when setting the cookie
3848 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3849 * @param array $params Array of options sent passed to WebResponse::setcookie()
3850 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3853 protected function setCookie(
3854 $name, $value, $exp = 0, $secure = null, $params = [], $request = null
3856 wfDeprecated( __METHOD__
, '1.27' );
3857 if ( $request === null ) {
3858 $request = $this->getRequest();
3860 $params['secure'] = $secure;
3861 $request->response()->setCookie( $name, $value, $exp, $params );
3865 * Clear a cookie on the user's client
3866 * @deprecated since 1.27
3867 * @param string $name Name of the cookie to clear
3868 * @param bool $secure
3869 * true: Force setting the secure attribute when setting the cookie
3870 * false: Force NOT setting the secure attribute when setting the cookie
3871 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3872 * @param array $params Array of options sent passed to WebResponse::setcookie()
3874 protected function clearCookie( $name, $secure = null, $params = [] ) {
3875 wfDeprecated( __METHOD__
, '1.27' );
3876 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3880 * Set an extended login cookie on the user's client. The expiry of the cookie
3881 * is controlled by the $wgExtendedLoginCookieExpiration configuration
3884 * @see User::setCookie
3886 * @deprecated since 1.27
3887 * @param string $name Name of the cookie to set
3888 * @param string $value Value to set
3889 * @param bool $secure
3890 * true: Force setting the secure attribute when setting the cookie
3891 * false: Force NOT setting the secure attribute when setting the cookie
3892 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3894 protected function setExtendedLoginCookie( $name, $value, $secure ) {
3895 global $wgExtendedLoginCookieExpiration, $wgCookieExpiration;
3897 wfDeprecated( __METHOD__
, '1.27' );
3900 $exp +
= $wgExtendedLoginCookieExpiration !== null
3901 ?
$wgExtendedLoginCookieExpiration
3902 : $wgCookieExpiration;
3904 $this->setCookie( $name, $value, $exp, $secure );
3908 * Persist this user's session (e.g. set cookies)
3910 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3912 * @param bool $secure Whether to force secure/insecure cookies or use default
3913 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3915 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3917 if ( 0 == $this->mId
) {
3921 $session = $this->getRequest()->getSession();
3922 if ( $request && $session->getRequest() !== $request ) {
3923 $session = $session->sessionWithRequest( $request );
3925 $delay = $session->delaySave();
3927 if ( !$session->getUser()->equals( $this ) ) {
3928 if ( !$session->canSetUser() ) {
3929 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3930 ->warning( __METHOD__
.
3931 ": Cannot save user \"$this\" to a user \"{$session->getUser()}\"'s immutable session"
3935 $session->setUser( $this );
3938 $session->setRememberUser( $rememberMe );
3939 if ( $secure !== null ) {
3940 $session->setForceHTTPS( $secure );
3943 $session->persist();
3945 ScopedCallback
::consume( $delay );
3949 * Log this user out.
3951 public function logout() {
3952 // Avoid PHP 7.1 warning of passing $this by reference
3954 if ( Hooks
::run( 'UserLogout', [ &$user ] ) ) {
3960 * Clear the user's session, and reset the instance cache.
3963 public function doLogout() {
3964 $session = $this->getRequest()->getSession();
3965 if ( !$session->canSetUser() ) {
3966 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3967 ->warning( __METHOD__
. ": Cannot log out of an immutable session" );
3968 $error = 'immutable';
3969 } elseif ( !$session->getUser()->equals( $this ) ) {
3970 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3971 ->warning( __METHOD__
.
3972 ": Cannot log user \"$this\" out of a user \"{$session->getUser()}\"'s session"
3974 // But we still may as well make this user object anon
3975 $this->clearInstanceCache( 'defaults' );
3976 $error = 'wronguser';
3978 $this->clearInstanceCache( 'defaults' );
3979 $delay = $session->delaySave();
3980 $session->unpersist(); // Clear cookies (T127436)
3981 $session->setLoggedOutTimestamp( time() );
3982 $session->setUser( new User
);
3983 $session->set( 'wsUserID', 0 ); // Other code expects this
3984 $session->resetAllTokens();
3985 ScopedCallback
::consume( $delay );
3988 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authevents' )->info( 'Logout', [
3989 'event' => 'logout',
3990 'successful' => $error === false,
3991 'status' => $error ?
: 'success',
3996 * Save this user's settings into the database.
3997 * @todo Only rarely do all these fields need to be set!
3999 public function saveSettings() {
4000 if ( wfReadOnly() ) {
4001 // @TODO: caller should deal with this instead!
4002 // This should really just be an exception.
4003 MWExceptionHandler
::logException( new DBExpectedError(
4005 "Could not update user with ID '{$this->mId}'; DB is read-only."
4011 if ( 0 == $this->mId
) {
4015 // Get a new user_touched that is higher than the old one.
4016 // This will be used for a CAS check as a last-resort safety
4017 // check against race conditions and replica DB lag.
4018 $newTouched = $this->newTouchedTimestamp();
4020 $dbw = wfGetDB( DB_MASTER
);
4021 $dbw->update( 'user',
4023 'user_name' => $this->mName
,
4024 'user_real_name' => $this->mRealName
,
4025 'user_email' => $this->mEmail
,
4026 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
4027 'user_touched' => $dbw->timestamp( $newTouched ),
4028 'user_token' => strval( $this->mToken
),
4029 'user_email_token' => $this->mEmailToken
,
4030 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
4031 ], $this->makeUpdateConditions( $dbw, [ /* WHERE */
4032 'user_id' => $this->mId
,
4036 if ( !$dbw->affectedRows() ) {
4037 // Maybe the problem was a missed cache update; clear it to be safe
4038 $this->clearSharedCache( 'refresh' );
4039 // User was changed in the meantime or loaded with stale data
4040 $from = ( $this->queryFlagsUsed
& self
::READ_LATEST
) ?
'master' : 'replica';
4041 throw new MWException(
4042 "CAS update failed on user_touched for user ID '{$this->mId}' (read from $from);" .
4043 " the version of the user to be saved is older than the current version."
4047 $this->mTouched
= $newTouched;
4048 $this->saveOptions();
4050 Hooks
::run( 'UserSaveSettings', [ $this ] );
4051 $this->clearSharedCache();
4052 $this->getUserPage()->invalidateCache();
4056 * If only this user's username is known, and it exists, return the user ID.
4058 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
4061 public function idForName( $flags = 0 ) {
4062 $s = trim( $this->getName() );
4067 $db = ( ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
)
4068 ?
wfGetDB( DB_MASTER
)
4069 : wfGetDB( DB_REPLICA
);
4071 $options = ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
)
4072 ?
[ 'LOCK IN SHARE MODE' ]
4075 $id = $db->selectField( 'user',
4076 'user_id', [ 'user_name' => $s ], __METHOD__
, $options );
4082 * Add a user to the database, return the user object
4084 * @param string $name Username to add
4085 * @param array $params Array of Strings Non-default parameters to save to
4086 * the database as user_* fields:
4087 * - email: The user's email address.
4088 * - email_authenticated: The email authentication timestamp.
4089 * - real_name: The user's real name.
4090 * - options: An associative array of non-default options.
4091 * - token: Random authentication token. Do not set.
4092 * - registration: Registration timestamp. Do not set.
4094 * @return User|null User object, or null if the username already exists.
4096 public static function createNew( $name, $params = [] ) {
4097 foreach ( [ 'password', 'newpassword', 'newpass_time', 'password_expires' ] as $field ) {
4098 if ( isset( $params[$field] ) ) {
4099 wfDeprecated( __METHOD__
. " with param '$field'", '1.27' );
4100 unset( $params[$field] );
4106 $user->setToken(); // init token
4107 if ( isset( $params['options'] ) ) {
4108 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
4109 unset( $params['options'] );
4111 $dbw = wfGetDB( DB_MASTER
);
4112 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
4114 $noPass = PasswordFactory
::newInvalidPassword()->toString();
4117 'user_id' => $seqVal,
4118 'user_name' => $name,
4119 'user_password' => $noPass,
4120 'user_newpassword' => $noPass,
4121 'user_email' => $user->mEmail
,
4122 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
4123 'user_real_name' => $user->mRealName
,
4124 'user_token' => strval( $user->mToken
),
4125 'user_registration' => $dbw->timestamp( $user->mRegistration
),
4126 'user_editcount' => 0,
4127 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
4129 foreach ( $params as $name => $value ) {
4130 $fields["user_$name"] = $value;
4132 $dbw->insert( 'user', $fields, __METHOD__
, [ 'IGNORE' ] );
4133 if ( $dbw->affectedRows() ) {
4134 $newUser = self
::newFromId( $dbw->insertId() );
4142 * Add this existing user object to the database. If the user already
4143 * exists, a fatal status object is returned, and the user object is
4144 * initialised with the data from the database.
4146 * Previously, this function generated a DB error due to a key conflict
4147 * if the user already existed. Many extension callers use this function
4148 * in code along the lines of:
4150 * $user = User::newFromName( $name );
4151 * if ( !$user->isLoggedIn() ) {
4152 * $user->addToDatabase();
4154 * // do something with $user...
4156 * However, this was vulnerable to a race condition (T18020). By
4157 * initialising the user object if the user exists, we aim to support this
4158 * calling sequence as far as possible.
4160 * Note that if the user exists, this function will acquire a write lock,
4161 * so it is still advisable to make the call conditional on isLoggedIn(),
4162 * and to commit the transaction after calling.
4164 * @throws MWException
4167 public function addToDatabase() {
4169 if ( !$this->mToken
) {
4170 $this->setToken(); // init token
4173 if ( !is_string( $this->mName
) ) {
4174 throw new RuntimeException( "User name field is not set." );
4177 $this->mTouched
= $this->newTouchedTimestamp();
4179 $noPass = PasswordFactory
::newInvalidPassword()->toString();
4181 $dbw = wfGetDB( DB_MASTER
);
4182 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
4183 $dbw->insert( 'user',
4185 'user_id' => $seqVal,
4186 'user_name' => $this->mName
,
4187 'user_password' => $noPass,
4188 'user_newpassword' => $noPass,
4189 'user_email' => $this->mEmail
,
4190 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
4191 'user_real_name' => $this->mRealName
,
4192 'user_token' => strval( $this->mToken
),
4193 'user_registration' => $dbw->timestamp( $this->mRegistration
),
4194 'user_editcount' => 0,
4195 'user_touched' => $dbw->timestamp( $this->mTouched
),
4199 if ( !$dbw->affectedRows() ) {
4200 // Use locking reads to bypass any REPEATABLE-READ snapshot.
4201 $this->mId
= $dbw->selectField(
4204 [ 'user_name' => $this->mName
],
4206 [ 'LOCK IN SHARE MODE' ]
4210 if ( $this->loadFromDatabase( self
::READ_LOCKING
) ) {
4215 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
4216 "to insert user '{$this->mName}' row, but it was not present in select!" );
4218 return Status
::newFatal( 'userexists' );
4220 $this->mId
= $dbw->insertId();
4221 self
::$idCacheByName[$this->mName
] = $this->mId
;
4223 // Clear instance cache other than user table data, which is already accurate
4224 $this->clearInstanceCache();
4226 $this->saveOptions();
4227 return Status
::newGood();
4231 * If this user is logged-in and blocked,
4232 * block any IP address they've successfully logged in from.
4233 * @return bool A block was spread
4235 public function spreadAnyEditBlock() {
4236 if ( $this->isLoggedIn() && $this->isBlocked() ) {
4237 return $this->spreadBlock();
4244 * If this (non-anonymous) user is blocked,
4245 * block the IP address they've successfully logged in from.
4246 * @return bool A block was spread
4248 protected function spreadBlock() {
4249 wfDebug( __METHOD__
. "()\n" );
4251 if ( $this->mId
== 0 ) {
4255 $userblock = Block
::newFromTarget( $this->getName() );
4256 if ( !$userblock ) {
4260 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
4264 * Get whether the user is explicitly blocked from account creation.
4265 * @return bool|Block
4267 public function isBlockedFromCreateAccount() {
4268 $this->getBlockedStatus();
4269 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
4270 return $this->mBlock
;
4273 # T15611: if the IP address the user is trying to create an account from is
4274 # blocked with createaccount disabled, prevent new account creation there even
4275 # when the user is logged in
4276 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
4277 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
4279 return $this->mBlockedFromCreateAccount
instanceof Block
4280 && $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
4281 ?
$this->mBlockedFromCreateAccount
4286 * Get whether the user is blocked from using Special:Emailuser.
4289 public function isBlockedFromEmailuser() {
4290 $this->getBlockedStatus();
4291 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
4295 * Get whether the user is allowed to create an account.
4298 public function isAllowedToCreateAccount() {
4299 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
4303 * Get this user's personal page title.
4305 * @return Title User's personal page title
4307 public function getUserPage() {
4308 return Title
::makeTitle( NS_USER
, $this->getName() );
4312 * Get this user's talk page title.
4314 * @return Title User's talk page title
4316 public function getTalkPage() {
4317 $title = $this->getUserPage();
4318 return $title->getTalkPage();
4322 * Determine whether the user is a newbie. Newbies are either
4323 * anonymous IPs, or the most recently created accounts.
4326 public function isNewbie() {
4327 return !$this->isAllowed( 'autoconfirmed' );
4331 * Check to see if the given clear-text password is one of the accepted passwords
4332 * @deprecated since 1.27, use AuthManager instead
4333 * @param string $password User password
4334 * @return bool True if the given password is correct, otherwise False
4336 public function checkPassword( $password ) {
4337 $manager = AuthManager
::singleton();
4338 $reqs = AuthenticationRequest
::loadRequestsFromSubmission(
4339 $manager->getAuthenticationRequests( AuthManager
::ACTION_LOGIN
),
4341 'username' => $this->getName(),
4342 'password' => $password,
4345 $res = AuthManager
::singleton()->beginAuthentication( $reqs, 'null:' );
4346 switch ( $res->status
) {
4347 case AuthenticationResponse
::PASS
:
4349 case AuthenticationResponse
::FAIL
:
4350 // Hope it's not a PreAuthenticationProvider that failed...
4351 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
4352 ->info( __METHOD__
. ': Authentication failed: ' . $res->message
->plain() );
4355 throw new BadMethodCallException(
4356 'AuthManager returned a response unsupported by ' . __METHOD__
4362 * Check if the given clear-text password matches the temporary password
4363 * sent by e-mail for password reset operations.
4365 * @deprecated since 1.27, use AuthManager instead
4366 * @param string $plaintext
4367 * @return bool True if matches, false otherwise
4369 public function checkTemporaryPassword( $plaintext ) {
4370 // Can't check the temporary password individually.
4371 return $this->checkPassword( $plaintext );
4375 * Initialize (if necessary) and return a session token value
4376 * which can be used in edit forms to show that the user's
4377 * login credentials aren't being hijacked with a foreign form
4381 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4382 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4383 * @return MediaWiki\Session\Token The new edit token
4385 public function getEditTokenObject( $salt = '', $request = null ) {
4386 if ( $this->isAnon() ) {
4387 return new LoggedOutEditToken();
4391 $request = $this->getRequest();
4393 return $request->getSession()->getToken( $salt );
4397 * Initialize (if necessary) and return a session token value
4398 * which can be used in edit forms to show that the user's
4399 * login credentials aren't being hijacked with a foreign form
4402 * The $salt for 'edit' and 'csrf' tokens is the default (empty string).
4405 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4406 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4407 * @return string The new edit token
4409 public function getEditToken( $salt = '', $request = null ) {
4410 return $this->getEditTokenObject( $salt, $request )->toString();
4414 * Get the embedded timestamp from a token.
4415 * @deprecated since 1.27, use \MediaWiki\Session\Token::getTimestamp instead.
4416 * @param string $val Input token
4419 public static function getEditTokenTimestamp( $val ) {
4420 wfDeprecated( __METHOD__
, '1.27' );
4421 return MediaWiki\Session\Token
::getTimestamp( $val );
4425 * Check given value against the token value stored in the session.
4426 * A match should confirm that the form was submitted from the
4427 * user's own login session, not a form submission from a third-party
4430 * @param string $val Input value to compare
4431 * @param string $salt Optional function-specific data for hashing
4432 * @param WebRequest|null $request Object to use or null to use $wgRequest
4433 * @param int $maxage Fail tokens older than this, in seconds
4434 * @return bool Whether the token matches
4436 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4437 return $this->getEditTokenObject( $salt, $request )->match( $val, $maxage );
4441 * Check given value against the token value stored in the session,
4442 * ignoring the suffix.
4444 * @param string $val Input value to compare
4445 * @param string $salt Optional function-specific data for hashing
4446 * @param WebRequest|null $request Object to use or null to use $wgRequest
4447 * @param int $maxage Fail tokens older than this, in seconds
4448 * @return bool Whether the token matches
4450 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4451 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . Token
::SUFFIX
;
4452 return $this->matchEditToken( $val, $salt, $request, $maxage );
4456 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4457 * mail to the user's given address.
4459 * @param string $type Message to send, either "created", "changed" or "set"
4462 public function sendConfirmationMail( $type = 'created' ) {
4464 $expiration = null; // gets passed-by-ref and defined in next line.
4465 $token = $this->confirmationToken( $expiration );
4466 $url = $this->confirmationTokenUrl( $token );
4467 $invalidateURL = $this->invalidationTokenUrl( $token );
4468 $this->saveSettings();
4470 if ( $type == 'created' ||
$type === false ) {
4471 $message = 'confirmemail_body';
4472 } elseif ( $type === true ) {
4473 $message = 'confirmemail_body_changed';
4475 // Messages: confirmemail_body_changed, confirmemail_body_set
4476 $message = 'confirmemail_body_' . $type;
4479 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4480 wfMessage( $message,
4481 $this->getRequest()->getIP(),
4484 $wgLang->userTimeAndDate( $expiration, $this ),
4486 $wgLang->userDate( $expiration, $this ),
4487 $wgLang->userTime( $expiration, $this ) )->text() );
4491 * Send an e-mail to this user's account. Does not check for
4492 * confirmed status or validity.
4494 * @param string $subject Message subject
4495 * @param string $body Message body
4496 * @param User|null $from Optional sending user; if unspecified, default
4497 * $wgPasswordSender will be used.
4498 * @param string $replyto Reply-To address
4501 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4502 global $wgPasswordSender;
4504 if ( $from instanceof User
) {
4505 $sender = MailAddress
::newFromUser( $from );
4507 $sender = new MailAddress( $wgPasswordSender,
4508 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4510 $to = MailAddress
::newFromUser( $this );
4512 return UserMailer
::send( $to, $sender, $subject, $body, [
4513 'replyTo' => $replyto,
4518 * Generate, store, and return a new e-mail confirmation code.
4519 * A hash (unsalted, since it's used as a key) is stored.
4521 * @note Call saveSettings() after calling this function to commit
4522 * this change to the database.
4524 * @param string &$expiration Accepts the expiration time
4525 * @return string New token
4527 protected function confirmationToken( &$expiration ) {
4528 global $wgUserEmailConfirmationTokenExpiry;
4530 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4531 $expiration = wfTimestamp( TS_MW
, $expires );
4533 $token = MWCryptRand
::generateHex( 32 );
4534 $hash = md5( $token );
4535 $this->mEmailToken
= $hash;
4536 $this->mEmailTokenExpires
= $expiration;
4541 * Return a URL the user can use to confirm their email address.
4542 * @param string $token Accepts the email confirmation token
4543 * @return string New token URL
4545 protected function confirmationTokenUrl( $token ) {
4546 return $this->getTokenUrl( 'ConfirmEmail', $token );
4550 * Return a URL the user can use to invalidate their email address.
4551 * @param string $token Accepts the email confirmation token
4552 * @return string New token URL
4554 protected function invalidationTokenUrl( $token ) {
4555 return $this->getTokenUrl( 'InvalidateEmail', $token );
4559 * Internal function to format the e-mail validation/invalidation URLs.
4560 * This uses a quickie hack to use the
4561 * hardcoded English names of the Special: pages, for ASCII safety.
4563 * @note Since these URLs get dropped directly into emails, using the
4564 * short English names avoids insanely long URL-encoded links, which
4565 * also sometimes can get corrupted in some browsers/mailers
4566 * (T8957 with Gmail and Internet Explorer).
4568 * @param string $page Special page
4569 * @param string $token Token
4570 * @return string Formatted URL
4572 protected function getTokenUrl( $page, $token ) {
4573 // Hack to bypass localization of 'Special:'
4574 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4575 return $title->getCanonicalURL();
4579 * Mark the e-mail address confirmed.
4581 * @note Call saveSettings() after calling this function to commit the change.
4585 public function confirmEmail() {
4586 // Check if it's already confirmed, so we don't touch the database
4587 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4588 if ( !$this->isEmailConfirmed() ) {
4589 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4590 Hooks
::run( 'ConfirmEmailComplete', [ $this ] );
4596 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4597 * address if it was already confirmed.
4599 * @note Call saveSettings() after calling this function to commit the change.
4600 * @return bool Returns true
4602 public function invalidateEmail() {
4604 $this->mEmailToken
= null;
4605 $this->mEmailTokenExpires
= null;
4606 $this->setEmailAuthenticationTimestamp( null );
4608 Hooks
::run( 'InvalidateEmailComplete', [ $this ] );
4613 * Set the e-mail authentication timestamp.
4614 * @param string $timestamp TS_MW timestamp
4616 public function setEmailAuthenticationTimestamp( $timestamp ) {
4618 $this->mEmailAuthenticated
= $timestamp;
4619 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
4623 * Is this user allowed to send e-mails within limits of current
4624 * site configuration?
4627 public function canSendEmail() {
4628 global $wgEnableEmail, $wgEnableUserEmail;
4629 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4632 $canSend = $this->isEmailConfirmed();
4633 // Avoid PHP 7.1 warning of passing $this by reference
4635 Hooks
::run( 'UserCanSendEmail', [ &$user, &$canSend ] );
4640 * Is this user allowed to receive e-mails within limits of current
4641 * site configuration?
4644 public function canReceiveEmail() {
4645 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4649 * Is this user's e-mail address valid-looking and confirmed within
4650 * limits of the current site configuration?
4652 * @note If $wgEmailAuthentication is on, this may require the user to have
4653 * confirmed their address by returning a code or using a password
4654 * sent to the address from the wiki.
4658 public function isEmailConfirmed() {
4659 global $wgEmailAuthentication;
4661 // Avoid PHP 7.1 warning of passing $this by reference
4664 if ( Hooks
::run( 'EmailConfirmed', [ &$user, &$confirmed ] ) ) {
4665 if ( $this->isAnon() ) {
4668 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4671 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4681 * Check whether there is an outstanding request for e-mail confirmation.
4684 public function isEmailConfirmationPending() {
4685 global $wgEmailAuthentication;
4686 return $wgEmailAuthentication &&
4687 !$this->isEmailConfirmed() &&
4688 $this->mEmailToken
&&
4689 $this->mEmailTokenExpires
> wfTimestamp();
4693 * Get the timestamp of account creation.
4695 * @return string|bool|null Timestamp of account creation, false for
4696 * non-existent/anonymous user accounts, or null if existing account
4697 * but information is not in database.
4699 public function getRegistration() {
4700 if ( $this->isAnon() ) {
4704 return $this->mRegistration
;
4708 * Get the timestamp of the first edit
4710 * @return string|bool Timestamp of first edit, or false for
4711 * non-existent/anonymous user accounts.
4713 public function getFirstEditTimestamp() {
4714 if ( $this->getId() == 0 ) {
4715 return false; // anons
4717 $dbr = wfGetDB( DB_REPLICA
);
4718 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4719 [ 'rev_user' => $this->getId() ],
4721 [ 'ORDER BY' => 'rev_timestamp ASC' ]
4724 return false; // no edits
4726 return wfTimestamp( TS_MW
, $time );
4730 * Get the permissions associated with a given list of groups
4732 * @param array $groups Array of Strings List of internal group names
4733 * @return array Array of Strings List of permission key names for given groups combined
4735 public static function getGroupPermissions( $groups ) {
4736 global $wgGroupPermissions, $wgRevokePermissions;
4738 // grant every granted permission first
4739 foreach ( $groups as $group ) {
4740 if ( isset( $wgGroupPermissions[$group] ) ) {
4741 $rights = array_merge( $rights,
4742 // array_filter removes empty items
4743 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4746 // now revoke the revoked permissions
4747 foreach ( $groups as $group ) {
4748 if ( isset( $wgRevokePermissions[$group] ) ) {
4749 $rights = array_diff( $rights,
4750 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4753 return array_unique( $rights );
4757 * Get all the groups who have a given permission
4759 * @param string $role Role to check
4760 * @return array Array of Strings List of internal group names with the given permission
4762 public static function getGroupsWithPermission( $role ) {
4763 global $wgGroupPermissions;
4764 $allowedGroups = [];
4765 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4766 if ( self
::groupHasPermission( $group, $role ) ) {
4767 $allowedGroups[] = $group;
4770 return $allowedGroups;
4774 * Check, if the given group has the given permission
4776 * If you're wanting to check whether all users have a permission, use
4777 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4781 * @param string $group Group to check
4782 * @param string $role Role to check
4785 public static function groupHasPermission( $group, $role ) {
4786 global $wgGroupPermissions, $wgRevokePermissions;
4787 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4788 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4792 * Check if all users may be assumed to have the given permission
4794 * We generally assume so if the right is granted to '*' and isn't revoked
4795 * on any group. It doesn't attempt to take grants or other extension
4796 * limitations on rights into account in the general case, though, as that
4797 * would require it to always return false and defeat the purpose.
4798 * Specifically, session-based rights restrictions (such as OAuth or bot
4799 * passwords) are applied based on the current session.
4802 * @param string $right Right to check
4805 public static function isEveryoneAllowed( $right ) {
4806 global $wgGroupPermissions, $wgRevokePermissions;
4809 // Use the cached results, except in unit tests which rely on
4810 // being able change the permission mid-request
4811 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4812 return $cache[$right];
4815 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4816 $cache[$right] = false;
4820 // If it's revoked anywhere, then everyone doesn't have it
4821 foreach ( $wgRevokePermissions as $rights ) {
4822 if ( isset( $rights[$right] ) && $rights[$right] ) {
4823 $cache[$right] = false;
4828 // Remove any rights that aren't allowed to the global-session user,
4829 // unless there are no sessions for this endpoint.
4830 if ( !defined( 'MW_NO_SESSION' ) ) {
4831 $allowedRights = SessionManager
::getGlobalSession()->getAllowedUserRights();
4832 if ( $allowedRights !== null && !in_array( $right, $allowedRights, true ) ) {
4833 $cache[$right] = false;
4838 // Allow extensions to say false
4839 if ( !Hooks
::run( 'UserIsEveryoneAllowed', [ $right ] ) ) {
4840 $cache[$right] = false;
4844 $cache[$right] = true;
4849 * Get the localized descriptive name for a group, if it exists
4850 * @deprecated since 1.29 Use UserGroupMembership::getGroupName instead
4852 * @param string $group Internal group name
4853 * @return string Localized descriptive group name
4855 public static function getGroupName( $group ) {
4856 wfDeprecated( __METHOD__
, '1.29' );
4857 return UserGroupMembership
::getGroupName( $group );
4861 * Get the localized descriptive name for a member of a group, if it exists
4862 * @deprecated since 1.29 Use UserGroupMembership::getGroupMemberName instead
4864 * @param string $group Internal group name
4865 * @param string $username Username for gender (since 1.19)
4866 * @return string Localized name for group member
4868 public static function getGroupMember( $group, $username = '#' ) {
4869 wfDeprecated( __METHOD__
, '1.29' );
4870 return UserGroupMembership
::getGroupMemberName( $group, $username );
4874 * Return the set of defined explicit groups.
4875 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4876 * are not included, as they are defined automatically, not in the database.
4877 * @return array Array of internal group names
4879 public static function getAllGroups() {
4880 global $wgGroupPermissions, $wgRevokePermissions;
4882 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4883 self
::getImplicitGroups()
4888 * Get a list of all available permissions.
4889 * @return string[] Array of permission names
4891 public static function getAllRights() {
4892 if ( self
::$mAllRights === false ) {
4893 global $wgAvailableRights;
4894 if ( count( $wgAvailableRights ) ) {
4895 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
4897 self
::$mAllRights = self
::$mCoreRights;
4899 Hooks
::run( 'UserGetAllRights', [ &self
::$mAllRights ] );
4901 return self
::$mAllRights;
4905 * Get a list of implicit groups
4906 * @return array Array of Strings Array of internal group names
4908 public static function getImplicitGroups() {
4909 global $wgImplicitGroups;
4911 $groups = $wgImplicitGroups;
4912 # Deprecated, use $wgImplicitGroups instead
4913 Hooks
::run( 'UserGetImplicitGroups', [ &$groups ], '1.25' );
4919 * Get the title of a page describing a particular group
4920 * @deprecated since 1.29 Use UserGroupMembership::getGroupPage instead
4922 * @param string $group Internal group name
4923 * @return Title|bool Title of the page if it exists, false otherwise
4925 public static function getGroupPage( $group ) {
4926 wfDeprecated( __METHOD__
, '1.29' );
4927 return UserGroupMembership
::getGroupPage( $group );
4931 * Create a link to the group in HTML, if available;
4932 * else return the group name.
4933 * @deprecated since 1.29 Use UserGroupMembership::getLink instead, or
4934 * make the link yourself if you need custom text
4936 * @param string $group Internal name of the group
4937 * @param string $text The text of the link
4938 * @return string HTML link to the group
4940 public static function makeGroupLinkHTML( $group, $text = '' ) {
4941 wfDeprecated( __METHOD__
, '1.29' );
4943 if ( $text == '' ) {
4944 $text = UserGroupMembership
::getGroupName( $group );
4946 $title = UserGroupMembership
::getGroupPage( $group );
4948 return MediaWikiServices
::getInstance()
4949 ->getLinkRenderer()->makeLink( $title, $text );
4951 return htmlspecialchars( $text );
4956 * Create a link to the group in Wikitext, if available;
4957 * else return the group name.
4958 * @deprecated since 1.29 Use UserGroupMembership::getLink instead, or
4959 * make the link yourself if you need custom text
4961 * @param string $group Internal name of the group
4962 * @param string $text The text of the link
4963 * @return string Wikilink to the group
4965 public static function makeGroupLinkWiki( $group, $text = '' ) {
4966 wfDeprecated( __METHOD__
, '1.29' );
4968 if ( $text == '' ) {
4969 $text = UserGroupMembership
::getGroupName( $group );
4971 $title = UserGroupMembership
::getGroupPage( $group );
4973 $page = $title->getFullText();
4974 return "[[$page|$text]]";
4981 * Returns an array of the groups that a particular group can add/remove.
4983 * @param string $group The group to check for whether it can add/remove
4984 * @return array Array( 'add' => array( addablegroups ),
4985 * 'remove' => array( removablegroups ),
4986 * 'add-self' => array( addablegroups to self),
4987 * 'remove-self' => array( removable groups from self) )
4989 public static function changeableByGroup( $group ) {
4990 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4999 if ( empty( $wgAddGroups[$group] ) ) {
5000 // Don't add anything to $groups
5001 } elseif ( $wgAddGroups[$group] === true ) {
5002 // You get everything
5003 $groups['add'] = self
::getAllGroups();
5004 } elseif ( is_array( $wgAddGroups[$group] ) ) {
5005 $groups['add'] = $wgAddGroups[$group];
5008 // Same thing for remove
5009 if ( empty( $wgRemoveGroups[$group] ) ) {
5011 } elseif ( $wgRemoveGroups[$group] === true ) {
5012 $groups['remove'] = self
::getAllGroups();
5013 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
5014 $groups['remove'] = $wgRemoveGroups[$group];
5017 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
5018 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
5019 foreach ( $wgGroupsAddToSelf as $key => $value ) {
5020 if ( is_int( $key ) ) {
5021 $wgGroupsAddToSelf['user'][] = $value;
5026 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
5027 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
5028 if ( is_int( $key ) ) {
5029 $wgGroupsRemoveFromSelf['user'][] = $value;
5034 // Now figure out what groups the user can add to him/herself
5035 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
5037 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
5038 // No idea WHY this would be used, but it's there
5039 $groups['add-self'] = self
::getAllGroups();
5040 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
5041 $groups['add-self'] = $wgGroupsAddToSelf[$group];
5044 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
5046 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
5047 $groups['remove-self'] = self
::getAllGroups();
5048 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
5049 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
5056 * Returns an array of groups that this user can add and remove
5057 * @return array Array( 'add' => array( addablegroups ),
5058 * 'remove' => array( removablegroups ),
5059 * 'add-self' => array( addablegroups to self),
5060 * 'remove-self' => array( removable groups from self) )
5062 public function changeableGroups() {
5063 if ( $this->isAllowed( 'userrights' ) ) {
5064 // This group gives the right to modify everything (reverse-
5065 // compatibility with old "userrights lets you change
5067 // Using array_merge to make the groups reindexed
5068 $all = array_merge( self
::getAllGroups() );
5077 // Okay, it's not so simple, we will have to go through the arrays
5084 $addergroups = $this->getEffectiveGroups();
5086 foreach ( $addergroups as $addergroup ) {
5087 $groups = array_merge_recursive(
5088 $groups, $this->changeableByGroup( $addergroup )
5090 $groups['add'] = array_unique( $groups['add'] );
5091 $groups['remove'] = array_unique( $groups['remove'] );
5092 $groups['add-self'] = array_unique( $groups['add-self'] );
5093 $groups['remove-self'] = array_unique( $groups['remove-self'] );
5099 * Deferred version of incEditCountImmediate()
5101 * This function, rather than incEditCountImmediate(), should be used for
5102 * most cases as it avoids potential deadlocks caused by concurrent editing.
5104 public function incEditCount() {
5105 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle(
5107 $this->incEditCountImmediate();
5114 * Increment the user's edit-count field.
5115 * Will have no effect for anonymous users.
5118 public function incEditCountImmediate() {
5119 if ( $this->isAnon() ) {
5123 $dbw = wfGetDB( DB_MASTER
);
5124 // No rows will be "affected" if user_editcount is NULL
5127 [ 'user_editcount=user_editcount+1' ],
5128 [ 'user_id' => $this->getId(), 'user_editcount IS NOT NULL' ],
5131 // Lazy initialization check...
5132 if ( $dbw->affectedRows() == 0 ) {
5133 // Now here's a goddamn hack...
5134 $dbr = wfGetDB( DB_REPLICA
);
5135 if ( $dbr !== $dbw ) {
5136 // If we actually have a replica DB server, the count is
5137 // at least one behind because the current transaction
5138 // has not been committed and replicated.
5139 $this->mEditCount
= $this->initEditCount( 1 );
5141 // But if DB_REPLICA is selecting the master, then the
5142 // count we just read includes the revision that was
5143 // just added in the working transaction.
5144 $this->mEditCount
= $this->initEditCount();
5147 if ( $this->mEditCount
=== null ) {
5148 $this->getEditCount();
5149 $dbr = wfGetDB( DB_REPLICA
);
5150 $this->mEditCount +
= ( $dbr !== $dbw ) ?
1 : 0;
5152 $this->mEditCount++
;
5155 // Edit count in user cache too
5156 $this->invalidateCache();
5160 * Initialize user_editcount from data out of the revision table
5162 * @param int $add Edits to add to the count from the revision table
5163 * @return int Number of edits
5165 protected function initEditCount( $add = 0 ) {
5166 // Pull from a replica DB to be less cruel to servers
5167 // Accuracy isn't the point anyway here
5168 $dbr = wfGetDB( DB_REPLICA
);
5169 $count = (int)$dbr->selectField(
5172 [ 'rev_user' => $this->getId() ],
5175 $count = $count +
$add;
5177 $dbw = wfGetDB( DB_MASTER
);
5180 [ 'user_editcount' => $count ],
5181 [ 'user_id' => $this->getId() ],
5189 * Get the description of a given right
5192 * @param string $right Right to query
5193 * @return string Localized description of the right
5195 public static function getRightDescription( $right ) {
5196 $key = "right-$right";
5197 $msg = wfMessage( $key );
5198 return $msg->isDisabled() ?
$right : $msg->text();
5202 * Get the name of a given grant
5205 * @param string $grant Grant to query
5206 * @return string Localized name of the grant
5208 public static function getGrantName( $grant ) {
5209 $key = "grant-$grant";
5210 $msg = wfMessage( $key );
5211 return $msg->isDisabled() ?
$grant : $msg->text();
5215 * Add a newuser log entry for this user.
5216 * Before 1.19 the return value was always true.
5218 * @deprecated since 1.27, AuthManager handles logging
5219 * @param string|bool $action Account creation type.
5220 * - String, one of the following values:
5221 * - 'create' for an anonymous user creating an account for himself.
5222 * This will force the action's performer to be the created user itself,
5223 * no matter the value of $wgUser
5224 * - 'create2' for a logged in user creating an account for someone else
5225 * - 'byemail' when the created user will receive its password by e-mail
5226 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
5227 * - Boolean means whether the account was created by e-mail (deprecated):
5228 * - true will be converted to 'byemail'
5229 * - false will be converted to 'create' if this object is the same as
5230 * $wgUser and to 'create2' otherwise
5231 * @param string $reason User supplied reason
5234 public function addNewUserLogEntry( $action = false, $reason = '' ) {
5235 return true; // disabled
5239 * Add an autocreate newuser log entry for this user
5240 * Used by things like CentralAuth and perhaps other authplugins.
5241 * Consider calling addNewUserLogEntry() directly instead.
5243 * @deprecated since 1.27, AuthManager handles logging
5246 public function addNewUserLogEntryAutoCreate() {
5247 $this->addNewUserLogEntry( 'autocreate' );
5253 * Load the user options either from cache, the database or an array
5255 * @param array $data Rows for the current user out of the user_properties table
5257 protected function loadOptions( $data = null ) {
5262 if ( $this->mOptionsLoaded
) {
5266 $this->mOptions
= self
::getDefaultOptions();
5268 if ( !$this->getId() ) {
5269 // For unlogged-in users, load language/variant options from request.
5270 // There's no need to do it for logged-in users: they can set preferences,
5271 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5272 // so don't override user's choice (especially when the user chooses site default).
5273 $variant = $wgContLang->getDefaultVariant();
5274 $this->mOptions
['variant'] = $variant;
5275 $this->mOptions
['language'] = $variant;
5276 $this->mOptionsLoaded
= true;
5280 // Maybe load from the object
5281 if ( !is_null( $this->mOptionOverrides
) ) {
5282 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5283 foreach ( $this->mOptionOverrides
as $key => $value ) {
5284 $this->mOptions
[$key] = $value;
5287 if ( !is_array( $data ) ) {
5288 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5289 // Load from database
5290 $dbr = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
5291 ?
wfGetDB( DB_MASTER
)
5292 : wfGetDB( DB_REPLICA
);
5294 $res = $dbr->select(
5296 [ 'up_property', 'up_value' ],
5297 [ 'up_user' => $this->getId() ],
5301 $this->mOptionOverrides
= [];
5303 foreach ( $res as $row ) {
5304 // Convert '0' to 0. PHP's boolean conversion considers them both
5305 // false, but e.g. JavaScript considers the former as true.
5306 // @todo: T54542 Somehow determine the desired type (string/int/bool)
5307 // and convert all values here.
5308 if ( $row->up_value
=== '0' ) {
5311 $data[$row->up_property
] = $row->up_value
;
5314 foreach ( $data as $property => $value ) {
5315 $this->mOptionOverrides
[$property] = $value;
5316 $this->mOptions
[$property] = $value;
5320 $this->mOptionsLoaded
= true;
5322 Hooks
::run( 'UserLoadOptions', [ $this, &$this->mOptions
] );
5326 * Saves the non-default options for this user, as previously set e.g. via
5327 * setOption(), in the database's "user_properties" (preferences) table.
5328 * Usually used via saveSettings().
5330 protected function saveOptions() {
5331 $this->loadOptions();
5333 // Not using getOptions(), to keep hidden preferences in database
5334 $saveOptions = $this->mOptions
;
5336 // Allow hooks to abort, for instance to save to a global profile.
5337 // Reset options to default state before saving.
5338 if ( !Hooks
::run( 'UserSaveOptions', [ $this, &$saveOptions ] ) ) {
5342 $userId = $this->getId();
5344 $insert_rows = []; // all the new preference rows
5345 foreach ( $saveOptions as $key => $value ) {
5346 // Don't bother storing default values
5347 $defaultOption = self
::getDefaultOption( $key );
5348 if ( ( $defaultOption === null && $value !== false && $value !== null )
5349 ||
$value != $defaultOption
5352 'up_user' => $userId,
5353 'up_property' => $key,
5354 'up_value' => $value,
5359 $dbw = wfGetDB( DB_MASTER
);
5361 $res = $dbw->select( 'user_properties',
5362 [ 'up_property', 'up_value' ], [ 'up_user' => $userId ], __METHOD__
);
5364 // Find prior rows that need to be removed or updated. These rows will
5365 // all be deleted (the latter so that INSERT IGNORE applies the new values).
5367 foreach ( $res as $row ) {
5368 if ( !isset( $saveOptions[$row->up_property
] )
5369 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
5371 $keysDelete[] = $row->up_property
;
5375 if ( count( $keysDelete ) ) {
5376 // Do the DELETE by PRIMARY KEY for prior rows.
5377 // In the past a very large portion of calls to this function are for setting
5378 // 'rememberpassword' for new accounts (a preference that has since been removed).
5379 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5380 // caused gap locks on [max user ID,+infinity) which caused high contention since
5381 // updates would pile up on each other as they are for higher (newer) user IDs.
5382 // It might not be necessary these days, but it shouldn't hurt either.
5383 $dbw->delete( 'user_properties',
5384 [ 'up_user' => $userId, 'up_property' => $keysDelete ], __METHOD__
);
5386 // Insert the new preference rows
5387 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, [ 'IGNORE' ] );
5391 * Lazily instantiate and return a factory object for making passwords
5393 * @deprecated since 1.27, create a PasswordFactory directly instead
5394 * @return PasswordFactory
5396 public static function getPasswordFactory() {
5397 wfDeprecated( __METHOD__
, '1.27' );
5398 $ret = new PasswordFactory();
5399 $ret->init( RequestContext
::getMain()->getConfig() );
5404 * Provide an array of HTML5 attributes to put on an input element
5405 * intended for the user to enter a new password. This may include
5406 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
5408 * Do *not* use this when asking the user to enter his current password!
5409 * Regardless of configuration, users may have invalid passwords for whatever
5410 * reason (e.g., they were set before requirements were tightened up).
5411 * Only use it when asking for a new password, like on account creation or
5414 * Obviously, you still need to do server-side checking.
5416 * NOTE: A combination of bugs in various browsers means that this function
5417 * actually just returns array() unconditionally at the moment. May as
5418 * well keep it around for when the browser bugs get fixed, though.
5420 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
5422 * @deprecated since 1.27
5423 * @return array Array of HTML attributes suitable for feeding to
5424 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
5425 * That will get confused by the boolean attribute syntax used.)
5427 public static function passwordChangeInputAttribs() {
5428 global $wgMinimalPasswordLength;
5430 if ( $wgMinimalPasswordLength == 0 ) {
5434 # Note that the pattern requirement will always be satisfied if the
5435 # input is empty, so we need required in all cases.
5437 # @todo FIXME: T25769: This needs to not claim the password is required
5438 # if e-mail confirmation is being used. Since HTML5 input validation
5439 # is b0rked anyway in some browsers, just return nothing. When it's
5440 # re-enabled, fix this code to not output required for e-mail
5442 # $ret = array( 'required' );
5445 # We can't actually do this right now, because Opera 9.6 will print out
5446 # the entered password visibly in its error message! When other
5447 # browsers add support for this attribute, or Opera fixes its support,
5448 # we can add support with a version check to avoid doing this on Opera
5449 # versions where it will be a problem. Reported to Opera as
5450 # DSK-262266, but they don't have a public bug tracker for us to follow.
5452 if ( $wgMinimalPasswordLength > 1 ) {
5453 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
5454 $ret['title'] = wfMessage( 'passwordtooshort' )
5455 ->numParams( $wgMinimalPasswordLength )->text();
5463 * Return the list of user fields that should be selected to create
5464 * a new user object.
5467 public static function selectFields() {
5475 'user_email_authenticated',
5477 'user_email_token_expires',
5478 'user_registration',
5484 * Factory function for fatal permission-denied errors
5487 * @param string $permission User right required
5490 static function newFatalPermissionDeniedStatus( $permission ) {
5494 foreach ( self
::getGroupsWithPermission( $permission ) as $group ) {
5495 $groups[] = UserGroupMembership
::getLink( $group, RequestContext
::getMain(), 'wiki' );
5499 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5501 return Status
::newFatal( 'badaccess-group0' );
5506 * Get a new instance of this user that was loaded from the master via a locking read
5508 * Use this instead of the main context User when updating that user. This avoids races
5509 * where that user was loaded from a replica DB or even the master but without proper locks.
5511 * @return User|null Returns null if the user was not found in the DB
5514 public function getInstanceForUpdate() {
5515 if ( !$this->getId() ) {
5516 return null; // anon
5519 $user = self
::newFromId( $this->getId() );
5520 if ( !$user->loadFromId( self
::READ_EXCLUSIVE
) ) {
5528 * Checks if two user objects point to the same user.
5534 public function equals( User
$user ) {
5535 return $this->getName() === $user->getName();