3 * Implements the User class for the %MediaWiki software.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use MediaWiki\MediaWikiServices
;
24 use MediaWiki\Session\SessionManager
;
25 use MediaWiki\Session\Token
;
26 use MediaWiki\Auth\AuthManager
;
27 use MediaWiki\Auth\AuthenticationResponse
;
28 use MediaWiki\Auth\AuthenticationRequest
;
29 use MediaWiki\User\UserIdentity
;
31 use Wikimedia\ScopedCallback
;
32 use Wikimedia\Rdbms\Database
;
33 use Wikimedia\Rdbms\DBExpectedError
;
34 use Wikimedia\Rdbms\IDatabase
;
37 * String Some punctuation to prevent editing from broken text-mangling proxies.
38 * @deprecated since 1.27, use \MediaWiki\Session\Token::SUFFIX
41 define( 'EDIT_TOKEN_SUFFIX', Token
::SUFFIX
);
44 * The User object encapsulates all of the user-specific settings (user_id,
45 * name, rights, email address, options, last login time). Client
46 * classes use the getXXX() functions to access these fields. These functions
47 * do all the work of determining whether the user is logged in,
48 * whether the requested option can be satisfied from cookies or
49 * whether a database query is needed. Most of the settings needed
50 * for rendering normal pages are set in the cookie to minimize use
53 class User
implements IDBAccessObject
, UserIdentity
{
55 * @const int Number of characters in user_token field.
57 const TOKEN_LENGTH
= 32;
60 * @const string An invalid value for user_token
62 const INVALID_TOKEN
= '*** INVALID ***';
65 * Global constant made accessible as class constants so that autoloader
67 * @deprecated since 1.27, use \MediaWiki\Session\Token::SUFFIX
69 const EDIT_TOKEN_SUFFIX
= EDIT_TOKEN_SUFFIX
;
72 * @const int Serialized record version.
77 * Exclude user options that are set to their default value.
80 const GETOPTIONS_EXCLUDE_DEFAULTS
= 1;
85 const CHECK_USER_RIGHTS
= true;
90 const IGNORE_USER_RIGHTS
= false;
93 * Array of Strings List of member variables which are saved to the
94 * shared cache (memcached). Any operation which changes the
95 * corresponding database fields must call a cache-clearing function.
98 protected static $mCacheVars = [
106 'mEmailAuthenticated',
108 'mEmailTokenExpires',
113 // user_properties table
120 * Array of Strings Core rights.
121 * Each of these should have a corresponding message of the form
125 protected static $mCoreRights = [
168 'move-categorypages',
169 'move-rootuserpages',
173 'override-export-depth',
195 'userrights-interwiki',
203 * String Cached results of getAllRights()
205 protected static $mAllRights = false;
207 /** Cache variables */
220 /** @var string TS_MW timestamp from the DB */
222 /** @var string TS_MW timestamp from cache */
223 protected $mQuickTouched;
227 public $mEmailAuthenticated;
229 protected $mEmailToken;
231 protected $mEmailTokenExpires;
233 protected $mRegistration;
235 protected $mEditCount;
236 /** @var UserGroupMembership[] Associative array of (group name => UserGroupMembership object) */
237 protected $mGroupMemberships;
239 protected $mOptionOverrides;
243 * Bool Whether the cache variables have been loaded.
246 public $mOptionsLoaded;
249 * Array with already loaded items or true if all items have been loaded.
251 protected $mLoadedItems = [];
255 * String Initialization data source if mLoadedItems!==true. May be one of:
256 * - 'defaults' anonymous user initialised from class defaults
257 * - 'name' initialise from mName
258 * - 'id' initialise from mId
259 * - 'actor' initialise from mActorId
260 * - 'session' log in from session if possible
262 * Use the User::newFrom*() family of functions to set this.
267 * Lazy-initialized variables, invalidated with clearInstanceCache
271 protected $mDatePreference;
279 protected $mBlockreason;
281 protected $mEffectiveGroups;
283 protected $mImplicitGroups;
285 protected $mFormerGroups;
287 protected $mGlobalBlock;
295 /** @var WebRequest */
302 protected $mAllowUsertalk;
305 private $mBlockedFromCreateAccount = false;
307 /** @var int User::READ_* constant bitfield used to load data */
308 protected $queryFlagsUsed = self
::READ_NORMAL
;
310 public static $idCacheByName = [];
313 * Lightweight constructor for an anonymous user.
314 * Use the User::newFrom* factory functions for other kinds of users.
318 * @see newFromActorId()
319 * @see newFromConfirmationCode()
320 * @see newFromSession()
323 public function __construct() {
324 $this->clearInstanceCache( 'defaults' );
330 public function __toString() {
331 return (string)$this->getName();
335 * Test if it's safe to load this User object.
337 * You should typically check this before using $wgUser or
338 * RequestContext::getUser in a method that might be called before the
339 * system has been fully initialized. If the object is unsafe, you should
340 * use an anonymous user:
342 * $user = $wgUser->isSafeToLoad() ? $wgUser : new User;
348 public function isSafeToLoad() {
349 global $wgFullyInitialised;
351 // The user is safe to load if:
352 // * MW_NO_SESSION is undefined AND $wgFullyInitialised is true (safe to use session data)
353 // * mLoadedItems === true (already loaded)
354 // * mFrom !== 'session' (sessions not involved at all)
356 return ( !defined( 'MW_NO_SESSION' ) && $wgFullyInitialised ) ||
357 $this->mLoadedItems
=== true ||
$this->mFrom
!== 'session';
361 * Load the user table data for this object from the source given by mFrom.
363 * @param int $flags User::READ_* constant bitfield
365 public function load( $flags = self
::READ_NORMAL
) {
366 global $wgFullyInitialised;
368 if ( $this->mLoadedItems
=== true ) {
372 // Set it now to avoid infinite recursion in accessors
373 $oldLoadedItems = $this->mLoadedItems
;
374 $this->mLoadedItems
= true;
375 $this->queryFlagsUsed
= $flags;
377 // If this is called too early, things are likely to break.
378 if ( !$wgFullyInitialised && $this->mFrom
=== 'session' ) {
379 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
380 ->warning( 'User::loadFromSession called before the end of Setup.php', [
381 'exception' => new Exception( 'User::loadFromSession called before the end of Setup.php' ),
383 $this->loadDefaults();
384 $this->mLoadedItems
= $oldLoadedItems;
388 switch ( $this->mFrom
) {
390 $this->loadDefaults();
393 // Make sure this thread sees its own changes
394 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
395 if ( $lb->hasOrMadeRecentMasterChanges() ) {
396 $flags |
= self
::READ_LATEST
;
397 $this->queryFlagsUsed
= $flags;
400 $this->mId
= self
::idFromName( $this->mName
, $flags );
402 // Nonexistent user placeholder object
403 $this->loadDefaults( $this->mName
);
405 $this->loadFromId( $flags );
409 // Make sure this thread sees its own changes, if the ID isn't 0
410 if ( $this->mId
!= 0 ) {
411 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
412 if ( $lb->hasOrMadeRecentMasterChanges() ) {
413 $flags |
= self
::READ_LATEST
;
414 $this->queryFlagsUsed
= $flags;
418 $this->loadFromId( $flags );
421 // Make sure this thread sees its own changes
422 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
423 $flags |
= self
::READ_LATEST
;
424 $this->queryFlagsUsed
= $flags;
427 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
428 $row = wfGetDB( $index )->selectRow(
430 [ 'actor_user', 'actor_name' ],
431 [ 'actor_id' => $this->mActorId
],
438 $this->loadDefaults();
439 } elseif ( $row->actor_user
) {
440 $this->mId
= $row->actor_user
;
441 $this->loadFromId( $flags );
443 $this->loadDefaults( $row->actor_name
);
447 if ( !$this->loadFromSession() ) {
448 // Loading from session failed. Load defaults.
449 $this->loadDefaults();
451 Hooks
::run( 'UserLoadAfterLoadFromSession', [ $this ] );
454 throw new UnexpectedValueException(
455 "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
460 * Load user table data, given mId has already been set.
461 * @param int $flags User::READ_* constant bitfield
462 * @return bool False if the ID does not exist, true otherwise
464 public function loadFromId( $flags = self
::READ_NORMAL
) {
465 if ( $this->mId
== 0 ) {
466 // Anonymous users are not in the database (don't need cache)
467 $this->loadDefaults();
471 // Try cache (unless this needs data from the master DB).
472 // NOTE: if this thread called saveSettings(), the cache was cleared.
473 $latest = DBAccessObjectUtils
::hasFlags( $flags, self
::READ_LATEST
);
475 if ( !$this->loadFromDatabase( $flags ) ) {
476 // Can't load from ID
480 $this->loadFromCache();
483 $this->mLoadedItems
= true;
484 $this->queryFlagsUsed
= $flags;
491 * @param string $wikiId
494 public static function purge( $wikiId, $userId ) {
495 $cache = ObjectCache
::getMainWANInstance();
496 $key = $cache->makeGlobalKey( 'user', 'id', $wikiId, $userId );
497 $cache->delete( $key );
502 * @param WANObjectCache $cache
505 protected function getCacheKey( WANObjectCache
$cache ) {
506 return $cache->makeGlobalKey( 'user', 'id', wfWikiID(), $this->mId
);
510 * @param WANObjectCache $cache
514 public function getMutableCacheKeys( WANObjectCache
$cache ) {
515 $id = $this->getId();
517 return $id ?
[ $this->getCacheKey( $cache ) ] : [];
521 * Load user data from shared cache, given mId has already been set.
526 protected function loadFromCache() {
527 $cache = ObjectCache
::getMainWANInstance();
528 $data = $cache->getWithSetCallback(
529 $this->getCacheKey( $cache ),
531 function ( $oldValue, &$ttl, array &$setOpts ) use ( $cache ) {
532 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
533 wfDebug( "User: cache miss for user {$this->mId}\n" );
535 $this->loadFromDatabase( self
::READ_NORMAL
);
537 $this->loadOptions();
540 foreach ( self
::$mCacheVars as $name ) {
541 $data[$name] = $this->$name;
544 $ttl = $cache->adaptiveTTL( wfTimestamp( TS_UNIX
, $this->mTouched
), $ttl );
546 // if a user group membership is about to expire, the cache needs to
547 // expire at that time (T163691)
548 foreach ( $this->mGroupMemberships
as $ugm ) {
549 if ( $ugm->getExpiry() ) {
550 $secondsUntilExpiry = wfTimestamp( TS_UNIX
, $ugm->getExpiry() ) - time();
551 if ( $secondsUntilExpiry > 0 && $secondsUntilExpiry < $ttl ) {
552 $ttl = $secondsUntilExpiry;
559 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'version' => self
::VERSION
]
562 // Restore from cache
563 foreach ( self
::$mCacheVars as $name ) {
564 $this->$name = $data[$name];
570 /** @name newFrom*() static factory methods */
574 * Static factory method for creation from username.
576 * This is slightly less efficient than newFromId(), so use newFromId() if
577 * you have both an ID and a name handy.
579 * @param string $name Username, validated by Title::newFromText()
580 * @param string|bool $validate Validate username. Takes the same parameters as
581 * User::getCanonicalName(), except that true is accepted as an alias
582 * for 'valid', for BC.
584 * @return User|bool User object, or false if the username is invalid
585 * (e.g. if it contains illegal characters or is an IP address). If the
586 * username is not present in the database, the result will be a user object
587 * with a name, zero user ID and default settings.
589 public static function newFromName( $name, $validate = 'valid' ) {
590 if ( $validate === true ) {
593 $name = self
::getCanonicalName( $name, $validate );
594 if ( $name === false ) {
597 // Create unloaded user object
601 $u->setItemLoaded( 'name' );
607 * Static factory method for creation from a given user ID.
609 * @param int $id Valid user ID
610 * @return User The corresponding User object
612 public static function newFromId( $id ) {
616 $u->setItemLoaded( 'id' );
621 * Static factory method for creation from a given actor ID.
624 * @param int $id Valid actor ID
625 * @return User The corresponding User object
627 public static function newFromActorId( $id ) {
628 global $wgActorTableSchemaMigrationStage;
630 if ( $wgActorTableSchemaMigrationStage <= MIGRATION_OLD
) {
631 throw new BadMethodCallException(
632 'Cannot use ' . __METHOD__
. ' when $wgActorTableSchemaMigrationStage is MIGRATION_OLD'
639 $u->setItemLoaded( 'actor' );
644 * Static factory method for creation from an ID, name, and/or actor ID
646 * This does not check that the ID, name, and actor ID all correspond to
650 * @param int|null $userId User ID, if known
651 * @param string|null $userName User name, if known
652 * @param int|null $actorId Actor ID, if known
655 public static function newFromAnyId( $userId, $userName, $actorId ) {
656 global $wgActorTableSchemaMigrationStage;
659 $user->mFrom
= 'defaults';
661 if ( $wgActorTableSchemaMigrationStage > MIGRATION_OLD
&& $actorId !== null ) {
662 $user->mActorId
= (int)$actorId;
663 if ( $user->mActorId
!== 0 ) {
664 $user->mFrom
= 'actor';
666 $user->setItemLoaded( 'actor' );
669 if ( $userName !== null && $userName !== '' ) {
670 $user->mName
= $userName;
671 $user->mFrom
= 'name';
672 $user->setItemLoaded( 'name' );
675 if ( $userId !== null ) {
676 $user->mId
= (int)$userId;
677 if ( $user->mId
!== 0 ) {
680 $user->setItemLoaded( 'id' );
683 if ( $user->mFrom
=== 'defaults' ) {
684 throw new InvalidArgumentException(
685 'Cannot create a user with no name, no ID, and no actor ID'
693 * Factory method to fetch whichever user has a given email confirmation code.
694 * This code is generated when an account is created or its e-mail address
697 * If the code is invalid or has expired, returns NULL.
699 * @param string $code Confirmation code
700 * @param int $flags User::READ_* bitfield
703 public static function newFromConfirmationCode( $code, $flags = 0 ) {
704 $db = ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
705 ?
wfGetDB( DB_MASTER
)
706 : wfGetDB( DB_REPLICA
);
708 $id = $db->selectField(
712 'user_email_token' => md5( $code ),
713 'user_email_token_expires > ' . $db->addQuotes( $db->timestamp() ),
717 return $id ? self
::newFromId( $id ) : null;
721 * Create a new user object using data from session. If the login
722 * credentials are invalid, the result is an anonymous user.
724 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
727 public static function newFromSession( WebRequest
$request = null ) {
729 $user->mFrom
= 'session';
730 $user->mRequest
= $request;
735 * Create a new user object from a user row.
736 * The row should have the following fields from the user table in it:
737 * - either user_name or user_id to load further data if needed (or both)
739 * - all other fields (email, etc.)
740 * It is useless to provide the remaining fields if either user_id,
741 * user_name and user_real_name are not provided because the whole row
742 * will be loaded once more from the database when accessing them.
744 * @param stdClass $row A row from the user table
745 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
748 public static function newFromRow( $row, $data = null ) {
750 $user->loadFromRow( $row, $data );
755 * Static factory method for creation of a "system" user from username.
757 * A "system" user is an account that's used to attribute logged actions
758 * taken by MediaWiki itself, as opposed to a bot or human user. Examples
759 * might include the 'Maintenance script' or 'Conversion script' accounts
760 * used by various scripts in the maintenance/ directory or accounts such
761 * as 'MediaWiki message delivery' used by the MassMessage extension.
763 * This can optionally create the user if it doesn't exist, and "steal" the
764 * account if it does exist.
766 * "Stealing" an existing user is intended to make it impossible for normal
767 * authentication processes to use the account, effectively disabling the
768 * account for normal use:
769 * - Email is invalidated, to prevent account recovery by emailing a
770 * temporary password and to disassociate the account from the existing
772 * - The token is set to a magic invalid value, to kill existing sessions
773 * and to prevent $this->setToken() calls from resetting the token to a
775 * - SessionManager is instructed to prevent new sessions for the user, to
776 * do things like deauthorizing OAuth consumers.
777 * - AuthManager is instructed to revoke access, to invalidate or remove
778 * passwords and other credentials.
780 * @param string $name Username
781 * @param array $options Options are:
782 * - validate: As for User::getCanonicalName(), default 'valid'
783 * - create: Whether to create the user if it doesn't already exist, default true
784 * - steal: Whether to "disable" the account for normal use if it already
785 * exists, default false
789 public static function newSystemUser( $name, $options = [] ) {
791 'validate' => 'valid',
796 $name = self
::getCanonicalName( $name, $options['validate'] );
797 if ( $name === false ) {
801 $dbr = wfGetDB( DB_REPLICA
);
802 $userQuery = self
::getQueryInfo();
803 $row = $dbr->selectRow(
804 $userQuery['tables'],
805 $userQuery['fields'],
806 [ 'user_name' => $name ],
812 // Try the master database...
813 $dbw = wfGetDB( DB_MASTER
);
814 $row = $dbw->selectRow(
815 $userQuery['tables'],
816 $userQuery['fields'],
817 [ 'user_name' => $name ],
825 // No user. Create it?
826 return $options['create']
827 ? self
::createNew( $name, [ 'token' => self
::INVALID_TOKEN
] )
831 $user = self
::newFromRow( $row );
833 // A user is considered to exist as a non-system user if it can
834 // authenticate, or has an email set, or has a non-invalid token.
835 if ( $user->mEmail ||
$user->mToken
!== self
::INVALID_TOKEN ||
836 AuthManager
::singleton()->userCanAuthenticate( $name )
838 // User exists. Steal it?
839 if ( !$options['steal'] ) {
843 AuthManager
::singleton()->revokeAccessForUser( $name );
845 $user->invalidateEmail();
846 $user->mToken
= self
::INVALID_TOKEN
;
847 $user->saveSettings();
848 SessionManager
::singleton()->preventSessionsForUser( $user->getName() );
857 * Get the username corresponding to a given user ID
858 * @param int $id User ID
859 * @return string|bool The corresponding username
861 public static function whoIs( $id ) {
862 return UserCache
::singleton()->getProp( $id, 'name' );
866 * Get the real name of a user given their user ID
868 * @param int $id User ID
869 * @return string|bool The corresponding user's real name
871 public static function whoIsReal( $id ) {
872 return UserCache
::singleton()->getProp( $id, 'real_name' );
876 * Get database id given a user name
877 * @param string $name Username
878 * @param int $flags User::READ_* constant bitfield
879 * @return int|null The corresponding user's ID, or null if user is nonexistent
881 public static function idFromName( $name, $flags = self
::READ_NORMAL
) {
882 $nt = Title
::makeTitleSafe( NS_USER
, $name );
883 if ( is_null( $nt ) ) {
888 if ( !( $flags & self
::READ_LATEST
) && array_key_exists( $name, self
::$idCacheByName ) ) {
889 return self
::$idCacheByName[$name];
892 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
893 $db = wfGetDB( $index );
898 [ 'user_name' => $nt->getText() ],
903 if ( $s === false ) {
906 $result = $s->user_id
;
909 self
::$idCacheByName[$name] = $result;
911 if ( count( self
::$idCacheByName ) > 1000 ) {
912 self
::$idCacheByName = [];
919 * Reset the cache used in idFromName(). For use in tests.
921 public static function resetIdByNameCache() {
922 self
::$idCacheByName = [];
926 * Does the string match an anonymous IP address?
928 * This function exists for username validation, in order to reject
929 * usernames which are similar in form to IP addresses. Strings such
930 * as 300.300.300.300 will return true because it looks like an IP
931 * address, despite not being strictly valid.
933 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
934 * address because the usemod software would "cloak" anonymous IP
935 * addresses like this, if we allowed accounts like this to be created
936 * new users could get the old edits of these anonymous users.
938 * @param string $name Name to match
941 public static function isIP( $name ) {
942 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
943 || IP
::isIPv6( $name );
947 * Is the user an IP range?
952 public function isIPRange() {
953 return IP
::isValidRange( $this->mName
);
957 * Is the input a valid username?
959 * Checks if the input is a valid username, we don't want an empty string,
960 * an IP address, anything that contains slashes (would mess up subpages),
961 * is longer than the maximum allowed username size or doesn't begin with
964 * @param string $name Name to match
967 public static function isValidUserName( $name ) {
968 global $wgContLang, $wgMaxNameChars;
971 || self
::isIP( $name )
972 ||
strpos( $name, '/' ) !== false
973 ||
strlen( $name ) > $wgMaxNameChars
974 ||
$name != $wgContLang->ucfirst( $name )
979 // Ensure that the name can't be misresolved as a different title,
980 // such as with extra namespace keys at the start.
981 $parsed = Title
::newFromText( $name );
982 if ( is_null( $parsed )
983 ||
$parsed->getNamespace()
984 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
988 // Check an additional blacklist of troublemaker characters.
989 // Should these be merged into the title char list?
990 $unicodeBlacklist = '/[' .
991 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
992 '\x{00a0}' . # non-breaking space
993 '\x{2000}-\x{200f}' . # various whitespace
994 '\x{2028}-\x{202f}' . # breaks and control chars
995 '\x{3000}' . # ideographic space
996 '\x{e000}-\x{f8ff}' . # private use
998 if ( preg_match( $unicodeBlacklist, $name ) ) {
1006 * Usernames which fail to pass this function will be blocked
1007 * from user login and new account registrations, but may be used
1008 * internally by batch processes.
1010 * If an account already exists in this form, login will be blocked
1011 * by a failure to pass this function.
1013 * @param string $name Name to match
1016 public static function isUsableName( $name ) {
1017 global $wgReservedUsernames;
1018 // Must be a valid username, obviously ;)
1019 if ( !self
::isValidUserName( $name ) ) {
1023 static $reservedUsernames = false;
1024 if ( !$reservedUsernames ) {
1025 $reservedUsernames = $wgReservedUsernames;
1026 Hooks
::run( 'UserGetReservedNames', [ &$reservedUsernames ] );
1029 // Certain names may be reserved for batch processes.
1030 foreach ( $reservedUsernames as $reserved ) {
1031 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
1032 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
1034 if ( $reserved == $name ) {
1042 * Return the users who are members of the given group(s). In case of multiple groups,
1043 * users who are members of at least one of them are returned.
1045 * @param string|array $groups A single group name or an array of group names
1046 * @param int $limit Max number of users to return. The actual limit will never exceed 5000
1047 * records; larger values are ignored.
1048 * @param int $after ID the user to start after
1049 * @return UserArrayFromResult
1051 public static function findUsersByGroup( $groups, $limit = 5000, $after = null ) {
1052 if ( $groups === [] ) {
1053 return UserArrayFromResult
::newFromIDs( [] );
1056 $groups = array_unique( (array)$groups );
1057 $limit = min( 5000, $limit );
1059 $conds = [ 'ug_group' => $groups ];
1060 if ( $after !== null ) {
1061 $conds[] = 'ug_user > ' . (int)$after;
1064 $dbr = wfGetDB( DB_REPLICA
);
1065 $ids = $dbr->selectFieldValues(
1072 'ORDER BY' => 'ug_user',
1076 return UserArray
::newFromIDs( $ids );
1080 * Usernames which fail to pass this function will be blocked
1081 * from new account registrations, but may be used internally
1082 * either by batch processes or by user accounts which have
1083 * already been created.
1085 * Additional blacklisting may be added here rather than in
1086 * isValidUserName() to avoid disrupting existing accounts.
1088 * @param string $name String to match
1091 public static function isCreatableName( $name ) {
1092 global $wgInvalidUsernameCharacters;
1094 // Ensure that the username isn't longer than 235 bytes, so that
1095 // (at least for the builtin skins) user javascript and css files
1096 // will work. (T25080)
1097 if ( strlen( $name ) > 235 ) {
1098 wfDebugLog( 'username', __METHOD__
.
1099 ": '$name' invalid due to length" );
1103 // Preg yells if you try to give it an empty string
1104 if ( $wgInvalidUsernameCharacters !== '' ) {
1105 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
1106 wfDebugLog( 'username', __METHOD__
.
1107 ": '$name' invalid due to wgInvalidUsernameCharacters" );
1112 return self
::isUsableName( $name );
1116 * Is the input a valid password for this user?
1118 * @param string $password Desired password
1121 public function isValidPassword( $password ) {
1122 // simple boolean wrapper for getPasswordValidity
1123 return $this->getPasswordValidity( $password ) === true;
1127 * Given unvalidated password input, return error message on failure.
1129 * @param string $password Desired password
1130 * @return bool|string|array True on success, string or array of error message on failure
1132 public function getPasswordValidity( $password ) {
1133 $result = $this->checkPasswordValidity( $password );
1134 if ( $result->isGood() ) {
1138 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
1139 $messages[] = $error['message'];
1141 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
1142 $messages[] = $warning['message'];
1144 if ( count( $messages ) === 1 ) {
1145 return $messages[0];
1152 * Check if this is a valid password for this user
1154 * Create a Status object based on the password's validity.
1155 * The Status should be set to fatal if the user should not
1156 * be allowed to log in, and should have any errors that
1157 * would block changing the password.
1159 * If the return value of this is not OK, the password
1160 * should not be checked. If the return value is not Good,
1161 * the password can be checked, but the user should not be
1162 * able to set their password to this.
1164 * @param string $password Desired password
1168 public function checkPasswordValidity( $password ) {
1169 global $wgPasswordPolicy;
1171 $upp = new UserPasswordPolicy(
1172 $wgPasswordPolicy['policies'],
1173 $wgPasswordPolicy['checks']
1176 $status = Status
::newGood();
1177 $result = false; // init $result to false for the internal checks
1179 if ( !Hooks
::run( 'isValidPassword', [ $password, &$result, $this ] ) ) {
1180 $status->error( $result );
1184 if ( $result === false ) {
1185 $status->merge( $upp->checkUserPassword( $this, $password ) );
1187 } elseif ( $result === true ) {
1190 $status->error( $result );
1191 return $status; // the isValidPassword hook set a string $result and returned true
1196 * Given unvalidated user input, return a canonical username, or false if
1197 * the username is invalid.
1198 * @param string $name User input
1199 * @param string|bool $validate Type of validation to use:
1200 * - false No validation
1201 * - 'valid' Valid for batch processes
1202 * - 'usable' Valid for batch processes and login
1203 * - 'creatable' Valid for batch processes, login and account creation
1205 * @throws InvalidArgumentException
1206 * @return bool|string
1208 public static function getCanonicalName( $name, $validate = 'valid' ) {
1209 // Force usernames to capital
1211 $name = $wgContLang->ucfirst( $name );
1213 # Reject names containing '#'; these will be cleaned up
1214 # with title normalisation, but then it's too late to
1216 if ( strpos( $name, '#' ) !== false ) {
1220 // Clean up name according to title rules,
1221 // but only when validation is requested (T14654)
1222 $t = ( $validate !== false ) ?
1223 Title
::newFromText( $name, NS_USER
) : Title
::makeTitle( NS_USER
, $name );
1224 // Check for invalid titles
1225 if ( is_null( $t ) ||
$t->getNamespace() !== NS_USER ||
$t->isExternal() ) {
1229 // Reject various classes of invalid names
1230 $name = AuthManager
::callLegacyAuthPlugin(
1231 'getCanonicalName', [ $t->getText() ], $t->getText()
1234 switch ( $validate ) {
1238 if ( !self
::isValidUserName( $name ) ) {
1243 if ( !self
::isUsableName( $name ) ) {
1248 if ( !self
::isCreatableName( $name ) ) {
1253 throw new InvalidArgumentException(
1254 'Invalid parameter value for $validate in ' . __METHOD__
);
1260 * Return a random password.
1262 * @deprecated since 1.27, use PasswordFactory::generateRandomPasswordString()
1263 * @return string New random password
1265 public static function randomPassword() {
1266 global $wgMinimalPasswordLength;
1267 return PasswordFactory
::generateRandomPasswordString( $wgMinimalPasswordLength );
1271 * Set cached properties to default.
1273 * @note This no longer clears uncached lazy-initialised properties;
1274 * the constructor does that instead.
1276 * @param string|bool $name
1278 public function loadDefaults( $name = false ) {
1280 $this->mName
= $name;
1281 $this->mActorId
= null;
1282 $this->mRealName
= '';
1284 $this->mOptionOverrides
= null;
1285 $this->mOptionsLoaded
= false;
1287 $loggedOut = $this->mRequest
&& !defined( 'MW_NO_SESSION' )
1288 ?
$this->mRequest
->getSession()->getLoggedOutTimestamp() : 0;
1289 if ( $loggedOut !== 0 ) {
1290 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1292 $this->mTouched
= '1'; # Allow any pages to be cached
1295 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1296 $this->mEmailAuthenticated
= null;
1297 $this->mEmailToken
= '';
1298 $this->mEmailTokenExpires
= null;
1299 $this->mRegistration
= wfTimestamp( TS_MW
);
1300 $this->mGroupMemberships
= [];
1302 Hooks
::run( 'UserLoadDefaults', [ $this, $name ] );
1306 * Return whether an item has been loaded.
1308 * @param string $item Item to check. Current possibilities:
1312 * @param string $all 'all' to check if the whole object has been loaded
1313 * or any other string to check if only the item is available (e.g.
1317 public function isItemLoaded( $item, $all = 'all' ) {
1318 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1319 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1323 * Set that an item has been loaded
1325 * @param string $item
1327 protected function setItemLoaded( $item ) {
1328 if ( is_array( $this->mLoadedItems
) ) {
1329 $this->mLoadedItems
[$item] = true;
1334 * Load user data from the session.
1336 * @return bool True if the user is logged in, false otherwise.
1338 private function loadFromSession() {
1341 Hooks
::run( 'UserLoadFromSession', [ $this, &$result ], '1.27' );
1342 if ( $result !== null ) {
1346 // MediaWiki\Session\Session already did the necessary authentication of the user
1347 // returned here, so just use it if applicable.
1348 $session = $this->getRequest()->getSession();
1349 $user = $session->getUser();
1350 if ( $user->isLoggedIn() ) {
1351 $this->loadFromUserObject( $user );
1353 // If this user is autoblocked, set a cookie to track the Block. This has to be done on
1354 // every session load, because an autoblocked editor might not edit again from the same
1355 // IP address after being blocked.
1356 $config = RequestContext
::getMain()->getConfig();
1357 if ( $config->get( 'CookieSetOnAutoblock' ) === true ) {
1358 $block = $this->getBlock();
1359 $shouldSetCookie = $this->getRequest()->getCookie( 'BlockID' ) === null
1361 && $block->getType() === Block
::TYPE_USER
1362 && $block->isAutoblocking();
1363 if ( $shouldSetCookie ) {
1364 wfDebug( __METHOD__
. ': User is autoblocked, setting cookie to track' );
1365 $block->setCookie( $this->getRequest()->response() );
1369 // Other code expects these to be set in the session, so set them.
1370 $session->set( 'wsUserID', $this->getId() );
1371 $session->set( 'wsUserName', $this->getName() );
1372 $session->set( 'wsToken', $this->getToken() );
1379 * Load user and user_group data from the database.
1380 * $this->mId must be set, this is how the user is identified.
1382 * @param int $flags User::READ_* constant bitfield
1383 * @return bool True if the user exists, false if the user is anonymous
1385 public function loadFromDatabase( $flags = self
::READ_LATEST
) {
1387 $this->mId
= intval( $this->mId
);
1389 if ( !$this->mId
) {
1390 // Anonymous users are not in the database
1391 $this->loadDefaults();
1395 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
1396 $db = wfGetDB( $index );
1398 $userQuery = self
::getQueryInfo();
1399 $s = $db->selectRow(
1400 $userQuery['tables'],
1401 $userQuery['fields'],
1402 [ 'user_id' => $this->mId
],
1408 $this->queryFlagsUsed
= $flags;
1409 Hooks
::run( 'UserLoadFromDatabase', [ $this, &$s ] );
1411 if ( $s !== false ) {
1412 // Initialise user table data
1413 $this->loadFromRow( $s );
1414 $this->mGroupMemberships
= null; // deferred
1415 $this->getEditCount(); // revalidation for nulls
1420 $this->loadDefaults();
1426 * Initialize this object from a row from the user table.
1428 * @param stdClass $row Row from the user table to load.
1429 * @param array $data Further user data to load into the object
1431 * user_groups Array of arrays or stdClass result rows out of the user_groups
1432 * table. Previously you were supposed to pass an array of strings
1433 * here, but we also need expiry info nowadays, so an array of
1434 * strings is ignored.
1435 * user_properties Array with properties out of the user_properties table
1437 protected function loadFromRow( $row, $data = null ) {
1438 global $wgActorTableSchemaMigrationStage;
1440 if ( !is_object( $row ) ) {
1441 throw new InvalidArgumentException( '$row must be an object' );
1446 $this->mGroupMemberships
= null; // deferred
1448 if ( $wgActorTableSchemaMigrationStage > MIGRATION_OLD
) {
1449 if ( isset( $row->actor_id
) ) {
1450 $this->mActorId
= (int)$row->actor_id
;
1451 if ( $this->mActorId
!== 0 ) {
1452 $this->mFrom
= 'actor';
1454 $this->setItemLoaded( 'actor' );
1460 if ( isset( $row->user_name
) && $row->user_name
!== '' ) {
1461 $this->mName
= $row->user_name
;
1462 $this->mFrom
= 'name';
1463 $this->setItemLoaded( 'name' );
1468 if ( isset( $row->user_real_name
) ) {
1469 $this->mRealName
= $row->user_real_name
;
1470 $this->setItemLoaded( 'realname' );
1475 if ( isset( $row->user_id
) ) {
1476 $this->mId
= intval( $row->user_id
);
1477 if ( $this->mId
!== 0 ) {
1478 $this->mFrom
= 'id';
1480 $this->setItemLoaded( 'id' );
1485 if ( isset( $row->user_id
) && isset( $row->user_name
) && $row->user_name
!== '' ) {
1486 self
::$idCacheByName[$row->user_name
] = $row->user_id
;
1489 if ( isset( $row->user_editcount
) ) {
1490 $this->mEditCount
= $row->user_editcount
;
1495 if ( isset( $row->user_touched
) ) {
1496 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1501 if ( isset( $row->user_token
) ) {
1502 // The definition for the column is binary(32), so trim the NULs
1503 // that appends. The previous definition was char(32), so trim
1505 $this->mToken
= rtrim( $row->user_token
, " \0" );
1506 if ( $this->mToken
=== '' ) {
1507 $this->mToken
= null;
1513 if ( isset( $row->user_email
) ) {
1514 $this->mEmail
= $row->user_email
;
1515 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1516 $this->mEmailToken
= $row->user_email_token
;
1517 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1518 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1524 $this->mLoadedItems
= true;
1527 if ( is_array( $data ) ) {
1528 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1529 if ( !count( $data['user_groups'] ) ) {
1530 $this->mGroupMemberships
= [];
1532 $firstGroup = reset( $data['user_groups'] );
1533 if ( is_array( $firstGroup ) ||
is_object( $firstGroup ) ) {
1534 $this->mGroupMemberships
= [];
1535 foreach ( $data['user_groups'] as $row ) {
1536 $ugm = UserGroupMembership
::newFromRow( (object)$row );
1537 $this->mGroupMemberships
[$ugm->getGroup()] = $ugm;
1542 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1543 $this->loadOptions( $data['user_properties'] );
1549 * Load the data for this user object from another user object.
1553 protected function loadFromUserObject( $user ) {
1555 foreach ( self
::$mCacheVars as $var ) {
1556 $this->$var = $user->$var;
1561 * Load the groups from the database if they aren't already loaded.
1563 private function loadGroups() {
1564 if ( is_null( $this->mGroupMemberships
) ) {
1565 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
1566 ?
wfGetDB( DB_MASTER
)
1567 : wfGetDB( DB_REPLICA
);
1568 $this->mGroupMemberships
= UserGroupMembership
::getMembershipsForUser(
1574 * Add the user to the group if he/she meets given criteria.
1576 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1577 * possible to remove manually via Special:UserRights. In such case it
1578 * will not be re-added automatically. The user will also not lose the
1579 * group if they no longer meet the criteria.
1581 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1583 * @return array Array of groups the user has been promoted to.
1585 * @see $wgAutopromoteOnce
1587 public function addAutopromoteOnceGroups( $event ) {
1588 global $wgAutopromoteOnceLogInRC;
1590 if ( wfReadOnly() ||
!$this->getId() ) {
1594 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1595 if ( !count( $toPromote ) ) {
1599 if ( !$this->checkAndSetTouched() ) {
1600 return []; // raced out (bug T48834)
1603 $oldGroups = $this->getGroups(); // previous groups
1604 $oldUGMs = $this->getGroupMemberships();
1605 foreach ( $toPromote as $group ) {
1606 $this->addGroup( $group );
1608 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1609 $newUGMs = $this->getGroupMemberships();
1611 // update groups in external authentication database
1612 Hooks
::run( 'UserGroupsChanged', [ $this, $toPromote, [], false, false, $oldUGMs, $newUGMs ] );
1613 AuthManager
::callLegacyAuthPlugin( 'updateExternalDBGroups', [ $this, $toPromote ] );
1615 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1616 $logEntry->setPerformer( $this );
1617 $logEntry->setTarget( $this->getUserPage() );
1618 $logEntry->setParameters( [
1619 '4::oldgroups' => $oldGroups,
1620 '5::newgroups' => $newGroups,
1622 $logid = $logEntry->insert();
1623 if ( $wgAutopromoteOnceLogInRC ) {
1624 $logEntry->publish( $logid );
1631 * Builds update conditions. Additional conditions may be added to $conditions to
1632 * protected against race conditions using a compare-and-set (CAS) mechanism
1633 * based on comparing $this->mTouched with the user_touched field.
1635 * @param Database $db
1636 * @param array $conditions WHERE conditions for use with Database::update
1637 * @return array WHERE conditions for use with Database::update
1639 protected function makeUpdateConditions( Database
$db, array $conditions ) {
1640 if ( $this->mTouched
) {
1641 // CAS check: only update if the row wasn't changed sicne it was loaded.
1642 $conditions['user_touched'] = $db->timestamp( $this->mTouched
);
1649 * Bump user_touched if it didn't change since this object was loaded
1651 * On success, the mTouched field is updated.
1652 * The user serialization cache is always cleared.
1654 * @return bool Whether user_touched was actually updated
1657 protected function checkAndSetTouched() {
1660 if ( !$this->mId
) {
1661 return false; // anon
1664 // Get a new user_touched that is higher than the old one
1665 $newTouched = $this->newTouchedTimestamp();
1667 $dbw = wfGetDB( DB_MASTER
);
1668 $dbw->update( 'user',
1669 [ 'user_touched' => $dbw->timestamp( $newTouched ) ],
1670 $this->makeUpdateConditions( $dbw, [
1671 'user_id' => $this->mId
,
1675 $success = ( $dbw->affectedRows() > 0 );
1678 $this->mTouched
= $newTouched;
1679 $this->clearSharedCache();
1681 // Clears on failure too since that is desired if the cache is stale
1682 $this->clearSharedCache( 'refresh' );
1689 * Clear various cached data stored in this object. The cache of the user table
1690 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1692 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1693 * given source. May be "name", "id", "actor", "defaults", "session", or false for no reload.
1695 public function clearInstanceCache( $reloadFrom = false ) {
1696 $this->mNewtalk
= -1;
1697 $this->mDatePreference
= null;
1698 $this->mBlockedby
= -1; # Unset
1699 $this->mHash
= false;
1700 $this->mRights
= null;
1701 $this->mEffectiveGroups
= null;
1702 $this->mImplicitGroups
= null;
1703 $this->mGroupMemberships
= null;
1704 $this->mOptions
= null;
1705 $this->mOptionsLoaded
= false;
1706 $this->mEditCount
= null;
1708 if ( $reloadFrom ) {
1709 $this->mLoadedItems
= [];
1710 $this->mFrom
= $reloadFrom;
1715 * Combine the language default options with any site-specific options
1716 * and add the default language variants.
1718 * @return array Array of String options
1720 public static function getDefaultOptions() {
1721 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1723 static $defOpt = null;
1724 static $defOptLang = null;
1726 if ( $defOpt !== null && $defOptLang === $wgContLang->getCode() ) {
1727 // $wgContLang does not change (and should not change) mid-request,
1728 // but the unit tests change it anyway, and expect this method to
1729 // return values relevant to the current $wgContLang.
1733 $defOpt = $wgDefaultUserOptions;
1734 // Default language setting
1735 $defOptLang = $wgContLang->getCode();
1736 $defOpt['language'] = $defOptLang;
1737 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1738 $defOpt[$langCode == $wgContLang->getCode() ?
'variant' : "variant-$langCode"] = $langCode;
1741 // NOTE: don't use SearchEngineConfig::getSearchableNamespaces here,
1742 // since extensions may change the set of searchable namespaces depending
1743 // on user groups/permissions.
1744 foreach ( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
1745 $defOpt['searchNs' . $nsnum] = (bool)$val;
1747 $defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1749 Hooks
::run( 'UserGetDefaultOptions', [ &$defOpt ] );
1755 * Get a given default option value.
1757 * @param string $opt Name of option to retrieve
1758 * @return string Default option value
1760 public static function getDefaultOption( $opt ) {
1761 $defOpts = self
::getDefaultOptions();
1762 if ( isset( $defOpts[$opt] ) ) {
1763 return $defOpts[$opt];
1770 * Get blocking information
1771 * @param bool $bFromSlave Whether to check the replica DB first.
1772 * To improve performance, non-critical checks are done against replica DBs.
1773 * Check when actually saving should be done against master.
1775 private function getBlockedStatus( $bFromSlave = true ) {
1776 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff, $wgSoftBlockRanges;
1778 if ( -1 != $this->mBlockedby
) {
1782 wfDebug( __METHOD__
. ": checking...\n" );
1784 // Initialize data...
1785 // Otherwise something ends up stomping on $this->mBlockedby when
1786 // things get lazy-loaded later, causing false positive block hits
1787 // due to -1 !== 0. Probably session-related... Nothing should be
1788 // overwriting mBlockedby, surely?
1791 # We only need to worry about passing the IP address to the Block generator if the
1792 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1793 # know which IP address they're actually coming from
1795 if ( !$this->isAllowed( 'ipblock-exempt' ) ) {
1796 // $wgUser->getName() only works after the end of Setup.php. Until
1797 // then, assume it's a logged-out user.
1798 $globalUserName = $wgUser->isSafeToLoad()
1799 ?
$wgUser->getName()
1800 : IP
::sanitizeIP( $wgUser->getRequest()->getIP() );
1801 if ( $this->getName() === $globalUserName ) {
1802 $ip = $this->getRequest()->getIP();
1807 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1810 if ( !$block instanceof Block
) {
1811 $block = $this->getBlockFromCookieValue( $this->getRequest()->getCookie( 'BlockID' ) );
1815 if ( !$block instanceof Block
&& $ip !== null && !in_array( $ip, $wgProxyWhitelist ) ) {
1817 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1818 $block = new Block( [
1819 'byText' => wfMessage( 'proxyblocker' )->text(),
1820 'reason' => wfMessage( 'proxyblockreason' )->text(),
1822 'systemBlock' => 'proxy',
1824 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1825 $block = new Block( [
1826 'byText' => wfMessage( 'sorbs' )->text(),
1827 'reason' => wfMessage( 'sorbsreason' )->text(),
1829 'systemBlock' => 'dnsbl',
1834 // (T25343) Apply IP blocks to the contents of XFF headers, if enabled
1835 if ( !$block instanceof Block
1836 && $wgApplyIpBlocksToXff
1838 && !in_array( $ip, $wgProxyWhitelist )
1840 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1841 $xff = array_map( 'trim', explode( ',', $xff ) );
1842 $xff = array_diff( $xff, [ $ip ] );
1843 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1844 $block = Block
::chooseBlock( $xffblocks, $xff );
1845 if ( $block instanceof Block
) {
1846 # Mangle the reason to alert the user that the block
1847 # originated from matching the X-Forwarded-For header.
1848 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->text();
1852 if ( !$block instanceof Block
1855 && IP
::isInRanges( $ip, $wgSoftBlockRanges )
1857 $block = new Block( [
1859 'byText' => 'MediaWiki default',
1860 'reason' => wfMessage( 'softblockrangesreason', $ip )->text(),
1862 'systemBlock' => 'wgSoftBlockRanges',
1866 if ( $block instanceof Block
) {
1867 wfDebug( __METHOD__
. ": Found block.\n" );
1868 $this->mBlock
= $block;
1869 $this->mBlockedby
= $block->getByName();
1870 $this->mBlockreason
= $block->mReason
;
1871 $this->mHideName
= $block->mHideName
;
1872 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1874 $this->mBlock
= null;
1875 $this->mBlockedby
= '';
1876 $this->mBlockreason
= '';
1877 $this->mHideName
= 0;
1878 $this->mAllowUsertalk
= false;
1881 // Avoid PHP 7.1 warning of passing $this by reference
1884 Hooks
::run( 'GetBlockedStatus', [ &$user ] );
1888 * Try to load a Block from an ID given in a cookie value.
1889 * @param string|null $blockCookieVal The cookie value to check.
1890 * @return Block|bool The Block object, or false if none could be loaded.
1892 protected function getBlockFromCookieValue( $blockCookieVal ) {
1893 // Make sure there's something to check. The cookie value must start with a number.
1894 if ( strlen( $blockCookieVal ) < 1 ||
!is_numeric( substr( $blockCookieVal, 0, 1 ) ) ) {
1897 // Load the Block from the ID in the cookie.
1898 $blockCookieId = Block
::getIdFromCookieValue( $blockCookieVal );
1899 if ( $blockCookieId !== null ) {
1900 // An ID was found in the cookie.
1901 $tmpBlock = Block
::newFromID( $blockCookieId );
1902 if ( $tmpBlock instanceof Block
) {
1903 // Check the validity of the block.
1904 $blockIsValid = $tmpBlock->getType() == Block
::TYPE_USER
1905 && !$tmpBlock->isExpired()
1906 && $tmpBlock->isAutoblocking();
1907 $config = RequestContext
::getMain()->getConfig();
1908 $useBlockCookie = ( $config->get( 'CookieSetOnAutoblock' ) === true );
1909 if ( $blockIsValid && $useBlockCookie ) {
1913 // If the block is not valid, remove the cookie.
1914 Block
::clearCookie( $this->getRequest()->response() );
1917 // If the block doesn't exist, remove the cookie.
1918 Block
::clearCookie( $this->getRequest()->response() );
1925 * Whether the given IP is in a DNS blacklist.
1927 * @param string $ip IP to check
1928 * @param bool $checkWhitelist Whether to check the whitelist first
1929 * @return bool True if blacklisted.
1931 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1932 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1934 if ( !$wgEnableDnsBlacklist ) {
1938 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1942 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1946 * Whether the given IP is in a given DNS blacklist.
1948 * @param string $ip IP to check
1949 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1950 * @return bool True if blacklisted.
1952 public function inDnsBlacklist( $ip, $bases ) {
1954 // @todo FIXME: IPv6 ??? (https://bugs.php.net/bug.php?id=33170)
1955 if ( IP
::isIPv4( $ip ) ) {
1956 // Reverse IP, T23255
1957 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1959 foreach ( (array)$bases as $base ) {
1961 // If we have an access key, use that too (ProjectHoneypot, etc.)
1963 if ( is_array( $base ) ) {
1964 if ( count( $base ) >= 2 ) {
1965 // Access key is 1, base URL is 0
1966 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1968 $host = "$ipReversed.{$base[0]}";
1970 $basename = $base[0];
1972 $host = "$ipReversed.$base";
1976 $ipList = gethostbynamel( $host );
1979 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
1983 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
1992 * Check if an IP address is in the local proxy list
1998 public static function isLocallyBlockedProxy( $ip ) {
1999 global $wgProxyList;
2001 if ( !$wgProxyList ) {
2005 if ( !is_array( $wgProxyList ) ) {
2006 // Load values from the specified file
2007 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
2010 $resultProxyList = [];
2011 $deprecatedIPEntries = [];
2013 // backward compatibility: move all ip addresses in keys to values
2014 foreach ( $wgProxyList as $key => $value ) {
2015 $keyIsIP = IP
::isIPAddress( $key );
2016 $valueIsIP = IP
::isIPAddress( $value );
2017 if ( $keyIsIP && !$valueIsIP ) {
2018 $deprecatedIPEntries[] = $key;
2019 $resultProxyList[] = $key;
2020 } elseif ( $keyIsIP && $valueIsIP ) {
2021 $deprecatedIPEntries[] = $key;
2022 $resultProxyList[] = $key;
2023 $resultProxyList[] = $value;
2025 $resultProxyList[] = $value;
2029 if ( $deprecatedIPEntries ) {
2031 'IP addresses in the keys of $wgProxyList (found the following IP addresses in keys: ' .
2032 implode( ', ', $deprecatedIPEntries ) . ', please move them to values)', '1.30' );
2035 $proxyListIPSet = new IPSet( $resultProxyList );
2036 return $proxyListIPSet->match( $ip );
2040 * Is this user subject to rate limiting?
2042 * @return bool True if rate limited
2044 public function isPingLimitable() {
2045 global $wgRateLimitsExcludedIPs;
2046 if ( IP
::isInRanges( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
2047 // No other good way currently to disable rate limits
2048 // for specific IPs. :P
2049 // But this is a crappy hack and should die.
2052 return !$this->isAllowed( 'noratelimit' );
2056 * Primitive rate limits: enforce maximum actions per time period
2057 * to put a brake on flooding.
2059 * The method generates both a generic profiling point and a per action one
2060 * (suffix being "-$action".
2062 * @note When using a shared cache like memcached, IP-address
2063 * last-hit counters will be shared across wikis.
2065 * @param string $action Action to enforce; 'edit' if unspecified
2066 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
2067 * @return bool True if a rate limiter was tripped
2069 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
2070 // Avoid PHP 7.1 warning of passing $this by reference
2072 // Call the 'PingLimiter' hook
2074 if ( !Hooks
::run( 'PingLimiter', [ &$user, $action, &$result, $incrBy ] ) ) {
2078 global $wgRateLimits;
2079 if ( !isset( $wgRateLimits[$action] ) ) {
2083 $limits = array_merge(
2084 [ '&can-bypass' => true ],
2085 $wgRateLimits[$action]
2088 // Some groups shouldn't trigger the ping limiter, ever
2089 if ( $limits['&can-bypass'] && !$this->isPingLimitable() ) {
2094 $id = $this->getId();
2096 $isNewbie = $this->isNewbie();
2097 $cache = ObjectCache
::getLocalClusterInstance();
2101 if ( isset( $limits['anon'] ) ) {
2102 $keys[$cache->makeKey( 'limiter', $action, 'anon' )] = $limits['anon'];
2105 // limits for logged-in users
2106 if ( isset( $limits['user'] ) ) {
2107 $userLimit = $limits['user'];
2109 // limits for newbie logged-in users
2110 if ( $isNewbie && isset( $limits['newbie'] ) ) {
2111 $keys[$cache->makeKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
2115 // limits for anons and for newbie logged-in users
2118 if ( isset( $limits['ip'] ) ) {
2119 $ip = $this->getRequest()->getIP();
2120 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
2122 // subnet-based limits
2123 if ( isset( $limits['subnet'] ) ) {
2124 $ip = $this->getRequest()->getIP();
2125 $subnet = IP
::getSubnet( $ip );
2126 if ( $subnet !== false ) {
2127 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
2132 // Check for group-specific permissions
2133 // If more than one group applies, use the group with the highest limit ratio (max/period)
2134 foreach ( $this->getGroups() as $group ) {
2135 if ( isset( $limits[$group] ) ) {
2136 if ( $userLimit === false
2137 ||
$limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
2139 $userLimit = $limits[$group];
2144 // Set the user limit key
2145 if ( $userLimit !== false ) {
2146 list( $max, $period ) = $userLimit;
2147 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
2148 $keys[$cache->makeKey( 'limiter', $action, 'user', $id )] = $userLimit;
2151 // ip-based limits for all ping-limitable users
2152 if ( isset( $limits['ip-all'] ) ) {
2153 $ip = $this->getRequest()->getIP();
2154 // ignore if user limit is more permissive
2155 if ( $isNewbie ||
$userLimit === false
2156 ||
$limits['ip-all'][0] / $limits['ip-all'][1] > $userLimit[0] / $userLimit[1] ) {
2157 $keys["mediawiki:limiter:$action:ip-all:$ip"] = $limits['ip-all'];
2161 // subnet-based limits for all ping-limitable users
2162 if ( isset( $limits['subnet-all'] ) ) {
2163 $ip = $this->getRequest()->getIP();
2164 $subnet = IP
::getSubnet( $ip );
2165 if ( $subnet !== false ) {
2166 // ignore if user limit is more permissive
2167 if ( $isNewbie ||
$userLimit === false
2168 ||
$limits['ip-all'][0] / $limits['ip-all'][1]
2169 > $userLimit[0] / $userLimit[1] ) {
2170 $keys["mediawiki:limiter:$action:subnet-all:$subnet"] = $limits['subnet-all'];
2176 foreach ( $keys as $key => $limit ) {
2177 list( $max, $period ) = $limit;
2178 $summary = "(limit $max in {$period}s)";
2179 $count = $cache->get( $key );
2182 if ( $count >= $max ) {
2183 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
2184 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
2187 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
2190 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
2191 if ( $incrBy > 0 ) {
2192 $cache->add( $key, 0, intval( $period ) ); // first ping
2195 if ( $incrBy > 0 ) {
2196 $cache->incr( $key, $incrBy );
2204 * Check if user is blocked
2206 * @param bool $bFromSlave Whether to check the replica DB instead of
2207 * the master. Hacked from false due to horrible probs on site.
2208 * @return bool True if blocked, false otherwise
2210 public function isBlocked( $bFromSlave = true ) {
2211 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
2215 * Get the block affecting the user, or null if the user is not blocked
2217 * @param bool $bFromSlave Whether to check the replica DB instead of the master
2218 * @return Block|null
2220 public function getBlock( $bFromSlave = true ) {
2221 $this->getBlockedStatus( $bFromSlave );
2222 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
2226 * Check if user is blocked from editing a particular article
2228 * @param Title $title Title to check
2229 * @param bool $bFromSlave Whether to check the replica DB instead of the master
2232 public function isBlockedFrom( $title, $bFromSlave = false ) {
2233 global $wgBlockAllowsUTEdit;
2235 $blocked = $this->isBlocked( $bFromSlave );
2236 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
2237 // If a user's name is suppressed, they cannot make edits anywhere
2238 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName()
2239 && $title->getNamespace() == NS_USER_TALK
) {
2241 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
2244 Hooks
::run( 'UserIsBlockedFrom', [ $this, $title, &$blocked, &$allowUsertalk ] );
2250 * If user is blocked, return the name of the user who placed the block
2251 * @return string Name of blocker
2253 public function blockedBy() {
2254 $this->getBlockedStatus();
2255 return $this->mBlockedby
;
2259 * If user is blocked, return the specified reason for the block
2260 * @return string Blocking reason
2262 public function blockedFor() {
2263 $this->getBlockedStatus();
2264 return $this->mBlockreason
;
2268 * If user is blocked, return the ID for the block
2269 * @return int Block ID
2271 public function getBlockId() {
2272 $this->getBlockedStatus();
2273 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
2277 * Check if user is blocked on all wikis.
2278 * Do not use for actual edit permission checks!
2279 * This is intended for quick UI checks.
2281 * @param string $ip IP address, uses current client if none given
2282 * @return bool True if blocked, false otherwise
2284 public function isBlockedGlobally( $ip = '' ) {
2285 return $this->getGlobalBlock( $ip ) instanceof Block
;
2289 * Check if user is blocked on all wikis.
2290 * Do not use for actual edit permission checks!
2291 * This is intended for quick UI checks.
2293 * @param string $ip IP address, uses current client if none given
2294 * @return Block|null Block object if blocked, null otherwise
2295 * @throws FatalError
2296 * @throws MWException
2298 public function getGlobalBlock( $ip = '' ) {
2299 if ( $this->mGlobalBlock
!== null ) {
2300 return $this->mGlobalBlock ?
: null;
2302 // User is already an IP?
2303 if ( IP
::isIPAddress( $this->getName() ) ) {
2304 $ip = $this->getName();
2306 $ip = $this->getRequest()->getIP();
2308 // Avoid PHP 7.1 warning of passing $this by reference
2312 Hooks
::run( 'UserIsBlockedGlobally', [ &$user, $ip, &$blocked, &$block ] );
2314 if ( $blocked && $block === null ) {
2315 // back-compat: UserIsBlockedGlobally didn't have $block param first
2316 $block = new Block( [
2318 'systemBlock' => 'global-block'
2322 $this->mGlobalBlock
= $blocked ?
$block : false;
2323 return $this->mGlobalBlock ?
: null;
2327 * Check if user account is locked
2329 * @return bool True if locked, false otherwise
2331 public function isLocked() {
2332 if ( $this->mLocked
!== null ) {
2333 return $this->mLocked
;
2335 // Avoid PHP 7.1 warning of passing $this by reference
2337 $authUser = AuthManager
::callLegacyAuthPlugin( 'getUserInstance', [ &$user ], null );
2338 $this->mLocked
= $authUser && $authUser->isLocked();
2339 Hooks
::run( 'UserIsLocked', [ $this, &$this->mLocked
] );
2340 return $this->mLocked
;
2344 * Check if user account is hidden
2346 * @return bool True if hidden, false otherwise
2348 public function isHidden() {
2349 if ( $this->mHideName
!== null ) {
2350 return $this->mHideName
;
2352 $this->getBlockedStatus();
2353 if ( !$this->mHideName
) {
2354 // Avoid PHP 7.1 warning of passing $this by reference
2356 $authUser = AuthManager
::callLegacyAuthPlugin( 'getUserInstance', [ &$user ], null );
2357 $this->mHideName
= $authUser && $authUser->isHidden();
2358 Hooks
::run( 'UserIsHidden', [ $this, &$this->mHideName
] );
2360 return $this->mHideName
;
2364 * Get the user's ID.
2365 * @return int The user's ID; 0 if the user is anonymous or nonexistent
2367 public function getId() {
2368 if ( $this->mId
=== null && $this->mName
!== null && self
::isIP( $this->mName
) ) {
2369 // Special case, we know the user is anonymous
2371 } elseif ( !$this->isItemLoaded( 'id' ) ) {
2372 // Don't load if this was initialized from an ID
2376 return (int)$this->mId
;
2380 * Set the user and reload all fields according to a given ID
2381 * @param int $v User ID to reload
2383 public function setId( $v ) {
2385 $this->clearInstanceCache( 'id' );
2389 * Get the user name, or the IP of an anonymous user
2390 * @return string User's name or IP address
2392 public function getName() {
2393 if ( $this->isItemLoaded( 'name', 'only' ) ) {
2394 // Special case optimisation
2395 return $this->mName
;
2398 if ( $this->mName
=== false ) {
2400 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
2402 return $this->mName
;
2407 * Set the user name.
2409 * This does not reload fields from the database according to the given
2410 * name. Rather, it is used to create a temporary "nonexistent user" for
2411 * later addition to the database. It can also be used to set the IP
2412 * address for an anonymous user to something other than the current
2415 * @note User::newFromName() has roughly the same function, when the named user
2417 * @param string $str New user name to set
2419 public function setName( $str ) {
2421 $this->mName
= $str;
2425 * Get the user's actor ID.
2427 * @param IDatabase|null $dbw Assign a new actor ID, using this DB handle, if none exists
2428 * @return int The actor's ID, or 0 if no actor ID exists and $dbw was null
2430 public function getActorId( IDatabase
$dbw = null ) {
2431 global $wgActorTableSchemaMigrationStage;
2433 if ( $wgActorTableSchemaMigrationStage <= MIGRATION_OLD
) {
2437 if ( !$this->isItemLoaded( 'actor' ) ) {
2441 // Currently $this->mActorId might be null if $this was loaded from a
2442 // cache entry that was written when $wgActorTableSchemaMigrationStage
2443 // was MIGRATION_OLD. Once that is no longer a possibility (i.e. when
2444 // User::VERSION is incremented after $wgActorTableSchemaMigrationStage
2445 // has been removed), that condition may be removed.
2446 if ( $this->mActorId
=== null ||
!$this->mActorId
&& $dbw ) {
2448 'actor_user' => $this->getId() ?
: null,
2449 'actor_name' => (string)$this->getName(),
2452 if ( $q['actor_user'] === null && self
::isUsableName( $q['actor_name'] ) ) {
2453 throw new CannotCreateActorException(
2454 'Cannot create an actor for a usable name that is not an existing user'
2457 if ( $q['actor_name'] === '' ) {
2458 throw new CannotCreateActorException( 'Cannot create an actor for a user with no name' );
2460 $dbw->insert( 'actor', $q, __METHOD__
, [ 'IGNORE' ] );
2461 if ( $dbw->affectedRows() ) {
2462 $this->mActorId
= (int)$dbw->insertId();
2465 list( , $options ) = DBAccessObjectUtils
::getDBOptions( $this->queryFlagsUsed
);
2466 $this->mActorId
= (int)$dbw->selectField( 'actor', 'actor_id', $q, __METHOD__
, $options );
2467 if ( !$this->mActorId
) {
2468 throw new CannotCreateActorException(
2469 "Cannot create actor ID for user_id={$this->getId()} user_name={$this->getName()}"
2473 $this->invalidateCache();
2475 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $this->queryFlagsUsed
);
2476 $db = wfGetDB( $index );
2477 $this->mActorId
= (int)$db->selectField( 'actor', 'actor_id', $q, __METHOD__
, $options );
2479 $this->setItemLoaded( 'actor' );
2482 return (int)$this->mActorId
;
2486 * Get the user's name escaped by underscores.
2487 * @return string Username escaped by underscores.
2489 public function getTitleKey() {
2490 return str_replace( ' ', '_', $this->getName() );
2494 * Check if the user has new messages.
2495 * @return bool True if the user has new messages
2497 public function getNewtalk() {
2500 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2501 if ( $this->mNewtalk
=== -1 ) {
2502 $this->mNewtalk
= false; # reset talk page status
2504 // Check memcached separately for anons, who have no
2505 // entire User object stored in there.
2506 if ( !$this->mId
) {
2507 global $wgDisableAnonTalk;
2508 if ( $wgDisableAnonTalk ) {
2509 // Anon newtalk disabled by configuration.
2510 $this->mNewtalk
= false;
2512 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
2515 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2519 return (bool)$this->mNewtalk
;
2523 * Return the data needed to construct links for new talk page message
2524 * alerts. If there are new messages, this will return an associative array
2525 * with the following data:
2526 * wiki: The database name of the wiki
2527 * link: Root-relative link to the user's talk page
2528 * rev: The last talk page revision that the user has seen or null. This
2529 * is useful for building diff links.
2530 * If there are no new messages, it returns an empty array.
2531 * @note This function was designed to accomodate multiple talk pages, but
2532 * currently only returns a single link and revision.
2535 public function getNewMessageLinks() {
2536 // Avoid PHP 7.1 warning of passing $this by reference
2539 if ( !Hooks
::run( 'UserRetrieveNewTalks', [ &$user, &$talks ] ) ) {
2541 } elseif ( !$this->getNewtalk() ) {
2544 $utp = $this->getTalkPage();
2545 $dbr = wfGetDB( DB_REPLICA
);
2546 // Get the "last viewed rev" timestamp from the oldest message notification
2547 $timestamp = $dbr->selectField( 'user_newtalk',
2548 'MIN(user_last_timestamp)',
2549 $this->isAnon() ?
[ 'user_ip' => $this->getName() ] : [ 'user_id' => $this->getId() ],
2551 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2552 return [ [ 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ] ];
2556 * Get the revision ID for the last talk page revision viewed by the talk
2558 * @return int|null Revision ID or null
2560 public function getNewMessageRevisionId() {
2561 $newMessageRevisionId = null;
2562 $newMessageLinks = $this->getNewMessageLinks();
2563 if ( $newMessageLinks ) {
2564 // Note: getNewMessageLinks() never returns more than a single link
2565 // and it is always for the same wiki, but we double-check here in
2566 // case that changes some time in the future.
2567 if ( count( $newMessageLinks ) === 1
2568 && $newMessageLinks[0]['wiki'] === wfWikiID()
2569 && $newMessageLinks[0]['rev']
2571 /** @var Revision $newMessageRevision */
2572 $newMessageRevision = $newMessageLinks[0]['rev'];
2573 $newMessageRevisionId = $newMessageRevision->getId();
2576 return $newMessageRevisionId;
2580 * Internal uncached check for new messages
2583 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2584 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2585 * @return bool True if the user has new messages
2587 protected function checkNewtalk( $field, $id ) {
2588 $dbr = wfGetDB( DB_REPLICA
);
2590 $ok = $dbr->selectField( 'user_newtalk', $field, [ $field => $id ], __METHOD__
);
2592 return $ok !== false;
2596 * Add or update the new messages flag
2597 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2598 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2599 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2600 * @return bool True if successful, false otherwise
2602 protected function updateNewtalk( $field, $id, $curRev = null ) {
2603 // Get timestamp of the talk page revision prior to the current one
2604 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2605 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2606 // Mark the user as having new messages since this revision
2607 $dbw = wfGetDB( DB_MASTER
);
2608 $dbw->insert( 'user_newtalk',
2609 [ $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ],
2612 if ( $dbw->affectedRows() ) {
2613 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2616 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2622 * Clear the new messages flag for the given user
2623 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2624 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2625 * @return bool True if successful, false otherwise
2627 protected function deleteNewtalk( $field, $id ) {
2628 $dbw = wfGetDB( DB_MASTER
);
2629 $dbw->delete( 'user_newtalk',
2632 if ( $dbw->affectedRows() ) {
2633 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2636 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2642 * Update the 'You have new messages!' status.
2643 * @param bool $val Whether the user has new messages
2644 * @param Revision $curRev New, as yet unseen revision of the user talk
2645 * page. Ignored if null or !$val.
2647 public function setNewtalk( $val, $curRev = null ) {
2648 if ( wfReadOnly() ) {
2653 $this->mNewtalk
= $val;
2655 if ( $this->isAnon() ) {
2657 $id = $this->getName();
2660 $id = $this->getId();
2664 $changed = $this->updateNewtalk( $field, $id, $curRev );
2666 $changed = $this->deleteNewtalk( $field, $id );
2670 $this->invalidateCache();
2675 * Generate a current or new-future timestamp to be stored in the
2676 * user_touched field when we update things.
2677 * @return string Timestamp in TS_MW format
2679 private function newTouchedTimestamp() {
2680 global $wgClockSkewFudge;
2682 $time = wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2683 if ( $this->mTouched
&& $time <= $this->mTouched
) {
2684 $time = wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $this->mTouched
) +
1 );
2691 * Clear user data from memcached
2693 * Use after applying updates to the database; caller's
2694 * responsibility to update user_touched if appropriate.
2696 * Called implicitly from invalidateCache() and saveSettings().
2698 * @param string $mode Use 'refresh' to clear now; otherwise before DB commit
2700 public function clearSharedCache( $mode = 'changed' ) {
2701 if ( !$this->getId() ) {
2705 $cache = ObjectCache
::getMainWANInstance();
2706 $key = $this->getCacheKey( $cache );
2707 if ( $mode === 'refresh' ) {
2708 $cache->delete( $key, 1 );
2710 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
2711 if ( $lb->hasOrMadeRecentMasterChanges() ) {
2712 $lb->getConnection( DB_MASTER
)->onTransactionPreCommitOrIdle(
2713 function () use ( $cache, $key ) {
2714 $cache->delete( $key );
2719 $cache->delete( $key );
2725 * Immediately touch the user data cache for this account
2727 * Calls touch() and removes account data from memcached
2729 public function invalidateCache() {
2731 $this->clearSharedCache();
2735 * Update the "touched" timestamp for the user
2737 * This is useful on various login/logout events when making sure that
2738 * a browser or proxy that has multiple tenants does not suffer cache
2739 * pollution where the new user sees the old users content. The value
2740 * of getTouched() is checked when determining 304 vs 200 responses.
2741 * Unlike invalidateCache(), this preserves the User object cache and
2742 * avoids database writes.
2746 public function touch() {
2747 $id = $this->getId();
2749 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
2750 $key = $cache->makeKey( 'user-quicktouched', 'id', $id );
2751 $cache->touchCheckKey( $key );
2752 $this->mQuickTouched
= null;
2757 * Validate the cache for this account.
2758 * @param string $timestamp A timestamp in TS_MW format
2761 public function validateCache( $timestamp ) {
2762 return ( $timestamp >= $this->getTouched() );
2766 * Get the user touched timestamp
2768 * Use this value only to validate caches via inequalities
2769 * such as in the case of HTTP If-Modified-Since response logic
2771 * @return string TS_MW Timestamp
2773 public function getTouched() {
2777 if ( $this->mQuickTouched
=== null ) {
2778 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
2779 $key = $cache->makeKey( 'user-quicktouched', 'id', $this->mId
);
2781 $this->mQuickTouched
= wfTimestamp( TS_MW
, $cache->getCheckKeyTime( $key ) );
2784 return max( $this->mTouched
, $this->mQuickTouched
);
2787 return $this->mTouched
;
2791 * Get the user_touched timestamp field (time of last DB updates)
2792 * @return string TS_MW Timestamp
2795 public function getDBTouched() {
2798 return $this->mTouched
;
2802 * Set the password and reset the random token.
2803 * Calls through to authentication plugin if necessary;
2804 * will have no effect if the auth plugin refuses to
2805 * pass the change through or if the legal password
2808 * As a special case, setting the password to null
2809 * wipes it, so the account cannot be logged in until
2810 * a new password is set, for instance via e-mail.
2812 * @deprecated since 1.27, use AuthManager instead
2813 * @param string $str New password to set
2814 * @throws PasswordError On failure
2817 public function setPassword( $str ) {
2818 return $this->setPasswordInternal( $str );
2822 * Set the password and reset the random token unconditionally.
2824 * @deprecated since 1.27, use AuthManager instead
2825 * @param string|null $str New password to set or null to set an invalid
2826 * password hash meaning that the user will not be able to log in
2827 * through the web interface.
2829 public function setInternalPassword( $str ) {
2830 $this->setPasswordInternal( $str );
2834 * Actually set the password and such
2835 * @since 1.27 cannot set a password for a user not in the database
2836 * @param string|null $str New password to set or null to set an invalid
2837 * password hash meaning that the user will not be able to log in
2838 * through the web interface.
2839 * @return bool Success
2841 private function setPasswordInternal( $str ) {
2842 $manager = AuthManager
::singleton();
2844 // If the user doesn't exist yet, fail
2845 if ( !$manager->userExists( $this->getName() ) ) {
2846 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2849 $status = $this->changeAuthenticationData( [
2850 'username' => $this->getName(),
2854 if ( !$status->isGood() ) {
2855 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
2856 ->info( __METHOD__
. ': Password change rejected: '
2857 . $status->getWikiText( null, null, 'en' ) );
2861 $this->setOption( 'watchlisttoken', false );
2862 SessionManager
::singleton()->invalidateSessionsForUser( $this );
2868 * Changes credentials of the user.
2870 * This is a convenience wrapper around AuthManager::changeAuthenticationData.
2871 * Note that this can return a status that isOK() but not isGood() on certain types of failures,
2872 * e.g. when no provider handled the change.
2874 * @param array $data A set of authentication data in fieldname => value format. This is the
2875 * same data you would pass the changeauthenticationdata API - 'username', 'password' etc.
2879 public function changeAuthenticationData( array $data ) {
2880 $manager = AuthManager
::singleton();
2881 $reqs = $manager->getAuthenticationRequests( AuthManager
::ACTION_CHANGE
, $this );
2882 $reqs = AuthenticationRequest
::loadRequestsFromSubmission( $reqs, $data );
2884 $status = Status
::newGood( 'ignored' );
2885 foreach ( $reqs as $req ) {
2886 $status->merge( $manager->allowsAuthenticationDataChange( $req ), true );
2888 if ( $status->getValue() === 'ignored' ) {
2889 $status->warning( 'authenticationdatachange-ignored' );
2892 if ( $status->isGood() ) {
2893 foreach ( $reqs as $req ) {
2894 $manager->changeAuthenticationData( $req );
2901 * Get the user's current token.
2902 * @param bool $forceCreation Force the generation of a new token if the
2903 * user doesn't have one (default=true for backwards compatibility).
2904 * @return string|null Token
2906 public function getToken( $forceCreation = true ) {
2907 global $wgAuthenticationTokenVersion;
2910 if ( !$this->mToken
&& $forceCreation ) {
2914 if ( !$this->mToken
) {
2915 // The user doesn't have a token, return null to indicate that.
2917 } elseif ( $this->mToken
=== self
::INVALID_TOKEN
) {
2918 // We return a random value here so existing token checks are very
2920 return MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2921 } elseif ( $wgAuthenticationTokenVersion === null ) {
2922 // $wgAuthenticationTokenVersion not in use, so return the raw secret
2923 return $this->mToken
;
2925 // $wgAuthenticationTokenVersion in use, so hmac it.
2926 $ret = MWCryptHash
::hmac( $wgAuthenticationTokenVersion, $this->mToken
, false );
2928 // The raw hash can be overly long. Shorten it up.
2929 $len = max( 32, self
::TOKEN_LENGTH
);
2930 if ( strlen( $ret ) < $len ) {
2931 // Should never happen, even md5 is 128 bits
2932 throw new \
UnexpectedValueException( 'Hmac returned less than 128 bits' );
2934 return substr( $ret, -$len );
2939 * Set the random token (used for persistent authentication)
2940 * Called from loadDefaults() among other places.
2942 * @param string|bool $token If specified, set the token to this value
2944 public function setToken( $token = false ) {
2946 if ( $this->mToken
=== self
::INVALID_TOKEN
) {
2947 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
2948 ->debug( __METHOD__
. ": Ignoring attempt to set token for system user \"$this\"" );
2949 } elseif ( !$token ) {
2950 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2952 $this->mToken
= $token;
2957 * Set the password for a password reminder or new account email
2959 * @deprecated Removed in 1.27. Use PasswordReset instead.
2960 * @param string $str New password to set or null to set an invalid
2961 * password hash meaning that the user will not be able to use it
2962 * @param bool $throttle If true, reset the throttle timestamp to the present
2964 public function setNewpassword( $str, $throttle = true ) {
2965 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2969 * Get the user's e-mail address
2970 * @return string User's email address
2972 public function getEmail() {
2974 Hooks
::run( 'UserGetEmail', [ $this, &$this->mEmail
] );
2975 return $this->mEmail
;
2979 * Get the timestamp of the user's e-mail authentication
2980 * @return string TS_MW timestamp
2982 public function getEmailAuthenticationTimestamp() {
2984 Hooks
::run( 'UserGetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
2985 return $this->mEmailAuthenticated
;
2989 * Set the user's e-mail address
2990 * @param string $str New e-mail address
2992 public function setEmail( $str ) {
2994 if ( $str == $this->mEmail
) {
2997 $this->invalidateEmail();
2998 $this->mEmail
= $str;
2999 Hooks
::run( 'UserSetEmail', [ $this, &$this->mEmail
] );
3003 * Set the user's e-mail address and a confirmation mail if needed.
3006 * @param string $str New e-mail address
3009 public function setEmailWithConfirmation( $str ) {
3010 global $wgEnableEmail, $wgEmailAuthentication;
3012 if ( !$wgEnableEmail ) {
3013 return Status
::newFatal( 'emaildisabled' );
3016 $oldaddr = $this->getEmail();
3017 if ( $str === $oldaddr ) {
3018 return Status
::newGood( true );
3021 $type = $oldaddr != '' ?
'changed' : 'set';
3022 $notificationResult = null;
3024 if ( $wgEmailAuthentication ) {
3025 // Send the user an email notifying the user of the change in registered
3026 // email address on their previous email address
3027 if ( $type == 'changed' ) {
3028 $change = $str != '' ?
'changed' : 'removed';
3029 $notificationResult = $this->sendMail(
3030 wfMessage( 'notificationemail_subject_' . $change )->text(),
3031 wfMessage( 'notificationemail_body_' . $change,
3032 $this->getRequest()->getIP(),
3039 $this->setEmail( $str );
3041 if ( $str !== '' && $wgEmailAuthentication ) {
3042 // Send a confirmation request to the new address if needed
3043 $result = $this->sendConfirmationMail( $type );
3045 if ( $notificationResult !== null ) {
3046 $result->merge( $notificationResult );
3049 if ( $result->isGood() ) {
3050 // Say to the caller that a confirmation and notification mail has been sent
3051 $result->value
= 'eauth';
3054 $result = Status
::newGood( true );
3061 * Get the user's real name
3062 * @return string User's real name
3064 public function getRealName() {
3065 if ( !$this->isItemLoaded( 'realname' ) ) {
3069 return $this->mRealName
;
3073 * Set the user's real name
3074 * @param string $str New real name
3076 public function setRealName( $str ) {
3078 $this->mRealName
= $str;
3082 * Get the user's current setting for a given option.
3084 * @param string $oname The option to check
3085 * @param string $defaultOverride A default value returned if the option does not exist
3086 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
3087 * @return string|array|int|null User's current value for the option
3088 * @see getBoolOption()
3089 * @see getIntOption()
3091 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
3092 global $wgHiddenPrefs;
3093 $this->loadOptions();
3095 # We want 'disabled' preferences to always behave as the default value for
3096 # users, even if they have set the option explicitly in their settings (ie they
3097 # set it, and then it was disabled removing their ability to change it). But
3098 # we don't want to erase the preferences in the database in case the preference
3099 # is re-enabled again. So don't touch $mOptions, just override the returned value
3100 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
3101 return self
::getDefaultOption( $oname );
3104 if ( array_key_exists( $oname, $this->mOptions
) ) {
3105 return $this->mOptions
[$oname];
3107 return $defaultOverride;
3112 * Get all user's options
3114 * @param int $flags Bitwise combination of:
3115 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
3116 * to the default value. (Since 1.25)
3119 public function getOptions( $flags = 0 ) {
3120 global $wgHiddenPrefs;
3121 $this->loadOptions();
3122 $options = $this->mOptions
;
3124 # We want 'disabled' preferences to always behave as the default value for
3125 # users, even if they have set the option explicitly in their settings (ie they
3126 # set it, and then it was disabled removing their ability to change it). But
3127 # we don't want to erase the preferences in the database in case the preference
3128 # is re-enabled again. So don't touch $mOptions, just override the returned value
3129 foreach ( $wgHiddenPrefs as $pref ) {
3130 $default = self
::getDefaultOption( $pref );
3131 if ( $default !== null ) {
3132 $options[$pref] = $default;
3136 if ( $flags & self
::GETOPTIONS_EXCLUDE_DEFAULTS
) {
3137 $options = array_diff_assoc( $options, self
::getDefaultOptions() );
3144 * Get the user's current setting for a given option, as a boolean value.
3146 * @param string $oname The option to check
3147 * @return bool User's current value for the option
3150 public function getBoolOption( $oname ) {
3151 return (bool)$this->getOption( $oname );
3155 * Get the user's current setting for a given option, as an integer value.
3157 * @param string $oname The option to check
3158 * @param int $defaultOverride A default value returned if the option does not exist
3159 * @return int User's current value for the option
3162 public function getIntOption( $oname, $defaultOverride = 0 ) {
3163 $val = $this->getOption( $oname );
3165 $val = $defaultOverride;
3167 return intval( $val );
3171 * Set the given option for a user.
3173 * You need to call saveSettings() to actually write to the database.
3175 * @param string $oname The option to set
3176 * @param mixed $val New value to set
3178 public function setOption( $oname, $val ) {
3179 $this->loadOptions();
3181 // Explicitly NULL values should refer to defaults
3182 if ( is_null( $val ) ) {
3183 $val = self
::getDefaultOption( $oname );
3186 $this->mOptions
[$oname] = $val;
3190 * Get a token stored in the preferences (like the watchlist one),
3191 * resetting it if it's empty (and saving changes).
3193 * @param string $oname The option name to retrieve the token from
3194 * @return string|bool User's current value for the option, or false if this option is disabled.
3195 * @see resetTokenFromOption()
3197 * @deprecated since 1.26 Applications should use the OAuth extension
3199 public function getTokenFromOption( $oname ) {
3200 global $wgHiddenPrefs;
3202 $id = $this->getId();
3203 if ( !$id ||
in_array( $oname, $wgHiddenPrefs ) ) {
3207 $token = $this->getOption( $oname );
3209 // Default to a value based on the user token to avoid space
3210 // wasted on storing tokens for all users. When this option
3211 // is set manually by the user, only then is it stored.
3212 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
3219 * Reset a token stored in the preferences (like the watchlist one).
3220 * *Does not* save user's preferences (similarly to setOption()).
3222 * @param string $oname The option name to reset the token in
3223 * @return string|bool New token value, or false if this option is disabled.
3224 * @see getTokenFromOption()
3227 public function resetTokenFromOption( $oname ) {
3228 global $wgHiddenPrefs;
3229 if ( in_array( $oname, $wgHiddenPrefs ) ) {
3233 $token = MWCryptRand
::generateHex( 40 );
3234 $this->setOption( $oname, $token );
3239 * Return a list of the types of user options currently returned by
3240 * User::getOptionKinds().
3242 * Currently, the option kinds are:
3243 * - 'registered' - preferences which are registered in core MediaWiki or
3244 * by extensions using the UserGetDefaultOptions hook.
3245 * - 'registered-multiselect' - as above, using the 'multiselect' type.
3246 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
3247 * - 'userjs' - preferences with names starting with 'userjs-', intended to
3248 * be used by user scripts.
3249 * - 'special' - "preferences" that are not accessible via User::getOptions
3250 * or User::setOptions.
3251 * - 'unused' - preferences about which MediaWiki doesn't know anything.
3252 * These are usually legacy options, removed in newer versions.
3254 * The API (and possibly others) use this function to determine the possible
3255 * option types for validation purposes, so make sure to update this when a
3256 * new option kind is added.
3258 * @see User::getOptionKinds
3259 * @return array Option kinds
3261 public static function listOptionKinds() {
3264 'registered-multiselect',
3265 'registered-checkmatrix',
3273 * Return an associative array mapping preferences keys to the kind of a preference they're
3274 * used for. Different kinds are handled differently when setting or reading preferences.
3276 * See User::listOptionKinds for the list of valid option types that can be provided.
3278 * @see User::listOptionKinds
3279 * @param IContextSource $context
3280 * @param array $options Assoc. array with options keys to check as keys.
3281 * Defaults to $this->mOptions.
3282 * @return array The key => kind mapping data
3284 public function getOptionKinds( IContextSource
$context, $options = null ) {
3285 $this->loadOptions();
3286 if ( $options === null ) {
3287 $options = $this->mOptions
;
3290 $preferencesFactory = MediaWikiServices
::getInstance()->getPreferencesFactory();
3291 $prefs = $preferencesFactory->getFormDescriptor( $this, $context );
3294 // Pull out the "special" options, so they don't get converted as
3295 // multiselect or checkmatrix.
3296 $specialOptions = array_fill_keys( $preferencesFactory->getSaveBlacklist(), true );
3297 foreach ( $specialOptions as $name => $value ) {
3298 unset( $prefs[$name] );
3301 // Multiselect and checkmatrix options are stored in the database with
3302 // one key per option, each having a boolean value. Extract those keys.
3303 $multiselectOptions = [];
3304 foreach ( $prefs as $name => $info ) {
3305 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
3306 ( isset( $info['class'] ) && $info['class'] == HTMLMultiSelectField
::class ) ) {
3307 $opts = HTMLFormField
::flattenOptions( $info['options'] );
3308 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
3310 foreach ( $opts as $value ) {
3311 $multiselectOptions["$prefix$value"] = true;
3314 unset( $prefs[$name] );
3317 $checkmatrixOptions = [];
3318 foreach ( $prefs as $name => $info ) {
3319 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
3320 ( isset( $info['class'] ) && $info['class'] == HTMLCheckMatrix
::class ) ) {
3321 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
3322 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
3323 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
3325 foreach ( $columns as $column ) {
3326 foreach ( $rows as $row ) {
3327 $checkmatrixOptions["$prefix$column-$row"] = true;
3331 unset( $prefs[$name] );
3335 // $value is ignored
3336 foreach ( $options as $key => $value ) {
3337 if ( isset( $prefs[$key] ) ) {
3338 $mapping[$key] = 'registered';
3339 } elseif ( isset( $multiselectOptions[$key] ) ) {
3340 $mapping[$key] = 'registered-multiselect';
3341 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
3342 $mapping[$key] = 'registered-checkmatrix';
3343 } elseif ( isset( $specialOptions[$key] ) ) {
3344 $mapping[$key] = 'special';
3345 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
3346 $mapping[$key] = 'userjs';
3348 $mapping[$key] = 'unused';
3356 * Reset certain (or all) options to the site defaults
3358 * The optional parameter determines which kinds of preferences will be reset.
3359 * Supported values are everything that can be reported by getOptionKinds()
3360 * and 'all', which forces a reset of *all* preferences and overrides everything else.
3362 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
3363 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
3364 * for backwards-compatibility.
3365 * @param IContextSource|null $context Context source used when $resetKinds
3366 * does not contain 'all', passed to getOptionKinds().
3367 * Defaults to RequestContext::getMain() when null.
3369 public function resetOptions(
3370 $resetKinds = [ 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ],
3371 IContextSource
$context = null
3374 $defaultOptions = self
::getDefaultOptions();
3376 if ( !is_array( $resetKinds ) ) {
3377 $resetKinds = [ $resetKinds ];
3380 if ( in_array( 'all', $resetKinds ) ) {
3381 $newOptions = $defaultOptions;
3383 if ( $context === null ) {
3384 $context = RequestContext
::getMain();
3387 $optionKinds = $this->getOptionKinds( $context );
3388 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
3391 // Use default values for the options that should be deleted, and
3392 // copy old values for the ones that shouldn't.
3393 foreach ( $this->mOptions
as $key => $value ) {
3394 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
3395 if ( array_key_exists( $key, $defaultOptions ) ) {
3396 $newOptions[$key] = $defaultOptions[$key];
3399 $newOptions[$key] = $value;
3404 Hooks
::run( 'UserResetAllOptions', [ $this, &$newOptions, $this->mOptions
, $resetKinds ] );
3406 $this->mOptions
= $newOptions;
3407 $this->mOptionsLoaded
= true;
3411 * Get the user's preferred date format.
3412 * @return string User's preferred date format
3414 public function getDatePreference() {
3415 // Important migration for old data rows
3416 if ( is_null( $this->mDatePreference
) ) {
3418 $value = $this->getOption( 'date' );
3419 $map = $wgLang->getDatePreferenceMigrationMap();
3420 if ( isset( $map[$value] ) ) {
3421 $value = $map[$value];
3423 $this->mDatePreference
= $value;
3425 return $this->mDatePreference
;
3429 * Determine based on the wiki configuration and the user's options,
3430 * whether this user must be over HTTPS no matter what.
3434 public function requiresHTTPS() {
3435 global $wgSecureLogin;
3436 if ( !$wgSecureLogin ) {
3439 $https = $this->getBoolOption( 'prefershttps' );
3440 Hooks
::run( 'UserRequiresHTTPS', [ $this, &$https ] );
3442 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
3449 * Get the user preferred stub threshold
3453 public function getStubThreshold() {
3454 global $wgMaxArticleSize; # Maximum article size, in Kb
3455 $threshold = $this->getIntOption( 'stubthreshold' );
3456 if ( $threshold > $wgMaxArticleSize * 1024 ) {
3457 // If they have set an impossible value, disable the preference
3458 // so we can use the parser cache again.
3465 * Get the permissions this user has.
3466 * @return string[] permission names
3468 public function getRights() {
3469 if ( is_null( $this->mRights
) ) {
3470 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
3471 Hooks
::run( 'UserGetRights', [ $this, &$this->mRights
] );
3473 // Deny any rights denied by the user's session, unless this
3474 // endpoint has no sessions.
3475 if ( !defined( 'MW_NO_SESSION' ) ) {
3476 $allowedRights = $this->getRequest()->getSession()->getAllowedUserRights();
3477 if ( $allowedRights !== null ) {
3478 $this->mRights
= array_intersect( $this->mRights
, $allowedRights );
3482 // Force reindexation of rights when a hook has unset one of them
3483 $this->mRights
= array_values( array_unique( $this->mRights
) );
3485 // If block disables login, we should also remove any
3486 // extra rights blocked users might have, in case the
3487 // blocked user has a pre-existing session (T129738).
3488 // This is checked here for cases where people only call
3489 // $user->isAllowed(). It is also checked in Title::checkUserBlock()
3490 // to give a better error message in the common case.
3491 $config = RequestContext
::getMain()->getConfig();
3493 $this->isLoggedIn() &&
3494 $config->get( 'BlockDisablesLogin' ) &&
3498 $this->mRights
= array_intersect( $this->mRights
, $anon->getRights() );
3501 return $this->mRights
;
3505 * Get the list of explicit group memberships this user has.
3506 * The implicit * and user groups are not included.
3507 * @return array Array of String internal group names
3509 public function getGroups() {
3511 $this->loadGroups();
3512 return array_keys( $this->mGroupMemberships
);
3516 * Get the list of explicit group memberships this user has, stored as
3517 * UserGroupMembership objects. Implicit groups are not included.
3519 * @return UserGroupMembership[] Associative array of (group name => UserGroupMembership object)
3522 public function getGroupMemberships() {
3524 $this->loadGroups();
3525 return $this->mGroupMemberships
;
3529 * Get the list of implicit group memberships this user has.
3530 * This includes all explicit groups, plus 'user' if logged in,
3531 * '*' for all accounts, and autopromoted groups
3532 * @param bool $recache Whether to avoid the cache
3533 * @return array Array of String internal group names
3535 public function getEffectiveGroups( $recache = false ) {
3536 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
3537 $this->mEffectiveGroups
= array_unique( array_merge(
3538 $this->getGroups(), // explicit groups
3539 $this->getAutomaticGroups( $recache ) // implicit groups
3541 // Avoid PHP 7.1 warning of passing $this by reference
3543 // Hook for additional groups
3544 Hooks
::run( 'UserEffectiveGroups', [ &$user, &$this->mEffectiveGroups
] );
3545 // Force reindexation of groups when a hook has unset one of them
3546 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
3548 return $this->mEffectiveGroups
;
3552 * Get the list of implicit group memberships this user has.
3553 * This includes 'user' if logged in, '*' for all accounts,
3554 * and autopromoted groups
3555 * @param bool $recache Whether to avoid the cache
3556 * @return array Array of String internal group names
3558 public function getAutomaticGroups( $recache = false ) {
3559 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
3560 $this->mImplicitGroups
= [ '*' ];
3561 if ( $this->getId() ) {
3562 $this->mImplicitGroups
[] = 'user';
3564 $this->mImplicitGroups
= array_unique( array_merge(
3565 $this->mImplicitGroups
,
3566 Autopromote
::getAutopromoteGroups( $this )
3570 // Assure data consistency with rights/groups,
3571 // as getEffectiveGroups() depends on this function
3572 $this->mEffectiveGroups
= null;
3575 return $this->mImplicitGroups
;
3579 * Returns the groups the user has belonged to.
3581 * The user may still belong to the returned groups. Compare with getGroups().
3583 * The function will not return groups the user had belonged to before MW 1.17
3585 * @return array Names of the groups the user has belonged to.
3587 public function getFormerGroups() {
3590 if ( is_null( $this->mFormerGroups
) ) {
3591 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3592 ?
wfGetDB( DB_MASTER
)
3593 : wfGetDB( DB_REPLICA
);
3594 $res = $db->select( 'user_former_groups',
3596 [ 'ufg_user' => $this->mId
],
3598 $this->mFormerGroups
= [];
3599 foreach ( $res as $row ) {
3600 $this->mFormerGroups
[] = $row->ufg_group
;
3604 return $this->mFormerGroups
;
3608 * Get the user's edit count.
3609 * @return int|null Null for anonymous users
3611 public function getEditCount() {
3612 if ( !$this->getId() ) {
3616 if ( $this->mEditCount
=== null ) {
3617 /* Populate the count, if it has not been populated yet */
3618 $dbr = wfGetDB( DB_REPLICA
);
3619 // check if the user_editcount field has been initialized
3620 $count = $dbr->selectField(
3621 'user', 'user_editcount',
3622 [ 'user_id' => $this->mId
],
3626 if ( $count === null ) {
3627 // it has not been initialized. do so.
3628 $count = $this->initEditCount();
3630 $this->mEditCount
= $count;
3632 return (int)$this->mEditCount
;
3636 * Add the user to the given group. This takes immediate effect.
3637 * If the user is already in the group, the expiry time will be updated to the new
3638 * expiry time. (If $expiry is omitted or null, the membership will be altered to
3641 * @param string $group Name of the group to add
3642 * @param string $expiry Optional expiry timestamp in any format acceptable to
3643 * wfTimestamp(), or null if the group assignment should not expire
3646 public function addGroup( $group, $expiry = null ) {
3648 $this->loadGroups();
3651 $expiry = wfTimestamp( TS_MW
, $expiry );
3654 if ( !Hooks
::run( 'UserAddGroup', [ $this, &$group, &$expiry ] ) ) {
3658 // create the new UserGroupMembership and put it in the DB
3659 $ugm = new UserGroupMembership( $this->mId
, $group, $expiry );
3660 if ( !$ugm->insert( true ) ) {
3664 $this->mGroupMemberships
[$group] = $ugm;
3666 // Refresh the groups caches, and clear the rights cache so it will be
3667 // refreshed on the next call to $this->getRights().
3668 $this->getEffectiveGroups( true );
3669 $this->mRights
= null;
3671 $this->invalidateCache();
3677 * Remove the user from the given group.
3678 * This takes immediate effect.
3679 * @param string $group Name of the group to remove
3682 public function removeGroup( $group ) {
3685 if ( !Hooks
::run( 'UserRemoveGroup', [ $this, &$group ] ) ) {
3689 $ugm = UserGroupMembership
::getMembership( $this->mId
, $group );
3690 // delete the membership entry
3691 if ( !$ugm ||
!$ugm->delete() ) {
3695 $this->loadGroups();
3696 unset( $this->mGroupMemberships
[$group] );
3698 // Refresh the groups caches, and clear the rights cache so it will be
3699 // refreshed on the next call to $this->getRights().
3700 $this->getEffectiveGroups( true );
3701 $this->mRights
= null;
3703 $this->invalidateCache();
3709 * Get whether the user is logged in
3712 public function isLoggedIn() {
3713 return $this->getId() != 0;
3717 * Get whether the user is anonymous
3720 public function isAnon() {
3721 return !$this->isLoggedIn();
3725 * @return bool Whether this user is flagged as being a bot role account
3728 public function isBot() {
3729 if ( in_array( 'bot', $this->getGroups() ) && $this->isAllowed( 'bot' ) ) {
3734 Hooks
::run( "UserIsBot", [ $this, &$isBot ] );
3740 * Check if user is allowed to access a feature / make an action
3742 * @param string $permissions,... Permissions to test
3743 * @return bool True if user is allowed to perform *any* of the given actions
3745 public function isAllowedAny() {
3746 $permissions = func_get_args();
3747 foreach ( $permissions as $permission ) {
3748 if ( $this->isAllowed( $permission ) ) {
3757 * @param string $permissions,... Permissions to test
3758 * @return bool True if the user is allowed to perform *all* of the given actions
3760 public function isAllowedAll() {
3761 $permissions = func_get_args();
3762 foreach ( $permissions as $permission ) {
3763 if ( !$this->isAllowed( $permission ) ) {
3771 * Internal mechanics of testing a permission
3772 * @param string $action
3775 public function isAllowed( $action = '' ) {
3776 if ( $action === '' ) {
3777 return true; // In the spirit of DWIM
3779 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3780 // by misconfiguration: 0 == 'foo'
3781 return in_array( $action, $this->getRights(), true );
3785 * Check whether to enable recent changes patrol features for this user
3786 * @return bool True or false
3788 public function useRCPatrol() {
3789 global $wgUseRCPatrol;
3790 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3794 * Check whether to enable new pages patrol features for this user
3795 * @return bool True or false
3797 public function useNPPatrol() {
3798 global $wgUseRCPatrol, $wgUseNPPatrol;
3800 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3801 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3806 * Check whether to enable new files patrol features for this user
3807 * @return bool True or false
3809 public function useFilePatrol() {
3810 global $wgUseRCPatrol, $wgUseFilePatrol;
3812 ( $wgUseRCPatrol ||
$wgUseFilePatrol )
3813 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3818 * Get the WebRequest object to use with this object
3820 * @return WebRequest
3822 public function getRequest() {
3823 if ( $this->mRequest
) {
3824 return $this->mRequest
;
3832 * Check the watched status of an article.
3833 * @since 1.22 $checkRights parameter added
3834 * @param Title $title Title of the article to look at
3835 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3836 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3839 public function isWatched( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3840 if ( $title->isWatchable() && ( !$checkRights ||
$this->isAllowed( 'viewmywatchlist' ) ) ) {
3841 return MediaWikiServices
::getInstance()->getWatchedItemStore()->isWatched( $this, $title );
3848 * @since 1.22 $checkRights parameter added
3849 * @param Title $title Title of the article to look at
3850 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3851 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3853 public function addWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3854 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3855 MediaWikiServices
::getInstance()->getWatchedItemStore()->addWatchBatchForUser(
3857 [ $title->getSubjectPage(), $title->getTalkPage() ]
3860 $this->invalidateCache();
3864 * Stop watching an article.
3865 * @since 1.22 $checkRights parameter added
3866 * @param Title $title Title of the article to look at
3867 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3868 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3870 public function removeWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3871 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3872 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
3873 $store->removeWatch( $this, $title->getSubjectPage() );
3874 $store->removeWatch( $this, $title->getTalkPage() );
3876 $this->invalidateCache();
3880 * Clear the user's notification timestamp for the given title.
3881 * If e-notif e-mails are on, they will receive notification mails on
3882 * the next change of the page if it's watched etc.
3883 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3884 * @param Title &$title Title of the article to look at
3885 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3887 public function clearNotification( &$title, $oldid = 0 ) {
3888 global $wgUseEnotif, $wgShowUpdatedMarker;
3890 // Do nothing if the database is locked to writes
3891 if ( wfReadOnly() ) {
3895 // Do nothing if not allowed to edit the watchlist
3896 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3900 // If we're working on user's talk page, we should update the talk page message indicator
3901 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3902 // Avoid PHP 7.1 warning of passing $this by reference
3904 if ( !Hooks
::run( 'UserClearNewTalkNotification', [ &$user, $oldid ] ) ) {
3908 // Try to update the DB post-send and only if needed...
3909 DeferredUpdates
::addCallableUpdate( function () use ( $title, $oldid ) {
3910 if ( !$this->getNewtalk() ) {
3911 return; // no notifications to clear
3914 // Delete the last notifications (they stack up)
3915 $this->setNewtalk( false );
3917 // If there is a new, unseen, revision, use its timestamp
3919 ?
$title->getNextRevisionID( $oldid, Title
::GAID_FOR_UPDATE
)
3922 $this->setNewtalk( true, Revision
::newFromId( $nextid ) );
3927 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3931 if ( $this->isAnon() ) {
3932 // Nothing else to do...
3936 // Only update the timestamp if the page is being watched.
3937 // The query to find out if it is watched is cached both in memcached and per-invocation,
3938 // and when it does have to be executed, it can be on a replica DB
3939 // If this is the user's newtalk page, we always update the timestamp
3941 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3945 MediaWikiServices
::getInstance()->getWatchedItemStore()
3946 ->resetNotificationTimestamp( $this, $title, $force, $oldid );
3950 * Resets all of the given user's page-change notification timestamps.
3951 * If e-notif e-mails are on, they will receive notification mails on
3952 * the next change of any watched page.
3953 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3955 public function clearAllNotifications() {
3956 global $wgUseEnotif, $wgShowUpdatedMarker;
3957 // Do nothing if not allowed to edit the watchlist
3958 if ( wfReadOnly() ||
!$this->isAllowed( 'editmywatchlist' ) ) {
3962 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3963 $this->setNewtalk( false );
3967 $id = $this->getId();
3972 $watchedItemStore = MediaWikiServices
::getInstance()->getWatchedItemStore();
3973 $watchedItemStore->resetAllNotificationTimestampsForUser( $this );
3975 // We also need to clear here the "you have new message" notification for the own
3976 // user_talk page; it's cleared one page view later in WikiPage::doViewUpdates().
3980 * Compute experienced level based on edit count and registration date.
3982 * @return string 'newcomer', 'learner', or 'experienced'
3984 public function getExperienceLevel() {
3985 global $wgLearnerEdits,
3986 $wgExperiencedUserEdits,
3987 $wgLearnerMemberSince,
3988 $wgExperiencedUserMemberSince;
3990 if ( $this->isAnon() ) {
3994 $editCount = $this->getEditCount();
3995 $registration = $this->getRegistration();
3997 $learnerRegistration = wfTimestamp( TS_MW
, $now - $wgLearnerMemberSince * 86400 );
3998 $experiencedRegistration = wfTimestamp( TS_MW
, $now - $wgExperiencedUserMemberSince * 86400 );
4001 $editCount < $wgLearnerEdits ||
4002 $registration > $learnerRegistration
4006 $editCount > $wgExperiencedUserEdits &&
4007 $registration <= $experiencedRegistration
4009 return 'experienced';
4016 * Persist this user's session (e.g. set cookies)
4018 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
4020 * @param bool $secure Whether to force secure/insecure cookies or use default
4021 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
4023 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
4025 if ( 0 == $this->mId
) {
4029 $session = $this->getRequest()->getSession();
4030 if ( $request && $session->getRequest() !== $request ) {
4031 $session = $session->sessionWithRequest( $request );
4033 $delay = $session->delaySave();
4035 if ( !$session->getUser()->equals( $this ) ) {
4036 if ( !$session->canSetUser() ) {
4037 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
4038 ->warning( __METHOD__
.
4039 ": Cannot save user \"$this\" to a user \"{$session->getUser()}\"'s immutable session"
4043 $session->setUser( $this );
4046 $session->setRememberUser( $rememberMe );
4047 if ( $secure !== null ) {
4048 $session->setForceHTTPS( $secure );
4051 $session->persist();
4053 ScopedCallback
::consume( $delay );
4057 * Log this user out.
4059 public function logout() {
4060 // Avoid PHP 7.1 warning of passing $this by reference
4062 if ( Hooks
::run( 'UserLogout', [ &$user ] ) ) {
4068 * Clear the user's session, and reset the instance cache.
4071 public function doLogout() {
4072 $session = $this->getRequest()->getSession();
4073 if ( !$session->canSetUser() ) {
4074 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
4075 ->warning( __METHOD__
. ": Cannot log out of an immutable session" );
4076 $error = 'immutable';
4077 } elseif ( !$session->getUser()->equals( $this ) ) {
4078 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
4079 ->warning( __METHOD__
.
4080 ": Cannot log user \"$this\" out of a user \"{$session->getUser()}\"'s session"
4082 // But we still may as well make this user object anon
4083 $this->clearInstanceCache( 'defaults' );
4084 $error = 'wronguser';
4086 $this->clearInstanceCache( 'defaults' );
4087 $delay = $session->delaySave();
4088 $session->unpersist(); // Clear cookies (T127436)
4089 $session->setLoggedOutTimestamp( time() );
4090 $session->setUser( new User
);
4091 $session->set( 'wsUserID', 0 ); // Other code expects this
4092 $session->resetAllTokens();
4093 ScopedCallback
::consume( $delay );
4096 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authevents' )->info( 'Logout', [
4097 'event' => 'logout',
4098 'successful' => $error === false,
4099 'status' => $error ?
: 'success',
4104 * Save this user's settings into the database.
4105 * @todo Only rarely do all these fields need to be set!
4107 public function saveSettings() {
4108 if ( wfReadOnly() ) {
4109 // @TODO: caller should deal with this instead!
4110 // This should really just be an exception.
4111 MWExceptionHandler
::logException( new DBExpectedError(
4113 "Could not update user with ID '{$this->mId}'; DB is read-only."
4119 if ( 0 == $this->mId
) {
4123 // Get a new user_touched that is higher than the old one.
4124 // This will be used for a CAS check as a last-resort safety
4125 // check against race conditions and replica DB lag.
4126 $newTouched = $this->newTouchedTimestamp();
4128 $dbw = wfGetDB( DB_MASTER
);
4129 $dbw->doAtomicSection( __METHOD__
, function ( $dbw, $fname ) use ( $newTouched ) {
4130 global $wgActorTableSchemaMigrationStage;
4132 $dbw->update( 'user',
4134 'user_name' => $this->mName
,
4135 'user_real_name' => $this->mRealName
,
4136 'user_email' => $this->mEmail
,
4137 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
4138 'user_touched' => $dbw->timestamp( $newTouched ),
4139 'user_token' => strval( $this->mToken
),
4140 'user_email_token' => $this->mEmailToken
,
4141 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
4142 ], $this->makeUpdateConditions( $dbw, [ /* WHERE */
4143 'user_id' => $this->mId
,
4147 if ( !$dbw->affectedRows() ) {
4148 // Maybe the problem was a missed cache update; clear it to be safe
4149 $this->clearSharedCache( 'refresh' );
4150 // User was changed in the meantime or loaded with stale data
4151 $from = ( $this->queryFlagsUsed
& self
::READ_LATEST
) ?
'master' : 'replica';
4152 throw new MWException(
4153 "CAS update failed on user_touched for user ID '{$this->mId}' (read from $from);" .
4154 " the version of the user to be saved is older than the current version."
4158 if ( $wgActorTableSchemaMigrationStage > MIGRATION_OLD
) {
4161 [ 'actor_name' => $this->mName
],
4162 [ 'actor_user' => $this->mId
],
4168 $this->mTouched
= $newTouched;
4169 $this->saveOptions();
4171 Hooks
::run( 'UserSaveSettings', [ $this ] );
4172 $this->clearSharedCache();
4173 $this->getUserPage()->invalidateCache();
4177 * If only this user's username is known, and it exists, return the user ID.
4179 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
4182 public function idForName( $flags = 0 ) {
4183 $s = trim( $this->getName() );
4188 $db = ( ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
)
4189 ?
wfGetDB( DB_MASTER
)
4190 : wfGetDB( DB_REPLICA
);
4192 $options = ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
)
4193 ?
[ 'LOCK IN SHARE MODE' ]
4196 $id = $db->selectField( 'user',
4197 'user_id', [ 'user_name' => $s ], __METHOD__
, $options );
4203 * Add a user to the database, return the user object
4205 * @param string $name Username to add
4206 * @param array $params Array of Strings Non-default parameters to save to
4207 * the database as user_* fields:
4208 * - email: The user's email address.
4209 * - email_authenticated: The email authentication timestamp.
4210 * - real_name: The user's real name.
4211 * - options: An associative array of non-default options.
4212 * - token: Random authentication token. Do not set.
4213 * - registration: Registration timestamp. Do not set.
4215 * @return User|null User object, or null if the username already exists.
4217 public static function createNew( $name, $params = [] ) {
4218 foreach ( [ 'password', 'newpassword', 'newpass_time', 'password_expires' ] as $field ) {
4219 if ( isset( $params[$field] ) ) {
4220 wfDeprecated( __METHOD__
. " with param '$field'", '1.27' );
4221 unset( $params[$field] );
4227 $user->setToken(); // init token
4228 if ( isset( $params['options'] ) ) {
4229 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
4230 unset( $params['options'] );
4232 $dbw = wfGetDB( DB_MASTER
);
4234 $noPass = PasswordFactory
::newInvalidPassword()->toString();
4237 'user_name' => $name,
4238 'user_password' => $noPass,
4239 'user_newpassword' => $noPass,
4240 'user_email' => $user->mEmail
,
4241 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
4242 'user_real_name' => $user->mRealName
,
4243 'user_token' => strval( $user->mToken
),
4244 'user_registration' => $dbw->timestamp( $user->mRegistration
),
4245 'user_editcount' => 0,
4246 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
4248 foreach ( $params as $name => $value ) {
4249 $fields["user_$name"] = $value;
4252 return $dbw->doAtomicSection( __METHOD__
, function ( $dbw, $fname ) use ( $fields ) {
4253 $dbw->insert( 'user', $fields, $fname, [ 'IGNORE' ] );
4254 if ( $dbw->affectedRows() ) {
4255 $newUser = self
::newFromId( $dbw->insertId() );
4256 // Load the user from master to avoid replica lag
4257 $newUser->load( self
::READ_LATEST
);
4258 $newUser->updateActorId( $dbw );
4267 * Add this existing user object to the database. If the user already
4268 * exists, a fatal status object is returned, and the user object is
4269 * initialised with the data from the database.
4271 * Previously, this function generated a DB error due to a key conflict
4272 * if the user already existed. Many extension callers use this function
4273 * in code along the lines of:
4275 * $user = User::newFromName( $name );
4276 * if ( !$user->isLoggedIn() ) {
4277 * $user->addToDatabase();
4279 * // do something with $user...
4281 * However, this was vulnerable to a race condition (T18020). By
4282 * initialising the user object if the user exists, we aim to support this
4283 * calling sequence as far as possible.
4285 * Note that if the user exists, this function will acquire a write lock,
4286 * so it is still advisable to make the call conditional on isLoggedIn(),
4287 * and to commit the transaction after calling.
4289 * @throws MWException
4292 public function addToDatabase() {
4294 if ( !$this->mToken
) {
4295 $this->setToken(); // init token
4298 if ( !is_string( $this->mName
) ) {
4299 throw new RuntimeException( "User name field is not set." );
4302 $this->mTouched
= $this->newTouchedTimestamp();
4304 $dbw = wfGetDB( DB_MASTER
);
4305 $status = $dbw->doAtomicSection( __METHOD__
, function ( $dbw, $fname ) {
4306 $noPass = PasswordFactory
::newInvalidPassword()->toString();
4307 $dbw->insert( 'user',
4309 'user_name' => $this->mName
,
4310 'user_password' => $noPass,
4311 'user_newpassword' => $noPass,
4312 'user_email' => $this->mEmail
,
4313 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
4314 'user_real_name' => $this->mRealName
,
4315 'user_token' => strval( $this->mToken
),
4316 'user_registration' => $dbw->timestamp( $this->mRegistration
),
4317 'user_editcount' => 0,
4318 'user_touched' => $dbw->timestamp( $this->mTouched
),
4322 if ( !$dbw->affectedRows() ) {
4323 // Use locking reads to bypass any REPEATABLE-READ snapshot.
4324 $this->mId
= $dbw->selectField(
4327 [ 'user_name' => $this->mName
],
4329 [ 'LOCK IN SHARE MODE' ]
4333 if ( $this->loadFromDatabase( self
::READ_LOCKING
) ) {
4338 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
4339 "to insert user '{$this->mName}' row, but it was not present in select!" );
4341 return Status
::newFatal( 'userexists' );
4343 $this->mId
= $dbw->insertId();
4344 self
::$idCacheByName[$this->mName
] = $this->mId
;
4345 $this->updateActorId( $dbw );
4347 return Status
::newGood();
4349 if ( !$status->isGood() ) {
4353 // Clear instance cache other than user table data and actor, which is already accurate
4354 $this->clearInstanceCache();
4356 $this->saveOptions();
4357 return Status
::newGood();
4361 * Update the actor ID after an insert
4362 * @param IDatabase $dbw Writable database handle
4364 private function updateActorId( IDatabase
$dbw ) {
4365 global $wgActorTableSchemaMigrationStage;
4367 if ( $wgActorTableSchemaMigrationStage > MIGRATION_OLD
) {
4370 [ 'actor_user' => $this->mId
, 'actor_name' => $this->mName
],
4373 $this->mActorId
= (int)$dbw->insertId();
4378 * If this user is logged-in and blocked,
4379 * block any IP address they've successfully logged in from.
4380 * @return bool A block was spread
4382 public function spreadAnyEditBlock() {
4383 if ( $this->isLoggedIn() && $this->isBlocked() ) {
4384 return $this->spreadBlock();
4391 * If this (non-anonymous) user is blocked,
4392 * block the IP address they've successfully logged in from.
4393 * @return bool A block was spread
4395 protected function spreadBlock() {
4396 wfDebug( __METHOD__
. "()\n" );
4398 if ( $this->mId
== 0 ) {
4402 $userblock = Block
::newFromTarget( $this->getName() );
4403 if ( !$userblock ) {
4407 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
4411 * Get whether the user is explicitly blocked from account creation.
4412 * @return bool|Block
4414 public function isBlockedFromCreateAccount() {
4415 $this->getBlockedStatus();
4416 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
4417 return $this->mBlock
;
4420 # T15611: if the IP address the user is trying to create an account from is
4421 # blocked with createaccount disabled, prevent new account creation there even
4422 # when the user is logged in
4423 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
4424 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
4426 return $this->mBlockedFromCreateAccount
instanceof Block
4427 && $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
4428 ?
$this->mBlockedFromCreateAccount
4433 * Get whether the user is blocked from using Special:Emailuser.
4436 public function isBlockedFromEmailuser() {
4437 $this->getBlockedStatus();
4438 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
4442 * Get whether the user is allowed to create an account.
4445 public function isAllowedToCreateAccount() {
4446 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
4450 * Get this user's personal page title.
4452 * @return Title User's personal page title
4454 public function getUserPage() {
4455 return Title
::makeTitle( NS_USER
, $this->getName() );
4459 * Get this user's talk page title.
4461 * @return Title User's talk page title
4463 public function getTalkPage() {
4464 $title = $this->getUserPage();
4465 return $title->getTalkPage();
4469 * Determine whether the user is a newbie. Newbies are either
4470 * anonymous IPs, or the most recently created accounts.
4473 public function isNewbie() {
4474 return !$this->isAllowed( 'autoconfirmed' );
4478 * Check to see if the given clear-text password is one of the accepted passwords
4479 * @deprecated since 1.27, use AuthManager instead
4480 * @param string $password User password
4481 * @return bool True if the given password is correct, otherwise False
4483 public function checkPassword( $password ) {
4484 $manager = AuthManager
::singleton();
4485 $reqs = AuthenticationRequest
::loadRequestsFromSubmission(
4486 $manager->getAuthenticationRequests( AuthManager
::ACTION_LOGIN
),
4488 'username' => $this->getName(),
4489 'password' => $password,
4492 $res = AuthManager
::singleton()->beginAuthentication( $reqs, 'null:' );
4493 switch ( $res->status
) {
4494 case AuthenticationResponse
::PASS
:
4496 case AuthenticationResponse
::FAIL
:
4497 // Hope it's not a PreAuthenticationProvider that failed...
4498 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
4499 ->info( __METHOD__
. ': Authentication failed: ' . $res->message
->plain() );
4502 throw new BadMethodCallException(
4503 'AuthManager returned a response unsupported by ' . __METHOD__
4509 * Check if the given clear-text password matches the temporary password
4510 * sent by e-mail for password reset operations.
4512 * @deprecated since 1.27, use AuthManager instead
4513 * @param string $plaintext
4514 * @return bool True if matches, false otherwise
4516 public function checkTemporaryPassword( $plaintext ) {
4517 // Can't check the temporary password individually.
4518 return $this->checkPassword( $plaintext );
4522 * Initialize (if necessary) and return a session token value
4523 * which can be used in edit forms to show that the user's
4524 * login credentials aren't being hijacked with a foreign form
4528 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4529 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4530 * @return MediaWiki\Session\Token The new edit token
4532 public function getEditTokenObject( $salt = '', $request = null ) {
4533 if ( $this->isAnon() ) {
4534 return new LoggedOutEditToken();
4538 $request = $this->getRequest();
4540 return $request->getSession()->getToken( $salt );
4544 * Initialize (if necessary) and return a session token value
4545 * which can be used in edit forms to show that the user's
4546 * login credentials aren't being hijacked with a foreign form
4549 * The $salt for 'edit' and 'csrf' tokens is the default (empty string).
4552 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4553 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4554 * @return string The new edit token
4556 public function getEditToken( $salt = '', $request = null ) {
4557 return $this->getEditTokenObject( $salt, $request )->toString();
4561 * Get the embedded timestamp from a token.
4562 * @deprecated since 1.27, use \MediaWiki\Session\Token::getTimestamp instead.
4563 * @param string $val Input token
4566 public static function getEditTokenTimestamp( $val ) {
4567 wfDeprecated( __METHOD__
, '1.27' );
4568 return MediaWiki\Session\Token
::getTimestamp( $val );
4572 * Check given value against the token value stored in the session.
4573 * A match should confirm that the form was submitted from the
4574 * user's own login session, not a form submission from a third-party
4577 * @param string $val Input value to compare
4578 * @param string $salt Optional function-specific data for hashing
4579 * @param WebRequest|null $request Object to use or null to use $wgRequest
4580 * @param int $maxage Fail tokens older than this, in seconds
4581 * @return bool Whether the token matches
4583 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4584 return $this->getEditTokenObject( $salt, $request )->match( $val, $maxage );
4588 * Check given value against the token value stored in the session,
4589 * ignoring the suffix.
4591 * @param string $val Input value to compare
4592 * @param string $salt Optional function-specific data for hashing
4593 * @param WebRequest|null $request Object to use or null to use $wgRequest
4594 * @param int $maxage Fail tokens older than this, in seconds
4595 * @return bool Whether the token matches
4597 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4598 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . Token
::SUFFIX
;
4599 return $this->matchEditToken( $val, $salt, $request, $maxage );
4603 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4604 * mail to the user's given address.
4606 * @param string $type Message to send, either "created", "changed" or "set"
4609 public function sendConfirmationMail( $type = 'created' ) {
4611 $expiration = null; // gets passed-by-ref and defined in next line.
4612 $token = $this->confirmationToken( $expiration );
4613 $url = $this->confirmationTokenUrl( $token );
4614 $invalidateURL = $this->invalidationTokenUrl( $token );
4615 $this->saveSettings();
4617 if ( $type == 'created' ||
$type === false ) {
4618 $message = 'confirmemail_body';
4619 } elseif ( $type === true ) {
4620 $message = 'confirmemail_body_changed';
4622 // Messages: confirmemail_body_changed, confirmemail_body_set
4623 $message = 'confirmemail_body_' . $type;
4626 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4627 wfMessage( $message,
4628 $this->getRequest()->getIP(),
4631 $wgLang->userTimeAndDate( $expiration, $this ),
4633 $wgLang->userDate( $expiration, $this ),
4634 $wgLang->userTime( $expiration, $this ) )->text() );
4638 * Send an e-mail to this user's account. Does not check for
4639 * confirmed status or validity.
4641 * @param string $subject Message subject
4642 * @param string $body Message body
4643 * @param User|null $from Optional sending user; if unspecified, default
4644 * $wgPasswordSender will be used.
4645 * @param string $replyto Reply-To address
4648 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4649 global $wgPasswordSender;
4651 if ( $from instanceof User
) {
4652 $sender = MailAddress
::newFromUser( $from );
4654 $sender = new MailAddress( $wgPasswordSender,
4655 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4657 $to = MailAddress
::newFromUser( $this );
4659 return UserMailer
::send( $to, $sender, $subject, $body, [
4660 'replyTo' => $replyto,
4665 * Generate, store, and return a new e-mail confirmation code.
4666 * A hash (unsalted, since it's used as a key) is stored.
4668 * @note Call saveSettings() after calling this function to commit
4669 * this change to the database.
4671 * @param string &$expiration Accepts the expiration time
4672 * @return string New token
4674 protected function confirmationToken( &$expiration ) {
4675 global $wgUserEmailConfirmationTokenExpiry;
4677 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4678 $expiration = wfTimestamp( TS_MW
, $expires );
4680 $token = MWCryptRand
::generateHex( 32 );
4681 $hash = md5( $token );
4682 $this->mEmailToken
= $hash;
4683 $this->mEmailTokenExpires
= $expiration;
4688 * Return a URL the user can use to confirm their email address.
4689 * @param string $token Accepts the email confirmation token
4690 * @return string New token URL
4692 protected function confirmationTokenUrl( $token ) {
4693 return $this->getTokenUrl( 'ConfirmEmail', $token );
4697 * Return a URL the user can use to invalidate their email address.
4698 * @param string $token Accepts the email confirmation token
4699 * @return string New token URL
4701 protected function invalidationTokenUrl( $token ) {
4702 return $this->getTokenUrl( 'InvalidateEmail', $token );
4706 * Internal function to format the e-mail validation/invalidation URLs.
4707 * This uses a quickie hack to use the
4708 * hardcoded English names of the Special: pages, for ASCII safety.
4710 * @note Since these URLs get dropped directly into emails, using the
4711 * short English names avoids insanely long URL-encoded links, which
4712 * also sometimes can get corrupted in some browsers/mailers
4713 * (T8957 with Gmail and Internet Explorer).
4715 * @param string $page Special page
4716 * @param string $token
4717 * @return string Formatted URL
4719 protected function getTokenUrl( $page, $token ) {
4720 // Hack to bypass localization of 'Special:'
4721 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4722 return $title->getCanonicalURL();
4726 * Mark the e-mail address confirmed.
4728 * @note Call saveSettings() after calling this function to commit the change.
4732 public function confirmEmail() {
4733 // Check if it's already confirmed, so we don't touch the database
4734 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4735 if ( !$this->isEmailConfirmed() ) {
4736 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4737 Hooks
::run( 'ConfirmEmailComplete', [ $this ] );
4743 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4744 * address if it was already confirmed.
4746 * @note Call saveSettings() after calling this function to commit the change.
4747 * @return bool Returns true
4749 public function invalidateEmail() {
4751 $this->mEmailToken
= null;
4752 $this->mEmailTokenExpires
= null;
4753 $this->setEmailAuthenticationTimestamp( null );
4755 Hooks
::run( 'InvalidateEmailComplete', [ $this ] );
4760 * Set the e-mail authentication timestamp.
4761 * @param string $timestamp TS_MW timestamp
4763 public function setEmailAuthenticationTimestamp( $timestamp ) {
4765 $this->mEmailAuthenticated
= $timestamp;
4766 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
4770 * Is this user allowed to send e-mails within limits of current
4771 * site configuration?
4774 public function canSendEmail() {
4775 global $wgEnableEmail, $wgEnableUserEmail;
4776 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4779 $canSend = $this->isEmailConfirmed();
4780 // Avoid PHP 7.1 warning of passing $this by reference
4782 Hooks
::run( 'UserCanSendEmail', [ &$user, &$canSend ] );
4787 * Is this user allowed to receive e-mails within limits of current
4788 * site configuration?
4791 public function canReceiveEmail() {
4792 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4796 * Is this user's e-mail address valid-looking and confirmed within
4797 * limits of the current site configuration?
4799 * @note If $wgEmailAuthentication is on, this may require the user to have
4800 * confirmed their address by returning a code or using a password
4801 * sent to the address from the wiki.
4805 public function isEmailConfirmed() {
4806 global $wgEmailAuthentication;
4808 // Avoid PHP 7.1 warning of passing $this by reference
4811 if ( Hooks
::run( 'EmailConfirmed', [ &$user, &$confirmed ] ) ) {
4812 if ( $this->isAnon() ) {
4815 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4818 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4828 * Check whether there is an outstanding request for e-mail confirmation.
4831 public function isEmailConfirmationPending() {
4832 global $wgEmailAuthentication;
4833 return $wgEmailAuthentication &&
4834 !$this->isEmailConfirmed() &&
4835 $this->mEmailToken
&&
4836 $this->mEmailTokenExpires
> wfTimestamp();
4840 * Get the timestamp of account creation.
4842 * @return string|bool|null Timestamp of account creation, false for
4843 * non-existent/anonymous user accounts, or null if existing account
4844 * but information is not in database.
4846 public function getRegistration() {
4847 if ( $this->isAnon() ) {
4851 return $this->mRegistration
;
4855 * Get the timestamp of the first edit
4857 * @return string|bool Timestamp of first edit, or false for
4858 * non-existent/anonymous user accounts.
4860 public function getFirstEditTimestamp() {
4861 if ( $this->getId() == 0 ) {
4862 return false; // anons
4864 $dbr = wfGetDB( DB_REPLICA
);
4865 $actorWhere = ActorMigration
::newMigration()->getWhere( $dbr, 'rev_user', $this );
4866 $time = $dbr->selectField(
4867 [ 'revision' ] +
$actorWhere['tables'],
4869 [ $actorWhere['conds'] ],
4871 [ 'ORDER BY' => 'rev_timestamp ASC' ],
4872 $actorWhere['joins']
4875 return false; // no edits
4877 return wfTimestamp( TS_MW
, $time );
4881 * Get the permissions associated with a given list of groups
4883 * @param array $groups Array of Strings List of internal group names
4884 * @return array Array of Strings List of permission key names for given groups combined
4886 public static function getGroupPermissions( $groups ) {
4887 global $wgGroupPermissions, $wgRevokePermissions;
4889 // grant every granted permission first
4890 foreach ( $groups as $group ) {
4891 if ( isset( $wgGroupPermissions[$group] ) ) {
4892 $rights = array_merge( $rights,
4893 // array_filter removes empty items
4894 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4897 // now revoke the revoked permissions
4898 foreach ( $groups as $group ) {
4899 if ( isset( $wgRevokePermissions[$group] ) ) {
4900 $rights = array_diff( $rights,
4901 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4904 return array_unique( $rights );
4908 * Get all the groups who have a given permission
4910 * @param string $role Role to check
4911 * @return array Array of Strings List of internal group names with the given permission
4913 public static function getGroupsWithPermission( $role ) {
4914 global $wgGroupPermissions;
4915 $allowedGroups = [];
4916 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4917 if ( self
::groupHasPermission( $group, $role ) ) {
4918 $allowedGroups[] = $group;
4921 return $allowedGroups;
4925 * Check, if the given group has the given permission
4927 * If you're wanting to check whether all users have a permission, use
4928 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4932 * @param string $group Group to check
4933 * @param string $role Role to check
4936 public static function groupHasPermission( $group, $role ) {
4937 global $wgGroupPermissions, $wgRevokePermissions;
4938 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4939 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4943 * Check if all users may be assumed to have the given permission
4945 * We generally assume so if the right is granted to '*' and isn't revoked
4946 * on any group. It doesn't attempt to take grants or other extension
4947 * limitations on rights into account in the general case, though, as that
4948 * would require it to always return false and defeat the purpose.
4949 * Specifically, session-based rights restrictions (such as OAuth or bot
4950 * passwords) are applied based on the current session.
4953 * @param string $right Right to check
4956 public static function isEveryoneAllowed( $right ) {
4957 global $wgGroupPermissions, $wgRevokePermissions;
4960 // Use the cached results, except in unit tests which rely on
4961 // being able change the permission mid-request
4962 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4963 return $cache[$right];
4966 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4967 $cache[$right] = false;
4971 // If it's revoked anywhere, then everyone doesn't have it
4972 foreach ( $wgRevokePermissions as $rights ) {
4973 if ( isset( $rights[$right] ) && $rights[$right] ) {
4974 $cache[$right] = false;
4979 // Remove any rights that aren't allowed to the global-session user,
4980 // unless there are no sessions for this endpoint.
4981 if ( !defined( 'MW_NO_SESSION' ) ) {
4982 $allowedRights = SessionManager
::getGlobalSession()->getAllowedUserRights();
4983 if ( $allowedRights !== null && !in_array( $right, $allowedRights, true ) ) {
4984 $cache[$right] = false;
4989 // Allow extensions to say false
4990 if ( !Hooks
::run( 'UserIsEveryoneAllowed', [ $right ] ) ) {
4991 $cache[$right] = false;
4995 $cache[$right] = true;
5000 * Get the localized descriptive name for a group, if it exists
5001 * @deprecated since 1.29 Use UserGroupMembership::getGroupName instead
5003 * @param string $group Internal group name
5004 * @return string Localized descriptive group name
5006 public static function getGroupName( $group ) {
5007 wfDeprecated( __METHOD__
, '1.29' );
5008 return UserGroupMembership
::getGroupName( $group );
5012 * Get the localized descriptive name for a member of a group, if it exists
5013 * @deprecated since 1.29 Use UserGroupMembership::getGroupMemberName instead
5015 * @param string $group Internal group name
5016 * @param string $username Username for gender (since 1.19)
5017 * @return string Localized name for group member
5019 public static function getGroupMember( $group, $username = '#' ) {
5020 wfDeprecated( __METHOD__
, '1.29' );
5021 return UserGroupMembership
::getGroupMemberName( $group, $username );
5025 * Return the set of defined explicit groups.
5026 * The implicit groups (by default *, 'user' and 'autoconfirmed')
5027 * are not included, as they are defined automatically, not in the database.
5028 * @return array Array of internal group names
5030 public static function getAllGroups() {
5031 global $wgGroupPermissions, $wgRevokePermissions;
5033 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
5034 self
::getImplicitGroups()
5039 * Get a list of all available permissions.
5040 * @return string[] Array of permission names
5042 public static function getAllRights() {
5043 if ( self
::$mAllRights === false ) {
5044 global $wgAvailableRights;
5045 if ( count( $wgAvailableRights ) ) {
5046 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
5048 self
::$mAllRights = self
::$mCoreRights;
5050 Hooks
::run( 'UserGetAllRights', [ &self
::$mAllRights ] );
5052 return self
::$mAllRights;
5056 * Get a list of implicit groups
5057 * @return array Array of Strings Array of internal group names
5059 public static function getImplicitGroups() {
5060 global $wgImplicitGroups;
5062 $groups = $wgImplicitGroups;
5063 # Deprecated, use $wgImplicitGroups instead
5064 Hooks
::run( 'UserGetImplicitGroups', [ &$groups ], '1.25' );
5070 * Get the title of a page describing a particular group
5071 * @deprecated since 1.29 Use UserGroupMembership::getGroupPage instead
5073 * @param string $group Internal group name
5074 * @return Title|bool Title of the page if it exists, false otherwise
5076 public static function getGroupPage( $group ) {
5077 wfDeprecated( __METHOD__
, '1.29' );
5078 return UserGroupMembership
::getGroupPage( $group );
5082 * Create a link to the group in HTML, if available;
5083 * else return the group name.
5084 * @deprecated since 1.29 Use UserGroupMembership::getLink instead, or
5085 * make the link yourself if you need custom text
5087 * @param string $group Internal name of the group
5088 * @param string $text The text of the link
5089 * @return string HTML link to the group
5091 public static function makeGroupLinkHTML( $group, $text = '' ) {
5092 wfDeprecated( __METHOD__
, '1.29' );
5094 if ( $text == '' ) {
5095 $text = UserGroupMembership
::getGroupName( $group );
5097 $title = UserGroupMembership
::getGroupPage( $group );
5099 return MediaWikiServices
::getInstance()
5100 ->getLinkRenderer()->makeLink( $title, $text );
5102 return htmlspecialchars( $text );
5107 * Create a link to the group in Wikitext, if available;
5108 * else return the group name.
5109 * @deprecated since 1.29 Use UserGroupMembership::getLink instead, or
5110 * make the link yourself if you need custom text
5112 * @param string $group Internal name of the group
5113 * @param string $text The text of the link
5114 * @return string Wikilink to the group
5116 public static function makeGroupLinkWiki( $group, $text = '' ) {
5117 wfDeprecated( __METHOD__
, '1.29' );
5119 if ( $text == '' ) {
5120 $text = UserGroupMembership
::getGroupName( $group );
5122 $title = UserGroupMembership
::getGroupPage( $group );
5124 $page = $title->getFullText();
5125 return "[[$page|$text]]";
5132 * Returns an array of the groups that a particular group can add/remove.
5134 * @param string $group The group to check for whether it can add/remove
5135 * @return array Array( 'add' => array( addablegroups ),
5136 * 'remove' => array( removablegroups ),
5137 * 'add-self' => array( addablegroups to self),
5138 * 'remove-self' => array( removable groups from self) )
5140 public static function changeableByGroup( $group ) {
5141 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
5150 if ( empty( $wgAddGroups[$group] ) ) {
5151 // Don't add anything to $groups
5152 } elseif ( $wgAddGroups[$group] === true ) {
5153 // You get everything
5154 $groups['add'] = self
::getAllGroups();
5155 } elseif ( is_array( $wgAddGroups[$group] ) ) {
5156 $groups['add'] = $wgAddGroups[$group];
5159 // Same thing for remove
5160 if ( empty( $wgRemoveGroups[$group] ) ) {
5162 } elseif ( $wgRemoveGroups[$group] === true ) {
5163 $groups['remove'] = self
::getAllGroups();
5164 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
5165 $groups['remove'] = $wgRemoveGroups[$group];
5168 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
5169 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
5170 foreach ( $wgGroupsAddToSelf as $key => $value ) {
5171 if ( is_int( $key ) ) {
5172 $wgGroupsAddToSelf['user'][] = $value;
5177 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
5178 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
5179 if ( is_int( $key ) ) {
5180 $wgGroupsRemoveFromSelf['user'][] = $value;
5185 // Now figure out what groups the user can add to him/herself
5186 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
5188 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
5189 // No idea WHY this would be used, but it's there
5190 $groups['add-self'] = self
::getAllGroups();
5191 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
5192 $groups['add-self'] = $wgGroupsAddToSelf[$group];
5195 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
5197 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
5198 $groups['remove-self'] = self
::getAllGroups();
5199 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
5200 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
5207 * Returns an array of groups that this user can add and remove
5208 * @return array Array( 'add' => array( addablegroups ),
5209 * 'remove' => array( removablegroups ),
5210 * 'add-self' => array( addablegroups to self),
5211 * 'remove-self' => array( removable groups from self) )
5213 public function changeableGroups() {
5214 if ( $this->isAllowed( 'userrights' ) ) {
5215 // This group gives the right to modify everything (reverse-
5216 // compatibility with old "userrights lets you change
5218 // Using array_merge to make the groups reindexed
5219 $all = array_merge( self
::getAllGroups() );
5228 // Okay, it's not so simple, we will have to go through the arrays
5235 $addergroups = $this->getEffectiveGroups();
5237 foreach ( $addergroups as $addergroup ) {
5238 $groups = array_merge_recursive(
5239 $groups, $this->changeableByGroup( $addergroup )
5241 $groups['add'] = array_unique( $groups['add'] );
5242 $groups['remove'] = array_unique( $groups['remove'] );
5243 $groups['add-self'] = array_unique( $groups['add-self'] );
5244 $groups['remove-self'] = array_unique( $groups['remove-self'] );
5250 * Deferred version of incEditCountImmediate()
5252 * This function, rather than incEditCountImmediate(), should be used for
5253 * most cases as it avoids potential deadlocks caused by concurrent editing.
5255 public function incEditCount() {
5256 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle(
5258 $this->incEditCountImmediate();
5265 * Increment the user's edit-count field.
5266 * Will have no effect for anonymous users.
5269 public function incEditCountImmediate() {
5270 if ( $this->isAnon() ) {
5274 $dbw = wfGetDB( DB_MASTER
);
5275 // No rows will be "affected" if user_editcount is NULL
5278 [ 'user_editcount=user_editcount+1' ],
5279 [ 'user_id' => $this->getId(), 'user_editcount IS NOT NULL' ],
5282 // Lazy initialization check...
5283 if ( $dbw->affectedRows() == 0 ) {
5284 // Now here's a goddamn hack...
5285 $dbr = wfGetDB( DB_REPLICA
);
5286 if ( $dbr !== $dbw ) {
5287 // If we actually have a replica DB server, the count is
5288 // at least one behind because the current transaction
5289 // has not been committed and replicated.
5290 $this->mEditCount
= $this->initEditCount( 1 );
5292 // But if DB_REPLICA is selecting the master, then the
5293 // count we just read includes the revision that was
5294 // just added in the working transaction.
5295 $this->mEditCount
= $this->initEditCount();
5298 if ( $this->mEditCount
=== null ) {
5299 $this->getEditCount();
5300 $dbr = wfGetDB( DB_REPLICA
);
5301 $this->mEditCount +
= ( $dbr !== $dbw ) ?
1 : 0;
5303 $this->mEditCount++
;
5306 // Edit count in user cache too
5307 $this->invalidateCache();
5311 * Initialize user_editcount from data out of the revision table
5313 * @param int $add Edits to add to the count from the revision table
5314 * @return int Number of edits
5316 protected function initEditCount( $add = 0 ) {
5317 // Pull from a replica DB to be less cruel to servers
5318 // Accuracy isn't the point anyway here
5319 $dbr = wfGetDB( DB_REPLICA
);
5320 $actorWhere = ActorMigration
::newMigration()->getWhere( $dbr, 'rev_user', $this );
5321 $count = (int)$dbr->selectField(
5322 [ 'revision' ] +
$actorWhere['tables'],
5324 [ $actorWhere['conds'] ],
5327 $actorWhere['joins']
5329 $count = $count +
$add;
5331 $dbw = wfGetDB( DB_MASTER
);
5334 [ 'user_editcount' => $count ],
5335 [ 'user_id' => $this->getId() ],
5343 * Get the description of a given right
5346 * @param string $right Right to query
5347 * @return string Localized description of the right
5349 public static function getRightDescription( $right ) {
5350 $key = "right-$right";
5351 $msg = wfMessage( $key );
5352 return $msg->isDisabled() ?
$right : $msg->text();
5356 * Get the name of a given grant
5359 * @param string $grant Grant to query
5360 * @return string Localized name of the grant
5362 public static function getGrantName( $grant ) {
5363 $key = "grant-$grant";
5364 $msg = wfMessage( $key );
5365 return $msg->isDisabled() ?
$grant : $msg->text();
5369 * Add a newuser log entry for this user.
5370 * Before 1.19 the return value was always true.
5372 * @deprecated since 1.27, AuthManager handles logging
5373 * @param string|bool $action Account creation type.
5374 * - String, one of the following values:
5375 * - 'create' for an anonymous user creating an account for himself.
5376 * This will force the action's performer to be the created user itself,
5377 * no matter the value of $wgUser
5378 * - 'create2' for a logged in user creating an account for someone else
5379 * - 'byemail' when the created user will receive its password by e-mail
5380 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
5381 * - Boolean means whether the account was created by e-mail (deprecated):
5382 * - true will be converted to 'byemail'
5383 * - false will be converted to 'create' if this object is the same as
5384 * $wgUser and to 'create2' otherwise
5385 * @param string $reason User supplied reason
5388 public function addNewUserLogEntry( $action = false, $reason = '' ) {
5389 return true; // disabled
5393 * Add an autocreate newuser log entry for this user
5394 * Used by things like CentralAuth and perhaps other authplugins.
5395 * Consider calling addNewUserLogEntry() directly instead.
5397 * @deprecated since 1.27, AuthManager handles logging
5400 public function addNewUserLogEntryAutoCreate() {
5401 $this->addNewUserLogEntry( 'autocreate' );
5407 * Load the user options either from cache, the database or an array
5409 * @param array $data Rows for the current user out of the user_properties table
5411 protected function loadOptions( $data = null ) {
5416 if ( $this->mOptionsLoaded
) {
5420 $this->mOptions
= self
::getDefaultOptions();
5422 if ( !$this->getId() ) {
5423 // For unlogged-in users, load language/variant options from request.
5424 // There's no need to do it for logged-in users: they can set preferences,
5425 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5426 // so don't override user's choice (especially when the user chooses site default).
5427 $variant = $wgContLang->getDefaultVariant();
5428 $this->mOptions
['variant'] = $variant;
5429 $this->mOptions
['language'] = $variant;
5430 $this->mOptionsLoaded
= true;
5434 // Maybe load from the object
5435 if ( !is_null( $this->mOptionOverrides
) ) {
5436 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5437 foreach ( $this->mOptionOverrides
as $key => $value ) {
5438 $this->mOptions
[$key] = $value;
5441 if ( !is_array( $data ) ) {
5442 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5443 // Load from database
5444 $dbr = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
5445 ?
wfGetDB( DB_MASTER
)
5446 : wfGetDB( DB_REPLICA
);
5448 $res = $dbr->select(
5450 [ 'up_property', 'up_value' ],
5451 [ 'up_user' => $this->getId() ],
5455 $this->mOptionOverrides
= [];
5457 foreach ( $res as $row ) {
5458 // Convert '0' to 0. PHP's boolean conversion considers them both
5459 // false, but e.g. JavaScript considers the former as true.
5460 // @todo: T54542 Somehow determine the desired type (string/int/bool)
5461 // and convert all values here.
5462 if ( $row->up_value
=== '0' ) {
5465 $data[$row->up_property
] = $row->up_value
;
5469 // Convert the email blacklist from a new line delimited string
5470 // to an array of ids.
5471 if ( isset( $data['email-blacklist'] ) && $data['email-blacklist'] ) {
5472 $data['email-blacklist'] = array_map( 'intval', explode( "\n", $data['email-blacklist'] ) );
5475 foreach ( $data as $property => $value ) {
5476 $this->mOptionOverrides
[$property] = $value;
5477 $this->mOptions
[$property] = $value;
5481 $this->mOptionsLoaded
= true;
5483 Hooks
::run( 'UserLoadOptions', [ $this, &$this->mOptions
] );
5487 * Saves the non-default options for this user, as previously set e.g. via
5488 * setOption(), in the database's "user_properties" (preferences) table.
5489 * Usually used via saveSettings().
5491 protected function saveOptions() {
5492 $this->loadOptions();
5494 // Not using getOptions(), to keep hidden preferences in database
5495 $saveOptions = $this->mOptions
;
5497 // Convert usernames to ids.
5498 if ( isset( $this->mOptions
['email-blacklist'] ) ) {
5499 if ( $this->mOptions
['email-blacklist'] ) {
5500 $value = $this->mOptions
['email-blacklist'];
5501 // Email Blacklist may be an array of ids or a string of new line
5502 // delimnated user names.
5503 if ( is_array( $value ) ) {
5504 $ids = array_filter( $value, 'is_numeric' );
5506 $lookup = CentralIdLookup
::factory();
5507 $ids = $lookup->centralIdsFromNames( explode( "\n", $value ), $this );
5509 $this->mOptions
['email-blacklist'] = $ids;
5510 $saveOptions['email-blacklist'] = implode( "\n", $this->mOptions
['email-blacklist'] );
5512 // If the blacklist is empty, set it to null rather than an empty string.
5513 $this->mOptions
['email-blacklist'] = null;
5517 // Allow hooks to abort, for instance to save to a global profile.
5518 // Reset options to default state before saving.
5519 if ( !Hooks
::run( 'UserSaveOptions', [ $this, &$saveOptions ] ) ) {
5523 $userId = $this->getId();
5525 $insert_rows = []; // all the new preference rows
5526 foreach ( $saveOptions as $key => $value ) {
5527 // Don't bother storing default values
5528 $defaultOption = self
::getDefaultOption( $key );
5529 if ( ( $defaultOption === null && $value !== false && $value !== null )
5530 ||
$value != $defaultOption
5533 'up_user' => $userId,
5534 'up_property' => $key,
5535 'up_value' => $value,
5540 $dbw = wfGetDB( DB_MASTER
);
5542 $res = $dbw->select( 'user_properties',
5543 [ 'up_property', 'up_value' ], [ 'up_user' => $userId ], __METHOD__
);
5545 // Find prior rows that need to be removed or updated. These rows will
5546 // all be deleted (the latter so that INSERT IGNORE applies the new values).
5548 foreach ( $res as $row ) {
5549 if ( !isset( $saveOptions[$row->up_property
] )
5550 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
5552 $keysDelete[] = $row->up_property
;
5556 if ( count( $keysDelete ) ) {
5557 // Do the DELETE by PRIMARY KEY for prior rows.
5558 // In the past a very large portion of calls to this function are for setting
5559 // 'rememberpassword' for new accounts (a preference that has since been removed).
5560 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5561 // caused gap locks on [max user ID,+infinity) which caused high contention since
5562 // updates would pile up on each other as they are for higher (newer) user IDs.
5563 // It might not be necessary these days, but it shouldn't hurt either.
5564 $dbw->delete( 'user_properties',
5565 [ 'up_user' => $userId, 'up_property' => $keysDelete ], __METHOD__
);
5567 // Insert the new preference rows
5568 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, [ 'IGNORE' ] );
5572 * Lazily instantiate and return a factory object for making passwords
5574 * @deprecated since 1.27, create a PasswordFactory directly instead
5575 * @return PasswordFactory
5577 public static function getPasswordFactory() {
5578 wfDeprecated( __METHOD__
, '1.27' );
5579 $ret = new PasswordFactory();
5580 $ret->init( RequestContext
::getMain()->getConfig() );
5585 * Provide an array of HTML5 attributes to put on an input element
5586 * intended for the user to enter a new password. This may include
5587 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
5589 * Do *not* use this when asking the user to enter his current password!
5590 * Regardless of configuration, users may have invalid passwords for whatever
5591 * reason (e.g., they were set before requirements were tightened up).
5592 * Only use it when asking for a new password, like on account creation or
5595 * Obviously, you still need to do server-side checking.
5597 * NOTE: A combination of bugs in various browsers means that this function
5598 * actually just returns array() unconditionally at the moment. May as
5599 * well keep it around for when the browser bugs get fixed, though.
5601 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
5603 * @deprecated since 1.27
5604 * @return array Array of HTML attributes suitable for feeding to
5605 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
5606 * That will get confused by the boolean attribute syntax used.)
5608 public static function passwordChangeInputAttribs() {
5609 global $wgMinimalPasswordLength;
5611 if ( $wgMinimalPasswordLength == 0 ) {
5615 # Note that the pattern requirement will always be satisfied if the
5616 # input is empty, so we need required in all cases.
5618 # @todo FIXME: T25769: This needs to not claim the password is required
5619 # if e-mail confirmation is being used. Since HTML5 input validation
5620 # is b0rked anyway in some browsers, just return nothing. When it's
5621 # re-enabled, fix this code to not output required for e-mail
5623 # $ret = array( 'required' );
5626 # We can't actually do this right now, because Opera 9.6 will print out
5627 # the entered password visibly in its error message! When other
5628 # browsers add support for this attribute, or Opera fixes its support,
5629 # we can add support with a version check to avoid doing this on Opera
5630 # versions where it will be a problem. Reported to Opera as
5631 # DSK-262266, but they don't have a public bug tracker for us to follow.
5633 if ( $wgMinimalPasswordLength > 1 ) {
5634 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
5635 $ret['title'] = wfMessage( 'passwordtooshort' )
5636 ->numParams( $wgMinimalPasswordLength )->text();
5644 * Return the list of user fields that should be selected to create
5645 * a new user object.
5646 * @deprecated since 1.31, use self::getQueryInfo() instead.
5649 public static function selectFields() {
5650 wfDeprecated( __METHOD__
, '1.31' );
5658 'user_email_authenticated',
5660 'user_email_token_expires',
5661 'user_registration',
5667 * Return the tables, fields, and join conditions to be selected to create
5668 * a new user object.
5670 * @return array With three keys:
5671 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
5672 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
5673 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
5675 public static function getQueryInfo() {
5676 global $wgActorTableSchemaMigrationStage;
5679 'tables' => [ 'user' ],
5687 'user_email_authenticated',
5689 'user_email_token_expires',
5690 'user_registration',
5695 if ( $wgActorTableSchemaMigrationStage > MIGRATION_OLD
) {
5696 $ret['tables']['user_actor'] = 'actor';
5697 $ret['fields'][] = 'user_actor.actor_id';
5698 $ret['joins']['user_actor'] = [
5699 $wgActorTableSchemaMigrationStage === MIGRATION_NEW ?
'JOIN' : 'LEFT JOIN',
5700 [ 'user_actor.actor_user = user_id' ]
5707 * Factory function for fatal permission-denied errors
5710 * @param string $permission User right required
5713 static function newFatalPermissionDeniedStatus( $permission ) {
5717 foreach ( self
::getGroupsWithPermission( $permission ) as $group ) {
5718 $groups[] = UserGroupMembership
::getLink( $group, RequestContext
::getMain(), 'wiki' );
5722 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5724 return Status
::newFatal( 'badaccess-group0' );
5729 * Get a new instance of this user that was loaded from the master via a locking read
5731 * Use this instead of the main context User when updating that user. This avoids races
5732 * where that user was loaded from a replica DB or even the master but without proper locks.
5734 * @return User|null Returns null if the user was not found in the DB
5737 public function getInstanceForUpdate() {
5738 if ( !$this->getId() ) {
5739 return null; // anon
5742 $user = self
::newFromId( $this->getId() );
5743 if ( !$user->loadFromId( self
::READ_EXCLUSIVE
) ) {
5751 * Checks if two user objects point to the same user.
5757 public function equals( User
$user ) {
5758 return $this->getName() === $user->getName();