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 Wikimedia\ScopedCallback
;
32 * String Some punctuation to prevent editing from broken text-mangling proxies.
33 * @deprecated since 1.27, use \MediaWiki\Session\Token::SUFFIX
36 define( 'EDIT_TOKEN_SUFFIX', Token
::SUFFIX
);
39 * The User object encapsulates all of the user-specific settings (user_id,
40 * name, rights, email address, options, last login time). Client
41 * classes use the getXXX() functions to access these fields. These functions
42 * do all the work of determining whether the user is logged in,
43 * whether the requested option can be satisfied from cookies or
44 * whether a database query is needed. Most of the settings needed
45 * for rendering normal pages are set in the cookie to minimize use
48 class User
implements IDBAccessObject
{
50 * @const int Number of characters in user_token field.
52 const TOKEN_LENGTH
= 32;
55 * @const string An invalid value for user_token
57 const INVALID_TOKEN
= '*** INVALID ***';
60 * Global constant made accessible as class constants so that autoloader
62 * @deprecated since 1.27, use \MediaWiki\Session\Token::SUFFIX
64 const EDIT_TOKEN_SUFFIX
= EDIT_TOKEN_SUFFIX
;
67 * @const int Serialized record version.
72 * Exclude user options that are set to their default value.
75 const GETOPTIONS_EXCLUDE_DEFAULTS
= 1;
80 const CHECK_USER_RIGHTS
= true;
85 const IGNORE_USER_RIGHTS
= false;
88 * Array of Strings List of member variables which are saved to the
89 * shared cache (memcached). Any operation which changes the
90 * corresponding database fields must call a cache-clearing function.
93 protected static $mCacheVars = [
101 'mEmailAuthenticated',
103 'mEmailTokenExpires',
108 // user_properties table
113 * Array of Strings Core rights.
114 * Each of these should have a corresponding message of the form
118 protected static $mCoreRights = [
149 'editusercssjs', # deprecated
162 'move-categorypages',
163 'move-rootuserpages',
167 'override-export-depth',
189 'userrights-interwiki',
197 * String Cached results of getAllRights()
199 protected static $mAllRights = false;
201 /** Cache variables */
212 /** @var string TS_MW timestamp from the DB */
214 /** @var string TS_MW timestamp from cache */
215 protected $mQuickTouched;
219 public $mEmailAuthenticated;
221 protected $mEmailToken;
223 protected $mEmailTokenExpires;
225 protected $mRegistration;
227 protected $mEditCount;
229 * @var array No longer used since 1.29; use User::getGroups() instead
230 * @deprecated since 1.29
233 /** @var array Associative array of (group name => UserGroupMembership object) */
234 protected $mGroupMemberships;
236 protected $mOptionOverrides;
240 * Bool Whether the cache variables have been loaded.
243 public $mOptionsLoaded;
246 * Array with already loaded items or true if all items have been loaded.
248 protected $mLoadedItems = [];
252 * String Initialization data source if mLoadedItems!==true. May be one of:
253 * - 'defaults' anonymous user initialised from class defaults
254 * - 'name' initialise from mName
255 * - 'id' initialise from mId
256 * - 'session' log in from session if possible
258 * Use the User::newFrom*() family of functions to set this.
263 * Lazy-initialized variables, invalidated with clearInstanceCache
267 protected $mDatePreference;
275 protected $mBlockreason;
277 protected $mEffectiveGroups;
279 protected $mImplicitGroups;
281 protected $mFormerGroups;
283 protected $mGlobalBlock;
291 /** @var WebRequest */
298 protected $mAllowUsertalk;
301 private $mBlockedFromCreateAccount = false;
303 /** @var integer User::READ_* constant bitfield used to load data */
304 protected $queryFlagsUsed = self
::READ_NORMAL
;
306 /** @var string Indicates type of block (used for eventlogging)
307 * Permitted values: 'cookie-block', 'proxy-block', 'openproxy-block', 'xff-block',
310 public $blockTrigger = false;
312 public static $idCacheByName = [];
315 * Lightweight constructor for an anonymous user.
316 * Use the User::newFrom* factory functions for other kinds of users.
320 * @see newFromConfirmationCode()
321 * @see newFromSession()
324 public function __construct() {
325 $this->clearInstanceCache( 'defaults' );
331 public function __toString() {
332 return (string)$this->getName();
336 * Test if it's safe to load this User object.
338 * You should typically check this before using $wgUser or
339 * RequestContext::getUser in a method that might be called before the
340 * system has been fully initialized. If the object is unsafe, you should
341 * use an anonymous user:
343 * $user = $wgUser->isSafeToLoad() ? $wgUser : new User;
349 public function isSafeToLoad() {
350 global $wgFullyInitialised;
352 // The user is safe to load if:
353 // * MW_NO_SESSION is undefined AND $wgFullyInitialised is true (safe to use session data)
354 // * mLoadedItems === true (already loaded)
355 // * mFrom !== 'session' (sessions not involved at all)
357 return ( !defined( 'MW_NO_SESSION' ) && $wgFullyInitialised ) ||
358 $this->mLoadedItems
=== true ||
$this->mFrom
!== 'session';
362 * Load the user table data for this object from the source given by mFrom.
364 * @param integer $flags User::READ_* constant bitfield
366 public function load( $flags = self
::READ_NORMAL
) {
367 global $wgFullyInitialised;
369 if ( $this->mLoadedItems
=== true ) {
373 // Set it now to avoid infinite recursion in accessors
374 $oldLoadedItems = $this->mLoadedItems
;
375 $this->mLoadedItems
= true;
376 $this->queryFlagsUsed
= $flags;
378 // If this is called too early, things are likely to break.
379 if ( !$wgFullyInitialised && $this->mFrom
=== 'session' ) {
380 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
381 ->warning( 'User::loadFromSession called before the end of Setup.php', [
382 'exception' => new Exception( 'User::loadFromSession called before the end of Setup.php' ),
384 $this->loadDefaults();
385 $this->mLoadedItems
= $oldLoadedItems;
389 switch ( $this->mFrom
) {
391 $this->loadDefaults();
394 // Make sure this thread sees its own changes
395 if ( wfGetLB()->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 $this->loadFromId( $flags );
412 if ( !$this->loadFromSession() ) {
413 // Loading from session failed. Load defaults.
414 $this->loadDefaults();
416 Hooks
::run( 'UserLoadAfterLoadFromSession', [ $this ] );
419 throw new UnexpectedValueException(
420 "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
425 * Load user table data, given mId has already been set.
426 * @param integer $flags User::READ_* constant bitfield
427 * @return bool False if the ID does not exist, true otherwise
429 public function loadFromId( $flags = self
::READ_NORMAL
) {
430 if ( $this->mId
== 0 ) {
431 // Anonymous users are not in the database (don't need cache)
432 $this->loadDefaults();
436 // Try cache (unless this needs data from the master DB).
437 // NOTE: if this thread called saveSettings(), the cache was cleared.
438 $latest = DBAccessObjectUtils
::hasFlags( $flags, self
::READ_LATEST
);
440 if ( !$this->loadFromDatabase( $flags ) ) {
441 // Can't load from ID
445 $this->loadFromCache();
448 $this->mLoadedItems
= true;
449 $this->queryFlagsUsed
= $flags;
456 * @param string $wikiId
457 * @param integer $userId
459 public static function purge( $wikiId, $userId ) {
460 $cache = ObjectCache
::getMainWANInstance();
461 $key = $cache->makeGlobalKey( 'user', 'id', $wikiId, $userId );
462 $cache->delete( $key );
467 * @param WANObjectCache $cache
470 protected function getCacheKey( WANObjectCache
$cache ) {
471 return $cache->makeGlobalKey( 'user', 'id', wfWikiID(), $this->mId
);
475 * @param WANObjectCache $cache
479 public function getMutableCacheKeys( WANObjectCache
$cache ) {
480 $id = $this->getId();
482 return $id ?
[ $this->getCacheKey( $cache ) ] : [];
486 * Load user data from shared cache, given mId has already been set.
491 protected function loadFromCache() {
492 $cache = ObjectCache
::getMainWANInstance();
493 $data = $cache->getWithSetCallback(
494 $this->getCacheKey( $cache ),
496 function ( $oldValue, &$ttl, array &$setOpts ) use ( $cache ) {
497 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
498 wfDebug( "User: cache miss for user {$this->mId}\n" );
500 $this->loadFromDatabase( self
::READ_NORMAL
);
502 $this->loadOptions();
505 foreach ( self
::$mCacheVars as $name ) {
506 $data[$name] = $this->$name;
509 $ttl = $cache->adaptiveTTL( wfTimestamp( TS_UNIX
, $this->mTouched
), $ttl );
514 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'version' => self
::VERSION
]
517 // Restore from cache
518 foreach ( self
::$mCacheVars as $name ) {
519 $this->$name = $data[$name];
525 /** @name newFrom*() static factory methods */
529 * Static factory method for creation from username.
531 * This is slightly less efficient than newFromId(), so use newFromId() if
532 * you have both an ID and a name handy.
534 * @param string $name Username, validated by Title::newFromText()
535 * @param string|bool $validate Validate username. Takes the same parameters as
536 * User::getCanonicalName(), except that true is accepted as an alias
537 * for 'valid', for BC.
539 * @return User|bool User object, or false if the username is invalid
540 * (e.g. if it contains illegal characters or is an IP address). If the
541 * username is not present in the database, the result will be a user object
542 * with a name, zero user ID and default settings.
544 public static function newFromName( $name, $validate = 'valid' ) {
545 if ( $validate === true ) {
548 $name = self
::getCanonicalName( $name, $validate );
549 if ( $name === false ) {
552 // Create unloaded user object
556 $u->setItemLoaded( 'name' );
562 * Static factory method for creation from a given user ID.
564 * @param int $id Valid user ID
565 * @return User The corresponding User object
567 public static function newFromId( $id ) {
571 $u->setItemLoaded( 'id' );
576 * Factory method to fetch whichever user has a given email confirmation code.
577 * This code is generated when an account is created or its e-mail address
580 * If the code is invalid or has expired, returns NULL.
582 * @param string $code Confirmation code
583 * @param int $flags User::READ_* bitfield
586 public static function newFromConfirmationCode( $code, $flags = 0 ) {
587 $db = ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
588 ?
wfGetDB( DB_MASTER
)
589 : wfGetDB( DB_REPLICA
);
591 $id = $db->selectField(
595 'user_email_token' => md5( $code ),
596 'user_email_token_expires > ' . $db->addQuotes( $db->timestamp() ),
600 return $id ? User
::newFromId( $id ) : null;
604 * Create a new user object using data from session. If the login
605 * credentials are invalid, the result is an anonymous user.
607 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
610 public static function newFromSession( WebRequest
$request = null ) {
612 $user->mFrom
= 'session';
613 $user->mRequest
= $request;
618 * Create a new user object from a user row.
619 * The row should have the following fields from the user table in it:
620 * - either user_name or user_id to load further data if needed (or both)
622 * - all other fields (email, etc.)
623 * It is useless to provide the remaining fields if either user_id,
624 * user_name and user_real_name are not provided because the whole row
625 * will be loaded once more from the database when accessing them.
627 * @param stdClass $row A row from the user table
628 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
631 public static function newFromRow( $row, $data = null ) {
633 $user->loadFromRow( $row, $data );
638 * Static factory method for creation of a "system" user from username.
640 * A "system" user is an account that's used to attribute logged actions
641 * taken by MediaWiki itself, as opposed to a bot or human user. Examples
642 * might include the 'Maintenance script' or 'Conversion script' accounts
643 * used by various scripts in the maintenance/ directory or accounts such
644 * as 'MediaWiki message delivery' used by the MassMessage extension.
646 * This can optionally create the user if it doesn't exist, and "steal" the
647 * account if it does exist.
649 * "Stealing" an existing user is intended to make it impossible for normal
650 * authentication processes to use the account, effectively disabling the
651 * account for normal use:
652 * - Email is invalidated, to prevent account recovery by emailing a
653 * temporary password and to disassociate the account from the existing
655 * - The token is set to a magic invalid value, to kill existing sessions
656 * and to prevent $this->setToken() calls from resetting the token to a
658 * - SessionManager is instructed to prevent new sessions for the user, to
659 * do things like deauthorizing OAuth consumers.
660 * - AuthManager is instructed to revoke access, to invalidate or remove
661 * passwords and other credentials.
663 * @param string $name Username
664 * @param array $options Options are:
665 * - validate: As for User::getCanonicalName(), default 'valid'
666 * - create: Whether to create the user if it doesn't already exist, default true
667 * - steal: Whether to "disable" the account for normal use if it already
668 * exists, default false
672 public static function newSystemUser( $name, $options = [] ) {
674 'validate' => 'valid',
679 $name = self
::getCanonicalName( $name, $options['validate'] );
680 if ( $name === false ) {
684 $fields = self
::selectFields();
686 $dbw = wfGetDB( DB_MASTER
);
687 $row = $dbw->selectRow(
690 [ 'user_name' => $name ],
694 // No user. Create it?
695 return $options['create'] ? self
::createNew( $name, [ 'token' => self
::INVALID_TOKEN
] ) : null;
697 $user = self
::newFromRow( $row );
699 // A user is considered to exist as a non-system user if it can
700 // authenticate, or has an email set, or has a non-invalid token.
701 if ( $user->mEmail ||
$user->mToken
!== self
::INVALID_TOKEN ||
702 AuthManager
::singleton()->userCanAuthenticate( $name )
704 // User exists. Steal it?
705 if ( !$options['steal'] ) {
709 AuthManager
::singleton()->revokeAccessForUser( $name );
711 $user->invalidateEmail();
712 $user->mToken
= self
::INVALID_TOKEN
;
713 $user->saveSettings();
714 SessionManager
::singleton()->preventSessionsForUser( $user->getName() );
723 * Get the username corresponding to a given user ID
724 * @param int $id User ID
725 * @return string|bool The corresponding username
727 public static function whoIs( $id ) {
728 return UserCache
::singleton()->getProp( $id, 'name' );
732 * Get the real name of a user given their user ID
734 * @param int $id User ID
735 * @return string|bool The corresponding user's real name
737 public static function whoIsReal( $id ) {
738 return UserCache
::singleton()->getProp( $id, 'real_name' );
742 * Get database id given a user name
743 * @param string $name Username
744 * @param integer $flags User::READ_* constant bitfield
745 * @return int|null The corresponding user's ID, or null if user is nonexistent
747 public static function idFromName( $name, $flags = self
::READ_NORMAL
) {
748 $nt = Title
::makeTitleSafe( NS_USER
, $name );
749 if ( is_null( $nt ) ) {
754 if ( !( $flags & self
::READ_LATEST
) && isset( self
::$idCacheByName[$name] ) ) {
755 return self
::$idCacheByName[$name];
758 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
759 $db = wfGetDB( $index );
764 [ 'user_name' => $nt->getText() ],
769 if ( $s === false ) {
772 $result = $s->user_id
;
775 self
::$idCacheByName[$name] = $result;
777 if ( count( self
::$idCacheByName ) > 1000 ) {
778 self
::$idCacheByName = [];
785 * Reset the cache used in idFromName(). For use in tests.
787 public static function resetIdByNameCache() {
788 self
::$idCacheByName = [];
792 * Does the string match an anonymous IP address?
794 * This function exists for username validation, in order to reject
795 * usernames which are similar in form to IP addresses. Strings such
796 * as 300.300.300.300 will return true because it looks like an IP
797 * address, despite not being strictly valid.
799 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
800 * address because the usemod software would "cloak" anonymous IP
801 * addresses like this, if we allowed accounts like this to be created
802 * new users could get the old edits of these anonymous users.
804 * @param string $name Name to match
807 public static function isIP( $name ) {
808 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
809 || IP
::isIPv6( $name );
813 * Is the input a valid username?
815 * Checks if the input is a valid username, we don't want an empty string,
816 * an IP address, anything that contains slashes (would mess up subpages),
817 * is longer than the maximum allowed username size or doesn't begin with
820 * @param string $name Name to match
823 public static function isValidUserName( $name ) {
824 global $wgContLang, $wgMaxNameChars;
827 || User
::isIP( $name )
828 ||
strpos( $name, '/' ) !== false
829 ||
strlen( $name ) > $wgMaxNameChars
830 ||
$name != $wgContLang->ucfirst( $name )
835 // Ensure that the name can't be misresolved as a different title,
836 // such as with extra namespace keys at the start.
837 $parsed = Title
::newFromText( $name );
838 if ( is_null( $parsed )
839 ||
$parsed->getNamespace()
840 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
844 // Check an additional blacklist of troublemaker characters.
845 // Should these be merged into the title char list?
846 $unicodeBlacklist = '/[' .
847 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
848 '\x{00a0}' . # non-breaking space
849 '\x{2000}-\x{200f}' . # various whitespace
850 '\x{2028}-\x{202f}' . # breaks and control chars
851 '\x{3000}' . # ideographic space
852 '\x{e000}-\x{f8ff}' . # private use
854 if ( preg_match( $unicodeBlacklist, $name ) ) {
862 * Usernames which fail to pass this function will be blocked
863 * from user login and new account registrations, but may be used
864 * internally by batch processes.
866 * If an account already exists in this form, login will be blocked
867 * by a failure to pass this function.
869 * @param string $name Name to match
872 public static function isUsableName( $name ) {
873 global $wgReservedUsernames;
874 // Must be a valid username, obviously ;)
875 if ( !self
::isValidUserName( $name ) ) {
879 static $reservedUsernames = false;
880 if ( !$reservedUsernames ) {
881 $reservedUsernames = $wgReservedUsernames;
882 Hooks
::run( 'UserGetReservedNames', [ &$reservedUsernames ] );
885 // Certain names may be reserved for batch processes.
886 foreach ( $reservedUsernames as $reserved ) {
887 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
888 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
890 if ( $reserved == $name ) {
898 * Return the users who are members of the given group(s). In case of multiple groups,
899 * users who are members of at least one of them are returned.
901 * @param string|array $groups A single group name or an array of group names
902 * @param int $limit Max number of users to return. The actual limit will never exceed 5000
903 * records; larger values are ignored.
904 * @param int $after ID the user to start after
905 * @return UserArrayFromResult
907 public static function findUsersByGroup( $groups, $limit = 5000, $after = null ) {
908 if ( $groups === [] ) {
909 return UserArrayFromResult
::newFromIDs( [] );
912 $groups = array_unique( (array)$groups );
913 $limit = min( 5000, $limit );
915 $conds = [ 'ug_group' => $groups ];
916 if ( $after !== null ) {
917 $conds[] = 'ug_user > ' . (int)$after;
920 $dbr = wfGetDB( DB_REPLICA
);
921 $ids = $dbr->selectFieldValues(
928 'ORDER BY' => 'ug_user',
932 return UserArray
::newFromIDs( $ids );
936 * Usernames which fail to pass this function will be blocked
937 * from new account registrations, but may be used internally
938 * either by batch processes or by user accounts which have
939 * already been created.
941 * Additional blacklisting may be added here rather than in
942 * isValidUserName() to avoid disrupting existing accounts.
944 * @param string $name String to match
947 public static function isCreatableName( $name ) {
948 global $wgInvalidUsernameCharacters;
950 // Ensure that the username isn't longer than 235 bytes, so that
951 // (at least for the builtin skins) user javascript and css files
952 // will work. (bug 23080)
953 if ( strlen( $name ) > 235 ) {
954 wfDebugLog( 'username', __METHOD__
.
955 ": '$name' invalid due to length" );
959 // Preg yells if you try to give it an empty string
960 if ( $wgInvalidUsernameCharacters !== '' ) {
961 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
962 wfDebugLog( 'username', __METHOD__
.
963 ": '$name' invalid due to wgInvalidUsernameCharacters" );
968 return self
::isUsableName( $name );
972 * Is the input a valid password for this user?
974 * @param string $password Desired password
977 public function isValidPassword( $password ) {
978 // simple boolean wrapper for getPasswordValidity
979 return $this->getPasswordValidity( $password ) === true;
983 * Given unvalidated password input, return error message on failure.
985 * @param string $password Desired password
986 * @return bool|string|array True on success, string or array of error message on failure
988 public function getPasswordValidity( $password ) {
989 $result = $this->checkPasswordValidity( $password );
990 if ( $result->isGood() ) {
994 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
995 $messages[] = $error['message'];
997 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
998 $messages[] = $warning['message'];
1000 if ( count( $messages ) === 1 ) {
1001 return $messages[0];
1008 * Check if this is a valid password for this user
1010 * Create a Status object based on the password's validity.
1011 * The Status should be set to fatal if the user should not
1012 * be allowed to log in, and should have any errors that
1013 * would block changing the password.
1015 * If the return value of this is not OK, the password
1016 * should not be checked. If the return value is not Good,
1017 * the password can be checked, but the user should not be
1018 * able to set their password to this.
1020 * @param string $password Desired password
1024 public function checkPasswordValidity( $password ) {
1025 global $wgPasswordPolicy;
1027 $upp = new UserPasswordPolicy(
1028 $wgPasswordPolicy['policies'],
1029 $wgPasswordPolicy['checks']
1032 $status = Status
::newGood();
1033 $result = false; // init $result to false for the internal checks
1035 if ( !Hooks
::run( 'isValidPassword', [ $password, &$result, $this ] ) ) {
1036 $status->error( $result );
1040 if ( $result === false ) {
1041 $status->merge( $upp->checkUserPassword( $this, $password ) );
1043 } elseif ( $result === true ) {
1046 $status->error( $result );
1047 return $status; // the isValidPassword hook set a string $result and returned true
1052 * Given unvalidated user input, return a canonical username, or false if
1053 * the username is invalid.
1054 * @param string $name User input
1055 * @param string|bool $validate Type of validation to use:
1056 * - false No validation
1057 * - 'valid' Valid for batch processes
1058 * - 'usable' Valid for batch processes and login
1059 * - 'creatable' Valid for batch processes, login and account creation
1061 * @throws InvalidArgumentException
1062 * @return bool|string
1064 public static function getCanonicalName( $name, $validate = 'valid' ) {
1065 // Force usernames to capital
1067 $name = $wgContLang->ucfirst( $name );
1069 # Reject names containing '#'; these will be cleaned up
1070 # with title normalisation, but then it's too late to
1072 if ( strpos( $name, '#' ) !== false ) {
1076 // Clean up name according to title rules,
1077 // but only when validation is requested (bug 12654)
1078 $t = ( $validate !== false ) ?
1079 Title
::newFromText( $name, NS_USER
) : Title
::makeTitle( NS_USER
, $name );
1080 // Check for invalid titles
1081 if ( is_null( $t ) ||
$t->getNamespace() !== NS_USER ||
$t->isExternal() ) {
1085 // Reject various classes of invalid names
1086 $name = AuthManager
::callLegacyAuthPlugin(
1087 'getCanonicalName', [ $t->getText() ], $t->getText()
1090 switch ( $validate ) {
1094 if ( !User
::isValidUserName( $name ) ) {
1099 if ( !User
::isUsableName( $name ) ) {
1104 if ( !User
::isCreatableName( $name ) ) {
1109 throw new InvalidArgumentException(
1110 'Invalid parameter value for $validate in ' . __METHOD__
);
1116 * Return a random password.
1118 * @deprecated since 1.27, use PasswordFactory::generateRandomPasswordString()
1119 * @return string New random password
1121 public static function randomPassword() {
1122 global $wgMinimalPasswordLength;
1123 return PasswordFactory
::generateRandomPasswordString( $wgMinimalPasswordLength );
1127 * Set cached properties to default.
1129 * @note This no longer clears uncached lazy-initialised properties;
1130 * the constructor does that instead.
1132 * @param string|bool $name
1134 public function loadDefaults( $name = false ) {
1136 $this->mName
= $name;
1137 $this->mRealName
= '';
1139 $this->mOptionOverrides
= null;
1140 $this->mOptionsLoaded
= false;
1142 $loggedOut = $this->mRequest
&& !defined( 'MW_NO_SESSION' )
1143 ?
$this->mRequest
->getSession()->getLoggedOutTimestamp() : 0;
1144 if ( $loggedOut !== 0 ) {
1145 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1147 $this->mTouched
= '1'; # Allow any pages to be cached
1150 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1151 $this->mEmailAuthenticated
= null;
1152 $this->mEmailToken
= '';
1153 $this->mEmailTokenExpires
= null;
1154 $this->mRegistration
= wfTimestamp( TS_MW
);
1155 $this->mGroupMemberships
= [];
1157 Hooks
::run( 'UserLoadDefaults', [ $this, $name ] );
1161 * Return whether an item has been loaded.
1163 * @param string $item Item to check. Current possibilities:
1167 * @param string $all 'all' to check if the whole object has been loaded
1168 * or any other string to check if only the item is available (e.g.
1172 public function isItemLoaded( $item, $all = 'all' ) {
1173 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1174 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1178 * Set that an item has been loaded
1180 * @param string $item
1182 protected function setItemLoaded( $item ) {
1183 if ( is_array( $this->mLoadedItems
) ) {
1184 $this->mLoadedItems
[$item] = true;
1189 * Load user data from the session.
1191 * @return bool True if the user is logged in, false otherwise.
1193 private function loadFromSession() {
1196 Hooks
::run( 'UserLoadFromSession', [ $this, &$result ], '1.27' );
1197 if ( $result !== null ) {
1201 // MediaWiki\Session\Session already did the necessary authentication of the user
1202 // returned here, so just use it if applicable.
1203 $session = $this->getRequest()->getSession();
1204 $user = $session->getUser();
1205 if ( $user->isLoggedIn() ) {
1206 $this->loadFromUserObject( $user );
1208 // If this user is autoblocked, set a cookie to track the Block. This has to be done on
1209 // every session load, because an autoblocked editor might not edit again from the same
1210 // IP address after being blocked.
1211 $config = RequestContext
::getMain()->getConfig();
1212 if ( $config->get( 'CookieSetOnAutoblock' ) === true ) {
1213 $block = $this->getBlock();
1214 $shouldSetCookie = $this->getRequest()->getCookie( 'BlockID' ) === null
1216 && $block->getType() === Block
::TYPE_USER
1217 && $block->isAutoblocking();
1218 if ( $shouldSetCookie ) {
1219 wfDebug( __METHOD__
. ': User is autoblocked, setting cookie to track' );
1220 $block->setCookie( $this->getRequest()->response() );
1224 // Other code expects these to be set in the session, so set them.
1225 $session->set( 'wsUserID', $this->getId() );
1226 $session->set( 'wsUserName', $this->getName() );
1227 $session->set( 'wsToken', $this->getToken() );
1234 * Load user and user_group data from the database.
1235 * $this->mId must be set, this is how the user is identified.
1237 * @param integer $flags User::READ_* constant bitfield
1238 * @return bool True if the user exists, false if the user is anonymous
1240 public function loadFromDatabase( $flags = self
::READ_LATEST
) {
1242 $this->mId
= intval( $this->mId
);
1244 if ( !$this->mId
) {
1245 // Anonymous users are not in the database
1246 $this->loadDefaults();
1250 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
1251 $db = wfGetDB( $index );
1253 $s = $db->selectRow(
1255 self
::selectFields(),
1256 [ 'user_id' => $this->mId
],
1261 $this->queryFlagsUsed
= $flags;
1262 Hooks
::run( 'UserLoadFromDatabase', [ $this, &$s ] );
1264 if ( $s !== false ) {
1265 // Initialise user table data
1266 $this->loadFromRow( $s );
1267 $this->mGroupMemberships
= null; // deferred
1268 $this->getEditCount(); // revalidation for nulls
1273 $this->loadDefaults();
1279 * Initialize this object from a row from the user table.
1281 * @param stdClass $row Row from the user table to load.
1282 * @param array $data Further user data to load into the object
1284 * user_groups Array of arrays or stdClass result rows out of the user_groups
1285 * table. Previously you were supposed to pass an array of strings
1286 * here, but we also need expiry info nowadays, so an array of
1287 * strings is ignored.
1288 * user_properties Array with properties out of the user_properties table
1290 protected function loadFromRow( $row, $data = null ) {
1293 $this->mGroupMemberships
= null; // deferred
1295 if ( isset( $row->user_name
) ) {
1296 $this->mName
= $row->user_name
;
1297 $this->mFrom
= 'name';
1298 $this->setItemLoaded( 'name' );
1303 if ( isset( $row->user_real_name
) ) {
1304 $this->mRealName
= $row->user_real_name
;
1305 $this->setItemLoaded( 'realname' );
1310 if ( isset( $row->user_id
) ) {
1311 $this->mId
= intval( $row->user_id
);
1312 $this->mFrom
= 'id';
1313 $this->setItemLoaded( 'id' );
1318 if ( isset( $row->user_id
) && isset( $row->user_name
) ) {
1319 self
::$idCacheByName[$row->user_name
] = $row->user_id
;
1322 if ( isset( $row->user_editcount
) ) {
1323 $this->mEditCount
= $row->user_editcount
;
1328 if ( isset( $row->user_touched
) ) {
1329 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1334 if ( isset( $row->user_token
) ) {
1335 // The definition for the column is binary(32), so trim the NULs
1336 // that appends. The previous definition was char(32), so trim
1338 $this->mToken
= rtrim( $row->user_token
, " \0" );
1339 if ( $this->mToken
=== '' ) {
1340 $this->mToken
= null;
1346 if ( isset( $row->user_email
) ) {
1347 $this->mEmail
= $row->user_email
;
1348 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1349 $this->mEmailToken
= $row->user_email_token
;
1350 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1351 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1357 $this->mLoadedItems
= true;
1360 if ( is_array( $data ) ) {
1361 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1362 if ( !count( $data['user_groups'] ) ) {
1363 $this->mGroupMemberships
= [];
1365 $firstGroup = reset( $data['user_groups'] );
1366 if ( is_array( $firstGroup ) ||
is_object( $firstGroup ) ) {
1367 $this->mGroupMemberships
= [];
1368 foreach ( $data['user_groups'] as $row ) {
1369 $ugm = UserGroupMembership
::newFromRow( (object)$row );
1370 $this->mGroupMemberships
[$ugm->getGroup()] = $ugm;
1375 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1376 $this->loadOptions( $data['user_properties'] );
1382 * Load the data for this user object from another user object.
1386 protected function loadFromUserObject( $user ) {
1388 foreach ( self
::$mCacheVars as $var ) {
1389 $this->$var = $user->$var;
1394 * Load the groups from the database if they aren't already loaded.
1396 private function loadGroups() {
1397 if ( is_null( $this->mGroupMemberships
) ) {
1398 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
1399 ?
wfGetDB( DB_MASTER
)
1400 : wfGetDB( DB_REPLICA
);
1401 $this->mGroupMemberships
= UserGroupMembership
::getMembershipsForUser(
1407 * Add the user to the group if he/she meets given criteria.
1409 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1410 * possible to remove manually via Special:UserRights. In such case it
1411 * will not be re-added automatically. The user will also not lose the
1412 * group if they no longer meet the criteria.
1414 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1416 * @return array Array of groups the user has been promoted to.
1418 * @see $wgAutopromoteOnce
1420 public function addAutopromoteOnceGroups( $event ) {
1421 global $wgAutopromoteOnceLogInRC;
1423 if ( wfReadOnly() ||
!$this->getId() ) {
1427 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1428 if ( !count( $toPromote ) ) {
1432 if ( !$this->checkAndSetTouched() ) {
1433 return []; // raced out (bug T48834)
1436 $oldGroups = $this->getGroups(); // previous groups
1437 foreach ( $toPromote as $group ) {
1438 $this->addGroup( $group );
1440 // update groups in external authentication database
1441 Hooks
::run( 'UserGroupsChanged', [ $this, $toPromote, [], false, false ] );
1442 AuthManager
::callLegacyAuthPlugin( 'updateExternalDBGroups', [ $this, $toPromote ] );
1444 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1446 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1447 $logEntry->setPerformer( $this );
1448 $logEntry->setTarget( $this->getUserPage() );
1449 $logEntry->setParameters( [
1450 '4::oldgroups' => $oldGroups,
1451 '5::newgroups' => $newGroups,
1453 $logid = $logEntry->insert();
1454 if ( $wgAutopromoteOnceLogInRC ) {
1455 $logEntry->publish( $logid );
1462 * Builds update conditions. Additional conditions may be added to $conditions to
1463 * protected against race conditions using a compare-and-set (CAS) mechanism
1464 * based on comparing $this->mTouched with the user_touched field.
1466 * @param Database $db
1467 * @param array $conditions WHERE conditions for use with Database::update
1468 * @return array WHERE conditions for use with Database::update
1470 protected function makeUpdateConditions( Database
$db, array $conditions ) {
1471 if ( $this->mTouched
) {
1472 // CAS check: only update if the row wasn't changed sicne it was loaded.
1473 $conditions['user_touched'] = $db->timestamp( $this->mTouched
);
1480 * Bump user_touched if it didn't change since this object was loaded
1482 * On success, the mTouched field is updated.
1483 * The user serialization cache is always cleared.
1485 * @return bool Whether user_touched was actually updated
1488 protected function checkAndSetTouched() {
1491 if ( !$this->mId
) {
1492 return false; // anon
1495 // Get a new user_touched that is higher than the old one
1496 $newTouched = $this->newTouchedTimestamp();
1498 $dbw = wfGetDB( DB_MASTER
);
1499 $dbw->update( 'user',
1500 [ 'user_touched' => $dbw->timestamp( $newTouched ) ],
1501 $this->makeUpdateConditions( $dbw, [
1502 'user_id' => $this->mId
,
1506 $success = ( $dbw->affectedRows() > 0 );
1509 $this->mTouched
= $newTouched;
1510 $this->clearSharedCache();
1512 // Clears on failure too since that is desired if the cache is stale
1513 $this->clearSharedCache( 'refresh' );
1520 * Clear various cached data stored in this object. The cache of the user table
1521 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1523 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1524 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1526 public function clearInstanceCache( $reloadFrom = false ) {
1527 $this->mNewtalk
= -1;
1528 $this->mDatePreference
= null;
1529 $this->mBlockedby
= -1; # Unset
1530 $this->mHash
= false;
1531 $this->mRights
= null;
1532 $this->mEffectiveGroups
= null;
1533 $this->mImplicitGroups
= null;
1534 $this->mGroupMemberships
= null;
1535 $this->mOptions
= null;
1536 $this->mOptionsLoaded
= false;
1537 $this->mEditCount
= null;
1539 if ( $reloadFrom ) {
1540 $this->mLoadedItems
= [];
1541 $this->mFrom
= $reloadFrom;
1546 * Combine the language default options with any site-specific options
1547 * and add the default language variants.
1549 * @return array Array of String options
1551 public static function getDefaultOptions() {
1552 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1554 static $defOpt = null;
1555 static $defOptLang = null;
1557 if ( $defOpt !== null && $defOptLang === $wgContLang->getCode() ) {
1558 // $wgContLang does not change (and should not change) mid-request,
1559 // but the unit tests change it anyway, and expect this method to
1560 // return values relevant to the current $wgContLang.
1564 $defOpt = $wgDefaultUserOptions;
1565 // Default language setting
1566 $defOptLang = $wgContLang->getCode();
1567 $defOpt['language'] = $defOptLang;
1568 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1569 $defOpt[$langCode == $wgContLang->getCode() ?
'variant' : "variant-$langCode"] = $langCode;
1572 // NOTE: don't use SearchEngineConfig::getSearchableNamespaces here,
1573 // since extensions may change the set of searchable namespaces depending
1574 // on user groups/permissions.
1575 foreach ( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
1576 $defOpt['searchNs' . $nsnum] = (boolean
)$val;
1578 $defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1580 Hooks
::run( 'UserGetDefaultOptions', [ &$defOpt ] );
1586 * Get a given default option value.
1588 * @param string $opt Name of option to retrieve
1589 * @return string Default option value
1591 public static function getDefaultOption( $opt ) {
1592 $defOpts = self
::getDefaultOptions();
1593 if ( isset( $defOpts[$opt] ) ) {
1594 return $defOpts[$opt];
1601 * Get blocking information
1602 * @param bool $bFromSlave Whether to check the replica DB first.
1603 * To improve performance, non-critical checks are done against replica DBs.
1604 * Check when actually saving should be done against master.
1606 private function getBlockedStatus( $bFromSlave = true ) {
1607 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff, $wgSoftBlockRanges;
1609 if ( -1 != $this->mBlockedby
) {
1613 wfDebug( __METHOD__
. ": checking...\n" );
1615 // Initialize data...
1616 // Otherwise something ends up stomping on $this->mBlockedby when
1617 // things get lazy-loaded later, causing false positive block hits
1618 // due to -1 !== 0. Probably session-related... Nothing should be
1619 // overwriting mBlockedby, surely?
1622 # We only need to worry about passing the IP address to the Block generator if the
1623 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1624 # know which IP address they're actually coming from
1626 if ( !$this->isAllowed( 'ipblock-exempt' ) ) {
1627 // $wgUser->getName() only works after the end of Setup.php. Until
1628 // then, assume it's a logged-out user.
1629 $globalUserName = $wgUser->isSafeToLoad()
1630 ?
$wgUser->getName()
1631 : IP
::sanitizeIP( $wgUser->getRequest()->getIP() );
1632 if ( $this->getName() === $globalUserName ) {
1633 $ip = $this->getRequest()->getIP();
1638 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1640 // If no block has been found, check for a cookie indicating that the user is blocked.
1641 $blockCookieVal = (int)$this->getRequest()->getCookie( 'BlockID' );
1642 if ( !$block instanceof Block
&& $blockCookieVal > 0 ) {
1643 // Load the Block from the ID in the cookie.
1644 $tmpBlock = Block
::newFromID( $blockCookieVal );
1645 if ( $tmpBlock instanceof Block
) {
1646 // Check the validity of the block.
1647 $blockIsValid = $tmpBlock->getType() == Block
::TYPE_USER
1648 && !$tmpBlock->isExpired()
1649 && $tmpBlock->isAutoblocking();
1650 $config = RequestContext
::getMain()->getConfig();
1651 $useBlockCookie = ( $config->get( 'CookieSetOnAutoblock' ) === true );
1652 if ( $blockIsValid && $useBlockCookie ) {
1655 $this->blockTrigger
= 'cookie-block';
1657 // If the block is not valid, clear the block cookie (but don't delete it,
1658 // because it needs to be cleared from LocalStorage as well and an empty string
1659 // value is checked for in the mediawiki.user.blockcookie module).
1660 $tmpBlock->setCookie( $this->getRequest()->response(), true );
1666 if ( !$block instanceof Block
&& $ip !== null && !in_array( $ip, $wgProxyWhitelist ) ) {
1668 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1669 $block = new Block( [
1670 'byText' => wfMessage( 'proxyblocker' )->text(),
1671 'reason' => wfMessage( 'proxyblockreason' )->text(),
1673 'systemBlock' => 'proxy',
1675 $this->blockTrigger
= 'proxy-block';
1676 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1677 $block = new Block( [
1678 'byText' => wfMessage( 'sorbs' )->text(),
1679 'reason' => wfMessage( 'sorbsreason' )->text(),
1681 'systemBlock' => 'dnsbl',
1683 $this->blockTrigger
= 'openproxy-block';
1687 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1688 if ( !$block instanceof Block
1689 && $wgApplyIpBlocksToXff
1691 && !in_array( $ip, $wgProxyWhitelist )
1693 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1694 $xff = array_map( 'trim', explode( ',', $xff ) );
1695 $xff = array_diff( $xff, [ $ip ] );
1696 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1697 $block = Block
::chooseBlock( $xffblocks, $xff );
1698 if ( $block instanceof Block
) {
1699 # Mangle the reason to alert the user that the block
1700 # originated from matching the X-Forwarded-For header.
1701 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->text();
1702 $this->blockTrigger
= 'xff-block';
1706 if ( !$block instanceof Block
1709 && IP
::isInRanges( $ip, $wgSoftBlockRanges )
1711 $block = new Block( [
1713 'byText' => 'MediaWiki default',
1714 'reason' => wfMessage( 'softblockrangesreason', $ip )->text(),
1716 'systemBlock' => 'wgSoftBlockRanges',
1718 $this->blockTrigger
= 'config-block';
1721 if ( $block instanceof Block
) {
1722 wfDebug( __METHOD__
. ": Found block.\n" );
1723 $this->mBlock
= $block;
1724 $this->mBlockedby
= $block->getByName();
1725 $this->mBlockreason
= $block->mReason
;
1726 $this->mHideName
= $block->mHideName
;
1727 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1729 $this->mBlockedby
= '';
1730 $this->mHideName
= 0;
1731 $this->mAllowUsertalk
= false;
1732 $this->blockTrigger
= false;
1735 // Avoid PHP 7.1 warning of passing $this by reference
1738 Hooks
::run( 'GetBlockedStatus', [ &$user ] );
1742 * Whether the given IP is in a DNS blacklist.
1744 * @param string $ip IP to check
1745 * @param bool $checkWhitelist Whether to check the whitelist first
1746 * @return bool True if blacklisted.
1748 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1749 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1751 if ( !$wgEnableDnsBlacklist ) {
1755 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1759 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1763 * Whether the given IP is in a given DNS blacklist.
1765 * @param string $ip IP to check
1766 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1767 * @return bool True if blacklisted.
1769 public function inDnsBlacklist( $ip, $bases ) {
1771 // @todo FIXME: IPv6 ??? (https://bugs.php.net/bug.php?id=33170)
1772 if ( IP
::isIPv4( $ip ) ) {
1773 // Reverse IP, bug 21255
1774 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1776 foreach ( (array)$bases as $base ) {
1778 // If we have an access key, use that too (ProjectHoneypot, etc.)
1780 if ( is_array( $base ) ) {
1781 if ( count( $base ) >= 2 ) {
1782 // Access key is 1, base URL is 0
1783 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1785 $host = "$ipReversed.{$base[0]}";
1787 $basename = $base[0];
1789 $host = "$ipReversed.$base";
1793 $ipList = gethostbynamel( $host );
1796 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
1800 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
1809 * Check if an IP address is in the local proxy list
1815 public static function isLocallyBlockedProxy( $ip ) {
1816 global $wgProxyList;
1818 if ( !$wgProxyList ) {
1822 if ( !is_array( $wgProxyList ) ) {
1823 // Load values from the specified file
1824 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1827 if ( is_array( $wgProxyList ) ) {
1829 // Look for IP as value
1830 array_search( $ip, $wgProxyList ) !== false ||
1831 // Look for IP as key (for backwards-compatility)
1832 array_key_exists( $ip, $wgProxyList )
1842 * Is this user subject to rate limiting?
1844 * @return bool True if rate limited
1846 public function isPingLimitable() {
1847 global $wgRateLimitsExcludedIPs;
1848 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1849 // No other good way currently to disable rate limits
1850 // for specific IPs. :P
1851 // But this is a crappy hack and should die.
1854 return !$this->isAllowed( 'noratelimit' );
1858 * Primitive rate limits: enforce maximum actions per time period
1859 * to put a brake on flooding.
1861 * The method generates both a generic profiling point and a per action one
1862 * (suffix being "-$action".
1864 * @note When using a shared cache like memcached, IP-address
1865 * last-hit counters will be shared across wikis.
1867 * @param string $action Action to enforce; 'edit' if unspecified
1868 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1869 * @return bool True if a rate limiter was tripped
1871 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1872 // Avoid PHP 7.1 warning of passing $this by reference
1874 // Call the 'PingLimiter' hook
1876 if ( !Hooks
::run( 'PingLimiter', [ &$user, $action, &$result, $incrBy ] ) ) {
1880 global $wgRateLimits;
1881 if ( !isset( $wgRateLimits[$action] ) ) {
1885 $limits = array_merge(
1886 [ '&can-bypass' => true ],
1887 $wgRateLimits[$action]
1890 // Some groups shouldn't trigger the ping limiter, ever
1891 if ( $limits['&can-bypass'] && !$this->isPingLimitable() ) {
1896 $id = $this->getId();
1898 $isNewbie = $this->isNewbie();
1902 if ( isset( $limits['anon'] ) ) {
1903 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1906 // limits for logged-in users
1907 if ( isset( $limits['user'] ) ) {
1908 $userLimit = $limits['user'];
1910 // limits for newbie logged-in users
1911 if ( $isNewbie && isset( $limits['newbie'] ) ) {
1912 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1916 // limits for anons and for newbie logged-in users
1919 if ( isset( $limits['ip'] ) ) {
1920 $ip = $this->getRequest()->getIP();
1921 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1923 // subnet-based limits
1924 if ( isset( $limits['subnet'] ) ) {
1925 $ip = $this->getRequest()->getIP();
1926 $subnet = IP
::getSubnet( $ip );
1927 if ( $subnet !== false ) {
1928 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1933 // Check for group-specific permissions
1934 // If more than one group applies, use the group with the highest limit ratio (max/period)
1935 foreach ( $this->getGroups() as $group ) {
1936 if ( isset( $limits[$group] ) ) {
1937 if ( $userLimit === false
1938 ||
$limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1940 $userLimit = $limits[$group];
1945 // Set the user limit key
1946 if ( $userLimit !== false ) {
1947 list( $max, $period ) = $userLimit;
1948 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
1949 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1952 // ip-based limits for all ping-limitable users
1953 if ( isset( $limits['ip-all'] ) ) {
1954 $ip = $this->getRequest()->getIP();
1955 // ignore if user limit is more permissive
1956 if ( $isNewbie ||
$userLimit === false
1957 ||
$limits['ip-all'][0] / $limits['ip-all'][1] > $userLimit[0] / $userLimit[1] ) {
1958 $keys["mediawiki:limiter:$action:ip-all:$ip"] = $limits['ip-all'];
1962 // subnet-based limits for all ping-limitable users
1963 if ( isset( $limits['subnet-all'] ) ) {
1964 $ip = $this->getRequest()->getIP();
1965 $subnet = IP
::getSubnet( $ip );
1966 if ( $subnet !== false ) {
1967 // ignore if user limit is more permissive
1968 if ( $isNewbie ||
$userLimit === false
1969 ||
$limits['ip-all'][0] / $limits['ip-all'][1]
1970 > $userLimit[0] / $userLimit[1] ) {
1971 $keys["mediawiki:limiter:$action:subnet-all:$subnet"] = $limits['subnet-all'];
1976 $cache = ObjectCache
::getLocalClusterInstance();
1979 foreach ( $keys as $key => $limit ) {
1980 list( $max, $period ) = $limit;
1981 $summary = "(limit $max in {$period}s)";
1982 $count = $cache->get( $key );
1985 if ( $count >= $max ) {
1986 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1987 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1990 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1993 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1994 if ( $incrBy > 0 ) {
1995 $cache->add( $key, 0, intval( $period ) ); // first ping
1998 if ( $incrBy > 0 ) {
1999 $cache->incr( $key, $incrBy );
2007 * Check if user is blocked
2009 * @param bool $bFromSlave Whether to check the replica DB instead of
2010 * the master. Hacked from false due to horrible probs on site.
2011 * @return bool True if blocked, false otherwise
2013 public function isBlocked( $bFromSlave = true ) {
2014 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
2018 * Get the block affecting the user, or null if the user is not blocked
2020 * @param bool $bFromSlave Whether to check the replica DB instead of the master
2021 * @return Block|null
2023 public function getBlock( $bFromSlave = true ) {
2024 $this->getBlockedStatus( $bFromSlave );
2025 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
2029 * Check if user is blocked from editing a particular article
2031 * @param Title $title Title to check
2032 * @param bool $bFromSlave Whether to check the replica DB instead of the master
2035 public function isBlockedFrom( $title, $bFromSlave = false ) {
2036 global $wgBlockAllowsUTEdit;
2038 $blocked = $this->isBlocked( $bFromSlave );
2039 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
2040 // If a user's name is suppressed, they cannot make edits anywhere
2041 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName()
2042 && $title->getNamespace() == NS_USER_TALK
) {
2044 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
2047 Hooks
::run( 'UserIsBlockedFrom', [ $this, $title, &$blocked, &$allowUsertalk ] );
2053 * If user is blocked, return the name of the user who placed the block
2054 * @return string Name of blocker
2056 public function blockedBy() {
2057 $this->getBlockedStatus();
2058 return $this->mBlockedby
;
2062 * If user is blocked, return the specified reason for the block
2063 * @return string Blocking reason
2065 public function blockedFor() {
2066 $this->getBlockedStatus();
2067 return $this->mBlockreason
;
2071 * If user is blocked, return the ID for the block
2072 * @return int Block ID
2074 public function getBlockId() {
2075 $this->getBlockedStatus();
2076 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
2080 * Check if user is blocked on all wikis.
2081 * Do not use for actual edit permission checks!
2082 * This is intended for quick UI checks.
2084 * @param string $ip IP address, uses current client if none given
2085 * @return bool True if blocked, false otherwise
2087 public function isBlockedGlobally( $ip = '' ) {
2088 return $this->getGlobalBlock( $ip ) instanceof Block
;
2092 * Check if user is blocked on all wikis.
2093 * Do not use for actual edit permission checks!
2094 * This is intended for quick UI checks.
2096 * @param string $ip IP address, uses current client if none given
2097 * @return Block|null Block object if blocked, null otherwise
2098 * @throws FatalError
2099 * @throws MWException
2101 public function getGlobalBlock( $ip = '' ) {
2102 if ( $this->mGlobalBlock
!== null ) {
2103 return $this->mGlobalBlock ?
: null;
2105 // User is already an IP?
2106 if ( IP
::isIPAddress( $this->getName() ) ) {
2107 $ip = $this->getName();
2109 $ip = $this->getRequest()->getIP();
2111 // Avoid PHP 7.1 warning of passing $this by reference
2115 Hooks
::run( 'UserIsBlockedGlobally', [ &$user, $ip, &$blocked, &$block ] );
2117 if ( $blocked && $block === null ) {
2118 // back-compat: UserIsBlockedGlobally didn't have $block param first
2119 $block = new Block( [
2121 'systemBlock' => 'global-block'
2125 $this->mGlobalBlock
= $blocked ?
$block : false;
2126 return $this->mGlobalBlock ?
: null;
2130 * Check if user account is locked
2132 * @return bool True if locked, false otherwise
2134 public function isLocked() {
2135 if ( $this->mLocked
!== null ) {
2136 return $this->mLocked
;
2138 // Avoid PHP 7.1 warning of passing $this by reference
2140 $authUser = AuthManager
::callLegacyAuthPlugin( 'getUserInstance', [ &$user ], null );
2141 $this->mLocked
= $authUser && $authUser->isLocked();
2142 Hooks
::run( 'UserIsLocked', [ $this, &$this->mLocked
] );
2143 return $this->mLocked
;
2147 * Check if user account is hidden
2149 * @return bool True if hidden, false otherwise
2151 public function isHidden() {
2152 if ( $this->mHideName
!== null ) {
2153 return $this->mHideName
;
2155 $this->getBlockedStatus();
2156 if ( !$this->mHideName
) {
2157 // Avoid PHP 7.1 warning of passing $this by reference
2159 $authUser = AuthManager
::callLegacyAuthPlugin( 'getUserInstance', [ &$user ], null );
2160 $this->mHideName
= $authUser && $authUser->isHidden();
2161 Hooks
::run( 'UserIsHidden', [ $this, &$this->mHideName
] );
2163 return $this->mHideName
;
2167 * Get the user's ID.
2168 * @return int The user's ID; 0 if the user is anonymous or nonexistent
2170 public function getId() {
2171 if ( $this->mId
=== null && $this->mName
!== null && User
::isIP( $this->mName
) ) {
2172 // Special case, we know the user is anonymous
2174 } elseif ( !$this->isItemLoaded( 'id' ) ) {
2175 // Don't load if this was initialized from an ID
2179 return (int)$this->mId
;
2183 * Set the user and reload all fields according to a given ID
2184 * @param int $v User ID to reload
2186 public function setId( $v ) {
2188 $this->clearInstanceCache( 'id' );
2192 * Get the user name, or the IP of an anonymous user
2193 * @return string User's name or IP address
2195 public function getName() {
2196 if ( $this->isItemLoaded( 'name', 'only' ) ) {
2197 // Special case optimisation
2198 return $this->mName
;
2201 if ( $this->mName
=== false ) {
2203 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
2205 return $this->mName
;
2210 * Set the user name.
2212 * This does not reload fields from the database according to the given
2213 * name. Rather, it is used to create a temporary "nonexistent user" for
2214 * later addition to the database. It can also be used to set the IP
2215 * address for an anonymous user to something other than the current
2218 * @note User::newFromName() has roughly the same function, when the named user
2220 * @param string $str New user name to set
2222 public function setName( $str ) {
2224 $this->mName
= $str;
2228 * Get the user's name escaped by underscores.
2229 * @return string Username escaped by underscores.
2231 public function getTitleKey() {
2232 return str_replace( ' ', '_', $this->getName() );
2236 * Check if the user has new messages.
2237 * @return bool True if the user has new messages
2239 public function getNewtalk() {
2242 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2243 if ( $this->mNewtalk
=== -1 ) {
2244 $this->mNewtalk
= false; # reset talk page status
2246 // Check memcached separately for anons, who have no
2247 // entire User object stored in there.
2248 if ( !$this->mId
) {
2249 global $wgDisableAnonTalk;
2250 if ( $wgDisableAnonTalk ) {
2251 // Anon newtalk disabled by configuration.
2252 $this->mNewtalk
= false;
2254 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
2257 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2261 return (bool)$this->mNewtalk
;
2265 * Return the data needed to construct links for new talk page message
2266 * alerts. If there are new messages, this will return an associative array
2267 * with the following data:
2268 * wiki: The database name of the wiki
2269 * link: Root-relative link to the user's talk page
2270 * rev: The last talk page revision that the user has seen or null. This
2271 * is useful for building diff links.
2272 * If there are no new messages, it returns an empty array.
2273 * @note This function was designed to accomodate multiple talk pages, but
2274 * currently only returns a single link and revision.
2277 public function getNewMessageLinks() {
2278 // Avoid PHP 7.1 warning of passing $this by reference
2281 if ( !Hooks
::run( 'UserRetrieveNewTalks', [ &$user, &$talks ] ) ) {
2283 } elseif ( !$this->getNewtalk() ) {
2286 $utp = $this->getTalkPage();
2287 $dbr = wfGetDB( DB_REPLICA
);
2288 // Get the "last viewed rev" timestamp from the oldest message notification
2289 $timestamp = $dbr->selectField( 'user_newtalk',
2290 'MIN(user_last_timestamp)',
2291 $this->isAnon() ?
[ 'user_ip' => $this->getName() ] : [ 'user_id' => $this->getId() ],
2293 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2294 return [ [ 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ] ];
2298 * Get the revision ID for the last talk page revision viewed by the talk
2300 * @return int|null Revision ID or null
2302 public function getNewMessageRevisionId() {
2303 $newMessageRevisionId = null;
2304 $newMessageLinks = $this->getNewMessageLinks();
2305 if ( $newMessageLinks ) {
2306 // Note: getNewMessageLinks() never returns more than a single link
2307 // and it is always for the same wiki, but we double-check here in
2308 // case that changes some time in the future.
2309 if ( count( $newMessageLinks ) === 1
2310 && $newMessageLinks[0]['wiki'] === wfWikiID()
2311 && $newMessageLinks[0]['rev']
2313 /** @var Revision $newMessageRevision */
2314 $newMessageRevision = $newMessageLinks[0]['rev'];
2315 $newMessageRevisionId = $newMessageRevision->getId();
2318 return $newMessageRevisionId;
2322 * Internal uncached check for new messages
2325 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2326 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2327 * @return bool True if the user has new messages
2329 protected function checkNewtalk( $field, $id ) {
2330 $dbr = wfGetDB( DB_REPLICA
);
2332 $ok = $dbr->selectField( 'user_newtalk', $field, [ $field => $id ], __METHOD__
);
2334 return $ok !== false;
2338 * Add or update the new messages flag
2339 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2340 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2341 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2342 * @return bool True if successful, false otherwise
2344 protected function updateNewtalk( $field, $id, $curRev = null ) {
2345 // Get timestamp of the talk page revision prior to the current one
2346 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2347 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2348 // Mark the user as having new messages since this revision
2349 $dbw = wfGetDB( DB_MASTER
);
2350 $dbw->insert( 'user_newtalk',
2351 [ $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ],
2354 if ( $dbw->affectedRows() ) {
2355 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2358 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2364 * Clear the new messages flag for the given user
2365 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2366 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2367 * @return bool True if successful, false otherwise
2369 protected function deleteNewtalk( $field, $id ) {
2370 $dbw = wfGetDB( DB_MASTER
);
2371 $dbw->delete( 'user_newtalk',
2374 if ( $dbw->affectedRows() ) {
2375 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2378 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2384 * Update the 'You have new messages!' status.
2385 * @param bool $val Whether the user has new messages
2386 * @param Revision $curRev New, as yet unseen revision of the user talk
2387 * page. Ignored if null or !$val.
2389 public function setNewtalk( $val, $curRev = null ) {
2390 if ( wfReadOnly() ) {
2395 $this->mNewtalk
= $val;
2397 if ( $this->isAnon() ) {
2399 $id = $this->getName();
2402 $id = $this->getId();
2406 $changed = $this->updateNewtalk( $field, $id, $curRev );
2408 $changed = $this->deleteNewtalk( $field, $id );
2412 $this->invalidateCache();
2417 * Generate a current or new-future timestamp to be stored in the
2418 * user_touched field when we update things.
2419 * @return string Timestamp in TS_MW format
2421 private function newTouchedTimestamp() {
2422 global $wgClockSkewFudge;
2424 $time = wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2425 if ( $this->mTouched
&& $time <= $this->mTouched
) {
2426 $time = wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $this->mTouched
) +
1 );
2433 * Clear user data from memcached
2435 * Use after applying updates to the database; caller's
2436 * responsibility to update user_touched if appropriate.
2438 * Called implicitly from invalidateCache() and saveSettings().
2440 * @param string $mode Use 'refresh' to clear now; otherwise before DB commit
2442 public function clearSharedCache( $mode = 'changed' ) {
2443 if ( !$this->getId() ) {
2447 $cache = ObjectCache
::getMainWANInstance();
2448 $key = $this->getCacheKey( $cache );
2449 if ( $mode === 'refresh' ) {
2450 $cache->delete( $key, 1 );
2452 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle(
2453 function() use ( $cache, $key ) {
2454 $cache->delete( $key );
2462 * Immediately touch the user data cache for this account
2464 * Calls touch() and removes account data from memcached
2466 public function invalidateCache() {
2468 $this->clearSharedCache();
2472 * Update the "touched" timestamp for the user
2474 * This is useful on various login/logout events when making sure that
2475 * a browser or proxy that has multiple tenants does not suffer cache
2476 * pollution where the new user sees the old users content. The value
2477 * of getTouched() is checked when determining 304 vs 200 responses.
2478 * Unlike invalidateCache(), this preserves the User object cache and
2479 * avoids database writes.
2483 public function touch() {
2484 $id = $this->getId();
2486 $key = wfMemcKey( 'user-quicktouched', 'id', $id );
2487 ObjectCache
::getMainWANInstance()->touchCheckKey( $key );
2488 $this->mQuickTouched
= null;
2493 * Validate the cache for this account.
2494 * @param string $timestamp A timestamp in TS_MW format
2497 public function validateCache( $timestamp ) {
2498 return ( $timestamp >= $this->getTouched() );
2502 * Get the user touched timestamp
2504 * Use this value only to validate caches via inequalities
2505 * such as in the case of HTTP If-Modified-Since response logic
2507 * @return string TS_MW Timestamp
2509 public function getTouched() {
2513 if ( $this->mQuickTouched
=== null ) {
2514 $key = wfMemcKey( 'user-quicktouched', 'id', $this->mId
);
2515 $cache = ObjectCache
::getMainWANInstance();
2517 $this->mQuickTouched
= wfTimestamp( TS_MW
, $cache->getCheckKeyTime( $key ) );
2520 return max( $this->mTouched
, $this->mQuickTouched
);
2523 return $this->mTouched
;
2527 * Get the user_touched timestamp field (time of last DB updates)
2528 * @return string TS_MW Timestamp
2531 public function getDBTouched() {
2534 return $this->mTouched
;
2538 * Set the password and reset the random token.
2539 * Calls through to authentication plugin if necessary;
2540 * will have no effect if the auth plugin refuses to
2541 * pass the change through or if the legal password
2544 * As a special case, setting the password to null
2545 * wipes it, so the account cannot be logged in until
2546 * a new password is set, for instance via e-mail.
2548 * @deprecated since 1.27, use AuthManager instead
2549 * @param string $str New password to set
2550 * @throws PasswordError On failure
2553 public function setPassword( $str ) {
2554 return $this->setPasswordInternal( $str );
2558 * Set the password and reset the random token unconditionally.
2560 * @deprecated since 1.27, use AuthManager instead
2561 * @param string|null $str New password to set or null to set an invalid
2562 * password hash meaning that the user will not be able to log in
2563 * through the web interface.
2565 public function setInternalPassword( $str ) {
2566 $this->setPasswordInternal( $str );
2570 * Actually set the password and such
2571 * @since 1.27 cannot set a password for a user not in the database
2572 * @param string|null $str New password to set or null to set an invalid
2573 * password hash meaning that the user will not be able to log in
2574 * through the web interface.
2575 * @return bool Success
2577 private function setPasswordInternal( $str ) {
2578 $manager = AuthManager
::singleton();
2580 // If the user doesn't exist yet, fail
2581 if ( !$manager->userExists( $this->getName() ) ) {
2582 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2585 $status = $this->changeAuthenticationData( [
2586 'username' => $this->getName(),
2590 if ( !$status->isGood() ) {
2591 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
2592 ->info( __METHOD__
. ': Password change rejected: '
2593 . $status->getWikiText( null, null, 'en' ) );
2597 $this->setOption( 'watchlisttoken', false );
2598 SessionManager
::singleton()->invalidateSessionsForUser( $this );
2604 * Changes credentials of the user.
2606 * This is a convenience wrapper around AuthManager::changeAuthenticationData.
2607 * Note that this can return a status that isOK() but not isGood() on certain types of failures,
2608 * e.g. when no provider handled the change.
2610 * @param array $data A set of authentication data in fieldname => value format. This is the
2611 * same data you would pass the changeauthenticationdata API - 'username', 'password' etc.
2615 public function changeAuthenticationData( array $data ) {
2616 $manager = AuthManager
::singleton();
2617 $reqs = $manager->getAuthenticationRequests( AuthManager
::ACTION_CHANGE
, $this );
2618 $reqs = AuthenticationRequest
::loadRequestsFromSubmission( $reqs, $data );
2620 $status = Status
::newGood( 'ignored' );
2621 foreach ( $reqs as $req ) {
2622 $status->merge( $manager->allowsAuthenticationDataChange( $req ), true );
2624 if ( $status->getValue() === 'ignored' ) {
2625 $status->warning( 'authenticationdatachange-ignored' );
2628 if ( $status->isGood() ) {
2629 foreach ( $reqs as $req ) {
2630 $manager->changeAuthenticationData( $req );
2637 * Get the user's current token.
2638 * @param bool $forceCreation Force the generation of a new token if the
2639 * user doesn't have one (default=true for backwards compatibility).
2640 * @return string|null Token
2642 public function getToken( $forceCreation = true ) {
2643 global $wgAuthenticationTokenVersion;
2646 if ( !$this->mToken
&& $forceCreation ) {
2650 if ( !$this->mToken
) {
2651 // The user doesn't have a token, return null to indicate that.
2653 } elseif ( $this->mToken
=== self
::INVALID_TOKEN
) {
2654 // We return a random value here so existing token checks are very
2656 return MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2657 } elseif ( $wgAuthenticationTokenVersion === null ) {
2658 // $wgAuthenticationTokenVersion not in use, so return the raw secret
2659 return $this->mToken
;
2661 // $wgAuthenticationTokenVersion in use, so hmac it.
2662 $ret = MWCryptHash
::hmac( $wgAuthenticationTokenVersion, $this->mToken
, false );
2664 // The raw hash can be overly long. Shorten it up.
2665 $len = max( 32, self
::TOKEN_LENGTH
);
2666 if ( strlen( $ret ) < $len ) {
2667 // Should never happen, even md5 is 128 bits
2668 throw new \
UnexpectedValueException( 'Hmac returned less than 128 bits' );
2670 return substr( $ret, -$len );
2675 * Set the random token (used for persistent authentication)
2676 * Called from loadDefaults() among other places.
2678 * @param string|bool $token If specified, set the token to this value
2680 public function setToken( $token = false ) {
2682 if ( $this->mToken
=== self
::INVALID_TOKEN
) {
2683 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
2684 ->debug( __METHOD__
. ": Ignoring attempt to set token for system user \"$this\"" );
2685 } elseif ( !$token ) {
2686 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2688 $this->mToken
= $token;
2693 * Set the password for a password reminder or new account email
2695 * @deprecated Removed in 1.27. Use PasswordReset instead.
2696 * @param string $str New password to set or null to set an invalid
2697 * password hash meaning that the user will not be able to use it
2698 * @param bool $throttle If true, reset the throttle timestamp to the present
2700 public function setNewpassword( $str, $throttle = true ) {
2701 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2705 * Get the user's e-mail address
2706 * @return string User's email address
2708 public function getEmail() {
2710 Hooks
::run( 'UserGetEmail', [ $this, &$this->mEmail
] );
2711 return $this->mEmail
;
2715 * Get the timestamp of the user's e-mail authentication
2716 * @return string TS_MW timestamp
2718 public function getEmailAuthenticationTimestamp() {
2720 Hooks
::run( 'UserGetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
2721 return $this->mEmailAuthenticated
;
2725 * Set the user's e-mail address
2726 * @param string $str New e-mail address
2728 public function setEmail( $str ) {
2730 if ( $str == $this->mEmail
) {
2733 $this->invalidateEmail();
2734 $this->mEmail
= $str;
2735 Hooks
::run( 'UserSetEmail', [ $this, &$this->mEmail
] );
2739 * Set the user's e-mail address and a confirmation mail if needed.
2742 * @param string $str New e-mail address
2745 public function setEmailWithConfirmation( $str ) {
2746 global $wgEnableEmail, $wgEmailAuthentication;
2748 if ( !$wgEnableEmail ) {
2749 return Status
::newFatal( 'emaildisabled' );
2752 $oldaddr = $this->getEmail();
2753 if ( $str === $oldaddr ) {
2754 return Status
::newGood( true );
2757 $type = $oldaddr != '' ?
'changed' : 'set';
2758 $notificationResult = null;
2760 if ( $wgEmailAuthentication ) {
2761 // Send the user an email notifying the user of the change in registered
2762 // email address on their previous email address
2763 if ( $type == 'changed' ) {
2764 $change = $str != '' ?
'changed' : 'removed';
2765 $notificationResult = $this->sendMail(
2766 wfMessage( 'notificationemail_subject_' . $change )->text(),
2767 wfMessage( 'notificationemail_body_' . $change,
2768 $this->getRequest()->getIP(),
2775 $this->setEmail( $str );
2777 if ( $str !== '' && $wgEmailAuthentication ) {
2778 // Send a confirmation request to the new address if needed
2779 $result = $this->sendConfirmationMail( $type );
2781 if ( $notificationResult !== null ) {
2782 $result->merge( $notificationResult );
2785 if ( $result->isGood() ) {
2786 // Say to the caller that a confirmation and notification mail has been sent
2787 $result->value
= 'eauth';
2790 $result = Status
::newGood( true );
2797 * Get the user's real name
2798 * @return string User's real name
2800 public function getRealName() {
2801 if ( !$this->isItemLoaded( 'realname' ) ) {
2805 return $this->mRealName
;
2809 * Set the user's real name
2810 * @param string $str New real name
2812 public function setRealName( $str ) {
2814 $this->mRealName
= $str;
2818 * Get the user's current setting for a given option.
2820 * @param string $oname The option to check
2821 * @param string $defaultOverride A default value returned if the option does not exist
2822 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2823 * @return string|null User's current value for the option
2824 * @see getBoolOption()
2825 * @see getIntOption()
2827 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2828 global $wgHiddenPrefs;
2829 $this->loadOptions();
2831 # We want 'disabled' preferences to always behave as the default value for
2832 # users, even if they have set the option explicitly in their settings (ie they
2833 # set it, and then it was disabled removing their ability to change it). But
2834 # we don't want to erase the preferences in the database in case the preference
2835 # is re-enabled again. So don't touch $mOptions, just override the returned value
2836 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2837 return self
::getDefaultOption( $oname );
2840 if ( array_key_exists( $oname, $this->mOptions
) ) {
2841 return $this->mOptions
[$oname];
2843 return $defaultOverride;
2848 * Get all user's options
2850 * @param int $flags Bitwise combination of:
2851 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2852 * to the default value. (Since 1.25)
2855 public function getOptions( $flags = 0 ) {
2856 global $wgHiddenPrefs;
2857 $this->loadOptions();
2858 $options = $this->mOptions
;
2860 # We want 'disabled' preferences to always behave as the default value for
2861 # users, even if they have set the option explicitly in their settings (ie they
2862 # set it, and then it was disabled removing their ability to change it). But
2863 # we don't want to erase the preferences in the database in case the preference
2864 # is re-enabled again. So don't touch $mOptions, just override the returned value
2865 foreach ( $wgHiddenPrefs as $pref ) {
2866 $default = self
::getDefaultOption( $pref );
2867 if ( $default !== null ) {
2868 $options[$pref] = $default;
2872 if ( $flags & self
::GETOPTIONS_EXCLUDE_DEFAULTS
) {
2873 $options = array_diff_assoc( $options, self
::getDefaultOptions() );
2880 * Get the user's current setting for a given option, as a boolean value.
2882 * @param string $oname The option to check
2883 * @return bool User's current value for the option
2886 public function getBoolOption( $oname ) {
2887 return (bool)$this->getOption( $oname );
2891 * Get the user's current setting for a given option, as an integer value.
2893 * @param string $oname The option to check
2894 * @param int $defaultOverride A default value returned if the option does not exist
2895 * @return int User's current value for the option
2898 public function getIntOption( $oname, $defaultOverride = 0 ) {
2899 $val = $this->getOption( $oname );
2901 $val = $defaultOverride;
2903 return intval( $val );
2907 * Set the given option for a user.
2909 * You need to call saveSettings() to actually write to the database.
2911 * @param string $oname The option to set
2912 * @param mixed $val New value to set
2914 public function setOption( $oname, $val ) {
2915 $this->loadOptions();
2917 // Explicitly NULL values should refer to defaults
2918 if ( is_null( $val ) ) {
2919 $val = self
::getDefaultOption( $oname );
2922 $this->mOptions
[$oname] = $val;
2926 * Get a token stored in the preferences (like the watchlist one),
2927 * resetting it if it's empty (and saving changes).
2929 * @param string $oname The option name to retrieve the token from
2930 * @return string|bool User's current value for the option, or false if this option is disabled.
2931 * @see resetTokenFromOption()
2933 * @deprecated since 1.26 Applications should use the OAuth extension
2935 public function getTokenFromOption( $oname ) {
2936 global $wgHiddenPrefs;
2938 $id = $this->getId();
2939 if ( !$id ||
in_array( $oname, $wgHiddenPrefs ) ) {
2943 $token = $this->getOption( $oname );
2945 // Default to a value based on the user token to avoid space
2946 // wasted on storing tokens for all users. When this option
2947 // is set manually by the user, only then is it stored.
2948 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
2955 * Reset a token stored in the preferences (like the watchlist one).
2956 * *Does not* save user's preferences (similarly to setOption()).
2958 * @param string $oname The option name to reset the token in
2959 * @return string|bool New token value, or false if this option is disabled.
2960 * @see getTokenFromOption()
2963 public function resetTokenFromOption( $oname ) {
2964 global $wgHiddenPrefs;
2965 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2969 $token = MWCryptRand
::generateHex( 40 );
2970 $this->setOption( $oname, $token );
2975 * Return a list of the types of user options currently returned by
2976 * User::getOptionKinds().
2978 * Currently, the option kinds are:
2979 * - 'registered' - preferences which are registered in core MediaWiki or
2980 * by extensions using the UserGetDefaultOptions hook.
2981 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2982 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2983 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2984 * be used by user scripts.
2985 * - 'special' - "preferences" that are not accessible via User::getOptions
2986 * or User::setOptions.
2987 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2988 * These are usually legacy options, removed in newer versions.
2990 * The API (and possibly others) use this function to determine the possible
2991 * option types for validation purposes, so make sure to update this when a
2992 * new option kind is added.
2994 * @see User::getOptionKinds
2995 * @return array Option kinds
2997 public static function listOptionKinds() {
3000 'registered-multiselect',
3001 'registered-checkmatrix',
3009 * Return an associative array mapping preferences keys to the kind of a preference they're
3010 * used for. Different kinds are handled differently when setting or reading preferences.
3012 * See User::listOptionKinds for the list of valid option types that can be provided.
3014 * @see User::listOptionKinds
3015 * @param IContextSource $context
3016 * @param array $options Assoc. array with options keys to check as keys.
3017 * Defaults to $this->mOptions.
3018 * @return array The key => kind mapping data
3020 public function getOptionKinds( IContextSource
$context, $options = null ) {
3021 $this->loadOptions();
3022 if ( $options === null ) {
3023 $options = $this->mOptions
;
3026 $prefs = Preferences
::getPreferences( $this, $context );
3029 // Pull out the "special" options, so they don't get converted as
3030 // multiselect or checkmatrix.
3031 $specialOptions = array_fill_keys( Preferences
::getSaveBlacklist(), true );
3032 foreach ( $specialOptions as $name => $value ) {
3033 unset( $prefs[$name] );
3036 // Multiselect and checkmatrix options are stored in the database with
3037 // one key per option, each having a boolean value. Extract those keys.
3038 $multiselectOptions = [];
3039 foreach ( $prefs as $name => $info ) {
3040 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
3041 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
3042 $opts = HTMLFormField
::flattenOptions( $info['options'] );
3043 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
3045 foreach ( $opts as $value ) {
3046 $multiselectOptions["$prefix$value"] = true;
3049 unset( $prefs[$name] );
3052 $checkmatrixOptions = [];
3053 foreach ( $prefs as $name => $info ) {
3054 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
3055 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
3056 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
3057 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
3058 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
3060 foreach ( $columns as $column ) {
3061 foreach ( $rows as $row ) {
3062 $checkmatrixOptions["$prefix$column-$row"] = true;
3066 unset( $prefs[$name] );
3070 // $value is ignored
3071 foreach ( $options as $key => $value ) {
3072 if ( isset( $prefs[$key] ) ) {
3073 $mapping[$key] = 'registered';
3074 } elseif ( isset( $multiselectOptions[$key] ) ) {
3075 $mapping[$key] = 'registered-multiselect';
3076 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
3077 $mapping[$key] = 'registered-checkmatrix';
3078 } elseif ( isset( $specialOptions[$key] ) ) {
3079 $mapping[$key] = 'special';
3080 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
3081 $mapping[$key] = 'userjs';
3083 $mapping[$key] = 'unused';
3091 * Reset certain (or all) options to the site defaults
3093 * The optional parameter determines which kinds of preferences will be reset.
3094 * Supported values are everything that can be reported by getOptionKinds()
3095 * and 'all', which forces a reset of *all* preferences and overrides everything else.
3097 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
3098 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
3099 * for backwards-compatibility.
3100 * @param IContextSource|null $context Context source used when $resetKinds
3101 * does not contain 'all', passed to getOptionKinds().
3102 * Defaults to RequestContext::getMain() when null.
3104 public function resetOptions(
3105 $resetKinds = [ 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ],
3106 IContextSource
$context = null
3109 $defaultOptions = self
::getDefaultOptions();
3111 if ( !is_array( $resetKinds ) ) {
3112 $resetKinds = [ $resetKinds ];
3115 if ( in_array( 'all', $resetKinds ) ) {
3116 $newOptions = $defaultOptions;
3118 if ( $context === null ) {
3119 $context = RequestContext
::getMain();
3122 $optionKinds = $this->getOptionKinds( $context );
3123 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
3126 // Use default values for the options that should be deleted, and
3127 // copy old values for the ones that shouldn't.
3128 foreach ( $this->mOptions
as $key => $value ) {
3129 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
3130 if ( array_key_exists( $key, $defaultOptions ) ) {
3131 $newOptions[$key] = $defaultOptions[$key];
3134 $newOptions[$key] = $value;
3139 Hooks
::run( 'UserResetAllOptions', [ $this, &$newOptions, $this->mOptions
, $resetKinds ] );
3141 $this->mOptions
= $newOptions;
3142 $this->mOptionsLoaded
= true;
3146 * Get the user's preferred date format.
3147 * @return string User's preferred date format
3149 public function getDatePreference() {
3150 // Important migration for old data rows
3151 if ( is_null( $this->mDatePreference
) ) {
3153 $value = $this->getOption( 'date' );
3154 $map = $wgLang->getDatePreferenceMigrationMap();
3155 if ( isset( $map[$value] ) ) {
3156 $value = $map[$value];
3158 $this->mDatePreference
= $value;
3160 return $this->mDatePreference
;
3164 * Determine based on the wiki configuration and the user's options,
3165 * whether this user must be over HTTPS no matter what.
3169 public function requiresHTTPS() {
3170 global $wgSecureLogin;
3171 if ( !$wgSecureLogin ) {
3174 $https = $this->getBoolOption( 'prefershttps' );
3175 Hooks
::run( 'UserRequiresHTTPS', [ $this, &$https ] );
3177 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
3184 * Get the user preferred stub threshold
3188 public function getStubThreshold() {
3189 global $wgMaxArticleSize; # Maximum article size, in Kb
3190 $threshold = $this->getIntOption( 'stubthreshold' );
3191 if ( $threshold > $wgMaxArticleSize * 1024 ) {
3192 // If they have set an impossible value, disable the preference
3193 // so we can use the parser cache again.
3200 * Get the permissions this user has.
3201 * @return array Array of String permission names
3203 public function getRights() {
3204 if ( is_null( $this->mRights
) ) {
3205 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
3206 Hooks
::run( 'UserGetRights', [ $this, &$this->mRights
] );
3208 // Deny any rights denied by the user's session, unless this
3209 // endpoint has no sessions.
3210 if ( !defined( 'MW_NO_SESSION' ) ) {
3211 $allowedRights = $this->getRequest()->getSession()->getAllowedUserRights();
3212 if ( $allowedRights !== null ) {
3213 $this->mRights
= array_intersect( $this->mRights
, $allowedRights );
3217 // Force reindexation of rights when a hook has unset one of them
3218 $this->mRights
= array_values( array_unique( $this->mRights
) );
3220 // If block disables login, we should also remove any
3221 // extra rights blocked users might have, in case the
3222 // blocked user has a pre-existing session (T129738).
3223 // This is checked here for cases where people only call
3224 // $user->isAllowed(). It is also checked in Title::checkUserBlock()
3225 // to give a better error message in the common case.
3226 $config = RequestContext
::getMain()->getConfig();
3228 $this->isLoggedIn() &&
3229 $config->get( 'BlockDisablesLogin' ) &&
3233 $this->mRights
= array_intersect( $this->mRights
, $anon->getRights() );
3236 return $this->mRights
;
3240 * Get the list of explicit group memberships this user has.
3241 * The implicit * and user groups are not included.
3242 * @return array Array of String internal group names
3244 public function getGroups() {
3246 $this->loadGroups();
3247 return array_keys( $this->mGroupMemberships
);
3251 * Get the list of explicit group memberships this user has, stored as
3252 * UserGroupMembership objects. Implicit groups are not included.
3254 * @return array Associative array of (group name as string => UserGroupMembership object)
3257 public function getGroupMemberships() {
3259 $this->loadGroups();
3260 return $this->mGroupMemberships
;
3264 * Get the list of implicit group memberships this user has.
3265 * This includes all explicit groups, plus 'user' if logged in,
3266 * '*' for all accounts, and autopromoted groups
3267 * @param bool $recache Whether to avoid the cache
3268 * @return array Array of String internal group names
3270 public function getEffectiveGroups( $recache = false ) {
3271 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
3272 $this->mEffectiveGroups
= array_unique( array_merge(
3273 $this->getGroups(), // explicit groups
3274 $this->getAutomaticGroups( $recache ) // implicit groups
3276 // Avoid PHP 7.1 warning of passing $this by reference
3278 // Hook for additional groups
3279 Hooks
::run( 'UserEffectiveGroups', [ &$user, &$this->mEffectiveGroups
] );
3280 // Force reindexation of groups when a hook has unset one of them
3281 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
3283 return $this->mEffectiveGroups
;
3287 * Get the list of implicit group memberships this user has.
3288 * This includes 'user' if logged in, '*' for all accounts,
3289 * and autopromoted groups
3290 * @param bool $recache Whether to avoid the cache
3291 * @return array Array of String internal group names
3293 public function getAutomaticGroups( $recache = false ) {
3294 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
3295 $this->mImplicitGroups
= [ '*' ];
3296 if ( $this->getId() ) {
3297 $this->mImplicitGroups
[] = 'user';
3299 $this->mImplicitGroups
= array_unique( array_merge(
3300 $this->mImplicitGroups
,
3301 Autopromote
::getAutopromoteGroups( $this )
3305 // Assure data consistency with rights/groups,
3306 // as getEffectiveGroups() depends on this function
3307 $this->mEffectiveGroups
= null;
3310 return $this->mImplicitGroups
;
3314 * Returns the groups the user has belonged to.
3316 * The user may still belong to the returned groups. Compare with getGroups().
3318 * The function will not return groups the user had belonged to before MW 1.17
3320 * @return array Names of the groups the user has belonged to.
3322 public function getFormerGroups() {
3325 if ( is_null( $this->mFormerGroups
) ) {
3326 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3327 ?
wfGetDB( DB_MASTER
)
3328 : wfGetDB( DB_REPLICA
);
3329 $res = $db->select( 'user_former_groups',
3331 [ 'ufg_user' => $this->mId
],
3333 $this->mFormerGroups
= [];
3334 foreach ( $res as $row ) {
3335 $this->mFormerGroups
[] = $row->ufg_group
;
3339 return $this->mFormerGroups
;
3343 * Get the user's edit count.
3344 * @return int|null Null for anonymous users
3346 public function getEditCount() {
3347 if ( !$this->getId() ) {
3351 if ( $this->mEditCount
=== null ) {
3352 /* Populate the count, if it has not been populated yet */
3353 $dbr = wfGetDB( DB_REPLICA
);
3354 // check if the user_editcount field has been initialized
3355 $count = $dbr->selectField(
3356 'user', 'user_editcount',
3357 [ 'user_id' => $this->mId
],
3361 if ( $count === null ) {
3362 // it has not been initialized. do so.
3363 $count = $this->initEditCount();
3365 $this->mEditCount
= $count;
3367 return (int)$this->mEditCount
;
3371 * Add the user to the given group. This takes immediate effect.
3372 * If the user is already in the group, the expiry time will be updated to the new
3373 * expiry time. (If $expiry is omitted or null, the membership will be altered to
3376 * @param string $group Name of the group to add
3377 * @param string $expiry Optional expiry timestamp in any format acceptable to
3378 * wfTimestamp(), or null if the group assignment should not expire
3381 public function addGroup( $group, $expiry = null ) {
3383 $this->loadGroups();
3386 $expiry = wfTimestamp( TS_MW
, $expiry );
3389 if ( !Hooks
::run( 'UserAddGroup', [ $this, &$group, &$expiry ] ) ) {
3393 // create the new UserGroupMembership and put it in the DB
3394 $ugm = new UserGroupMembership( $this->mId
, $group, $expiry );
3395 if ( !$ugm->insert( true ) ) {
3399 $this->mGroupMemberships
[$group] = $ugm;
3401 // Refresh the groups caches, and clear the rights cache so it will be
3402 // refreshed on the next call to $this->getRights().
3403 $this->getEffectiveGroups( true );
3404 $this->mRights
= null;
3406 $this->invalidateCache();
3412 * Remove the user from the given group.
3413 * This takes immediate effect.
3414 * @param string $group Name of the group to remove
3417 public function removeGroup( $group ) {
3420 if ( !Hooks
::run( 'UserRemoveGroup', [ $this, &$group ] ) ) {
3424 $ugm = UserGroupMembership
::getMembership( $this->mId
, $group );
3425 // delete the membership entry
3426 if ( !$ugm ||
!$ugm->delete() ) {
3430 $this->loadGroups();
3431 unset( $this->mGroupMemberships
[$group] );
3433 // Refresh the groups caches, and clear the rights cache so it will be
3434 // refreshed on the next call to $this->getRights().
3435 $this->getEffectiveGroups( true );
3436 $this->mRights
= null;
3438 $this->invalidateCache();
3444 * Get whether the user is logged in
3447 public function isLoggedIn() {
3448 return $this->getId() != 0;
3452 * Get whether the user is anonymous
3455 public function isAnon() {
3456 return !$this->isLoggedIn();
3460 * @return bool Whether this user is flagged as being a bot role account
3463 public function isBot() {
3464 if ( in_array( 'bot', $this->getGroups() ) && $this->isAllowed( 'bot' ) ) {
3469 Hooks
::run( "UserIsBot", [ $this, &$isBot ] );
3475 * Check if user is allowed to access a feature / make an action
3477 * @param string ... Permissions to test
3478 * @return bool True if user is allowed to perform *any* of the given actions
3480 public function isAllowedAny() {
3481 $permissions = func_get_args();
3482 foreach ( $permissions as $permission ) {
3483 if ( $this->isAllowed( $permission ) ) {
3492 * @param string ... Permissions to test
3493 * @return bool True if the user is allowed to perform *all* of the given actions
3495 public function isAllowedAll() {
3496 $permissions = func_get_args();
3497 foreach ( $permissions as $permission ) {
3498 if ( !$this->isAllowed( $permission ) ) {
3506 * Internal mechanics of testing a permission
3507 * @param string $action
3510 public function isAllowed( $action = '' ) {
3511 if ( $action === '' ) {
3512 return true; // In the spirit of DWIM
3514 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3515 // by misconfiguration: 0 == 'foo'
3516 return in_array( $action, $this->getRights(), true );
3520 * Check whether to enable recent changes patrol features for this user
3521 * @return bool True or false
3523 public function useRCPatrol() {
3524 global $wgUseRCPatrol;
3525 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3529 * Check whether to enable new pages patrol features for this user
3530 * @return bool True or false
3532 public function useNPPatrol() {
3533 global $wgUseRCPatrol, $wgUseNPPatrol;
3535 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3536 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3541 * Check whether to enable new files patrol features for this user
3542 * @return bool True or false
3544 public function useFilePatrol() {
3545 global $wgUseRCPatrol, $wgUseFilePatrol;
3547 ( $wgUseRCPatrol ||
$wgUseFilePatrol )
3548 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3553 * Get the WebRequest object to use with this object
3555 * @return WebRequest
3557 public function getRequest() {
3558 if ( $this->mRequest
) {
3559 return $this->mRequest
;
3567 * Check the watched status of an article.
3568 * @since 1.22 $checkRights parameter added
3569 * @param Title $title Title of the article to look at
3570 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3571 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3574 public function isWatched( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3575 if ( $title->isWatchable() && ( !$checkRights ||
$this->isAllowed( 'viewmywatchlist' ) ) ) {
3576 return MediaWikiServices
::getInstance()->getWatchedItemStore()->isWatched( $this, $title );
3583 * @since 1.22 $checkRights parameter added
3584 * @param Title $title Title of the article to look at
3585 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3586 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3588 public function addWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3589 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3590 MediaWikiServices
::getInstance()->getWatchedItemStore()->addWatchBatchForUser(
3592 [ $title->getSubjectPage(), $title->getTalkPage() ]
3595 $this->invalidateCache();
3599 * Stop watching an article.
3600 * @since 1.22 $checkRights parameter added
3601 * @param Title $title Title of the article to look at
3602 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3603 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3605 public function removeWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3606 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3607 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
3608 $store->removeWatch( $this, $title->getSubjectPage() );
3609 $store->removeWatch( $this, $title->getTalkPage() );
3611 $this->invalidateCache();
3615 * Clear the user's notification timestamp for the given title.
3616 * If e-notif e-mails are on, they will receive notification mails on
3617 * the next change of the page if it's watched etc.
3618 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3619 * @param Title $title Title of the article to look at
3620 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3622 public function clearNotification( &$title, $oldid = 0 ) {
3623 global $wgUseEnotif, $wgShowUpdatedMarker;
3625 // Do nothing if the database is locked to writes
3626 if ( wfReadOnly() ) {
3630 // Do nothing if not allowed to edit the watchlist
3631 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3635 // If we're working on user's talk page, we should update the talk page message indicator
3636 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3637 // Avoid PHP 7.1 warning of passing $this by reference
3639 if ( !Hooks
::run( 'UserClearNewTalkNotification', [ &$user, $oldid ] ) ) {
3643 // Try to update the DB post-send and only if needed...
3644 DeferredUpdates
::addCallableUpdate( function() use ( $title, $oldid ) {
3645 if ( !$this->getNewtalk() ) {
3646 return; // no notifications to clear
3649 // Delete the last notifications (they stack up)
3650 $this->setNewtalk( false );
3652 // If there is a new, unseen, revision, use its timestamp
3654 ?
$title->getNextRevisionID( $oldid, Title
::GAID_FOR_UPDATE
)
3657 $this->setNewtalk( true, Revision
::newFromId( $nextid ) );
3662 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3666 if ( $this->isAnon() ) {
3667 // Nothing else to do...
3671 // Only update the timestamp if the page is being watched.
3672 // The query to find out if it is watched is cached both in memcached and per-invocation,
3673 // and when it does have to be executed, it can be on a replica DB
3674 // If this is the user's newtalk page, we always update the timestamp
3676 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3680 MediaWikiServices
::getInstance()->getWatchedItemStore()
3681 ->resetNotificationTimestamp( $this, $title, $force, $oldid );
3685 * Resets all of the given user's page-change notification timestamps.
3686 * If e-notif e-mails are on, they will receive notification mails on
3687 * the next change of any watched page.
3688 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3690 public function clearAllNotifications() {
3691 global $wgUseEnotif, $wgShowUpdatedMarker;
3692 // Do nothing if not allowed to edit the watchlist
3693 if ( wfReadOnly() ||
!$this->isAllowed( 'editmywatchlist' ) ) {
3697 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3698 $this->setNewtalk( false );
3702 $id = $this->getId();
3707 $dbw = wfGetDB( DB_MASTER
);
3708 $asOfTimes = array_unique( $dbw->selectFieldValues(
3710 'wl_notificationtimestamp',
3711 [ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ],
3713 [ 'ORDER BY' => 'wl_notificationtimestamp DESC', 'LIMIT' => 500 ]
3715 if ( !$asOfTimes ) {
3718 // Immediately update the most recent touched rows, which hopefully covers what
3719 // the user sees on the watchlist page before pressing "mark all pages visited"....
3722 [ 'wl_notificationtimestamp' => null ],
3723 [ 'wl_user' => $id, 'wl_notificationtimestamp' => $asOfTimes ],
3726 // ...and finish the older ones in a post-send update with lag checks...
3727 DeferredUpdates
::addUpdate( new AutoCommitUpdate(
3730 function () use ( $dbw, $id ) {
3731 global $wgUpdateRowsPerQuery;
3733 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
3734 $ticket = $lbFactory->getEmptyTransactionTicket( __METHOD__
);
3735 $asOfTimes = array_unique( $dbw->selectFieldValues(
3737 'wl_notificationtimestamp',
3738 [ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ],
3741 foreach ( array_chunk( $asOfTimes, $wgUpdateRowsPerQuery ) as $asOfTimeBatch ) {
3744 [ 'wl_notificationtimestamp' => null ],
3745 [ 'wl_user' => $id, 'wl_notificationtimestamp' => $asOfTimeBatch ],
3748 $lbFactory->commitAndWaitForReplication( __METHOD__
, $ticket );
3752 // We also need to clear here the "you have new message" notification for the own
3753 // user_talk page; it's cleared one page view later in WikiPage::doViewUpdates().
3757 * Set a cookie on the user's client. Wrapper for
3758 * WebResponse::setCookie
3759 * @deprecated since 1.27
3760 * @param string $name Name of the cookie to set
3761 * @param string $value Value to set
3762 * @param int $exp Expiration time, as a UNIX time value;
3763 * if 0 or not specified, use the default $wgCookieExpiration
3764 * @param bool $secure
3765 * true: Force setting the secure attribute when setting the cookie
3766 * false: Force NOT setting the secure attribute when setting the cookie
3767 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3768 * @param array $params Array of options sent passed to WebResponse::setcookie()
3769 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3772 protected function setCookie(
3773 $name, $value, $exp = 0, $secure = null, $params = [], $request = null
3775 wfDeprecated( __METHOD__
, '1.27' );
3776 if ( $request === null ) {
3777 $request = $this->getRequest();
3779 $params['secure'] = $secure;
3780 $request->response()->setCookie( $name, $value, $exp, $params );
3784 * Clear a cookie on the user's client
3785 * @deprecated since 1.27
3786 * @param string $name Name of the cookie to clear
3787 * @param bool $secure
3788 * true: Force setting the secure attribute when setting the cookie
3789 * false: Force NOT setting the secure attribute when setting the cookie
3790 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3791 * @param array $params Array of options sent passed to WebResponse::setcookie()
3793 protected function clearCookie( $name, $secure = null, $params = [] ) {
3794 wfDeprecated( __METHOD__
, '1.27' );
3795 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3799 * Set an extended login cookie on the user's client. The expiry of the cookie
3800 * is controlled by the $wgExtendedLoginCookieExpiration configuration
3803 * @see User::setCookie
3805 * @deprecated since 1.27
3806 * @param string $name Name of the cookie to set
3807 * @param string $value Value to set
3808 * @param bool $secure
3809 * true: Force setting the secure attribute when setting the cookie
3810 * false: Force NOT setting the secure attribute when setting the cookie
3811 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3813 protected function setExtendedLoginCookie( $name, $value, $secure ) {
3814 global $wgExtendedLoginCookieExpiration, $wgCookieExpiration;
3816 wfDeprecated( __METHOD__
, '1.27' );
3819 $exp +
= $wgExtendedLoginCookieExpiration !== null
3820 ?
$wgExtendedLoginCookieExpiration
3821 : $wgCookieExpiration;
3823 $this->setCookie( $name, $value, $exp, $secure );
3827 * Persist this user's session (e.g. set cookies)
3829 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3831 * @param bool $secure Whether to force secure/insecure cookies or use default
3832 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3834 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3836 if ( 0 == $this->mId
) {
3840 $session = $this->getRequest()->getSession();
3841 if ( $request && $session->getRequest() !== $request ) {
3842 $session = $session->sessionWithRequest( $request );
3844 $delay = $session->delaySave();
3846 if ( !$session->getUser()->equals( $this ) ) {
3847 if ( !$session->canSetUser() ) {
3848 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3849 ->warning( __METHOD__
.
3850 ": Cannot save user \"$this\" to a user \"{$session->getUser()}\"'s immutable session"
3854 $session->setUser( $this );
3857 $session->setRememberUser( $rememberMe );
3858 if ( $secure !== null ) {
3859 $session->setForceHTTPS( $secure );
3862 $session->persist();
3864 ScopedCallback
::consume( $delay );
3868 * Log this user out.
3870 public function logout() {
3871 // Avoid PHP 7.1 warning of passing $this by reference
3873 if ( Hooks
::run( 'UserLogout', [ &$user ] ) ) {
3879 * Clear the user's session, and reset the instance cache.
3882 public function doLogout() {
3883 $session = $this->getRequest()->getSession();
3884 if ( !$session->canSetUser() ) {
3885 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3886 ->warning( __METHOD__
. ": Cannot log out of an immutable session" );
3887 $error = 'immutable';
3888 } elseif ( !$session->getUser()->equals( $this ) ) {
3889 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3890 ->warning( __METHOD__
.
3891 ": Cannot log user \"$this\" out of a user \"{$session->getUser()}\"'s session"
3893 // But we still may as well make this user object anon
3894 $this->clearInstanceCache( 'defaults' );
3895 $error = 'wronguser';
3897 $this->clearInstanceCache( 'defaults' );
3898 $delay = $session->delaySave();
3899 $session->unpersist(); // Clear cookies (T127436)
3900 $session->setLoggedOutTimestamp( time() );
3901 $session->setUser( new User
);
3902 $session->set( 'wsUserID', 0 ); // Other code expects this
3903 $session->resetAllTokens();
3904 ScopedCallback
::consume( $delay );
3907 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authevents' )->info( 'Logout', [
3908 'event' => 'logout',
3909 'successful' => $error === false,
3910 'status' => $error ?
: 'success',
3915 * Save this user's settings into the database.
3916 * @todo Only rarely do all these fields need to be set!
3918 public function saveSettings() {
3919 if ( wfReadOnly() ) {
3920 // @TODO: caller should deal with this instead!
3921 // This should really just be an exception.
3922 MWExceptionHandler
::logException( new DBExpectedError(
3924 "Could not update user with ID '{$this->mId}'; DB is read-only."
3930 if ( 0 == $this->mId
) {
3934 // Get a new user_touched that is higher than the old one.
3935 // This will be used for a CAS check as a last-resort safety
3936 // check against race conditions and replica DB lag.
3937 $newTouched = $this->newTouchedTimestamp();
3939 $dbw = wfGetDB( DB_MASTER
);
3940 $dbw->update( 'user',
3942 'user_name' => $this->mName
,
3943 'user_real_name' => $this->mRealName
,
3944 'user_email' => $this->mEmail
,
3945 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3946 'user_touched' => $dbw->timestamp( $newTouched ),
3947 'user_token' => strval( $this->mToken
),
3948 'user_email_token' => $this->mEmailToken
,
3949 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
3950 ], $this->makeUpdateConditions( $dbw, [ /* WHERE */
3951 'user_id' => $this->mId
,
3955 if ( !$dbw->affectedRows() ) {
3956 // Maybe the problem was a missed cache update; clear it to be safe
3957 $this->clearSharedCache( 'refresh' );
3958 // User was changed in the meantime or loaded with stale data
3959 $from = ( $this->queryFlagsUsed
& self
::READ_LATEST
) ?
'master' : 'replica';
3960 throw new MWException(
3961 "CAS update failed on user_touched for user ID '{$this->mId}' (read from $from);" .
3962 " the version of the user to be saved is older than the current version."
3966 $this->mTouched
= $newTouched;
3967 $this->saveOptions();
3969 Hooks
::run( 'UserSaveSettings', [ $this ] );
3970 $this->clearSharedCache();
3971 $this->getUserPage()->invalidateCache();
3975 * If only this user's username is known, and it exists, return the user ID.
3977 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
3980 public function idForName( $flags = 0 ) {
3981 $s = trim( $this->getName() );
3986 $db = ( ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
)
3987 ?
wfGetDB( DB_MASTER
)
3988 : wfGetDB( DB_REPLICA
);
3990 $options = ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
)
3991 ?
[ 'LOCK IN SHARE MODE' ]
3994 $id = $db->selectField( 'user',
3995 'user_id', [ 'user_name' => $s ], __METHOD__
, $options );
4001 * Add a user to the database, return the user object
4003 * @param string $name Username to add
4004 * @param array $params Array of Strings Non-default parameters to save to
4005 * the database as user_* fields:
4006 * - email: The user's email address.
4007 * - email_authenticated: The email authentication timestamp.
4008 * - real_name: The user's real name.
4009 * - options: An associative array of non-default options.
4010 * - token: Random authentication token. Do not set.
4011 * - registration: Registration timestamp. Do not set.
4013 * @return User|null User object, or null if the username already exists.
4015 public static function createNew( $name, $params = [] ) {
4016 foreach ( [ 'password', 'newpassword', 'newpass_time', 'password_expires' ] as $field ) {
4017 if ( isset( $params[$field] ) ) {
4018 wfDeprecated( __METHOD__
. " with param '$field'", '1.27' );
4019 unset( $params[$field] );
4025 $user->setToken(); // init token
4026 if ( isset( $params['options'] ) ) {
4027 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
4028 unset( $params['options'] );
4030 $dbw = wfGetDB( DB_MASTER
);
4031 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
4033 $noPass = PasswordFactory
::newInvalidPassword()->toString();
4036 'user_id' => $seqVal,
4037 'user_name' => $name,
4038 'user_password' => $noPass,
4039 'user_newpassword' => $noPass,
4040 'user_email' => $user->mEmail
,
4041 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
4042 'user_real_name' => $user->mRealName
,
4043 'user_token' => strval( $user->mToken
),
4044 'user_registration' => $dbw->timestamp( $user->mRegistration
),
4045 'user_editcount' => 0,
4046 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
4048 foreach ( $params as $name => $value ) {
4049 $fields["user_$name"] = $value;
4051 $dbw->insert( 'user', $fields, __METHOD__
, [ 'IGNORE' ] );
4052 if ( $dbw->affectedRows() ) {
4053 $newUser = User
::newFromId( $dbw->insertId() );
4061 * Add this existing user object to the database. If the user already
4062 * exists, a fatal status object is returned, and the user object is
4063 * initialised with the data from the database.
4065 * Previously, this function generated a DB error due to a key conflict
4066 * if the user already existed. Many extension callers use this function
4067 * in code along the lines of:
4069 * $user = User::newFromName( $name );
4070 * if ( !$user->isLoggedIn() ) {
4071 * $user->addToDatabase();
4073 * // do something with $user...
4075 * However, this was vulnerable to a race condition (bug 16020). By
4076 * initialising the user object if the user exists, we aim to support this
4077 * calling sequence as far as possible.
4079 * Note that if the user exists, this function will acquire a write lock,
4080 * so it is still advisable to make the call conditional on isLoggedIn(),
4081 * and to commit the transaction after calling.
4083 * @throws MWException
4086 public function addToDatabase() {
4088 if ( !$this->mToken
) {
4089 $this->setToken(); // init token
4092 $this->mTouched
= $this->newTouchedTimestamp();
4094 $noPass = PasswordFactory
::newInvalidPassword()->toString();
4096 $dbw = wfGetDB( DB_MASTER
);
4097 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
4098 $dbw->insert( 'user',
4100 'user_id' => $seqVal,
4101 'user_name' => $this->mName
,
4102 'user_password' => $noPass,
4103 'user_newpassword' => $noPass,
4104 'user_email' => $this->mEmail
,
4105 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
4106 'user_real_name' => $this->mRealName
,
4107 'user_token' => strval( $this->mToken
),
4108 'user_registration' => $dbw->timestamp( $this->mRegistration
),
4109 'user_editcount' => 0,
4110 'user_touched' => $dbw->timestamp( $this->mTouched
),
4114 if ( !$dbw->affectedRows() ) {
4115 // Use locking reads to bypass any REPEATABLE-READ snapshot.
4116 $this->mId
= $dbw->selectField(
4119 [ 'user_name' => $this->mName
],
4121 [ 'LOCK IN SHARE MODE' ]
4125 if ( $this->loadFromDatabase( self
::READ_LOCKING
) ) {
4130 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
4131 "to insert user '{$this->mName}' row, but it was not present in select!" );
4133 return Status
::newFatal( 'userexists' );
4135 $this->mId
= $dbw->insertId();
4136 self
::$idCacheByName[$this->mName
] = $this->mId
;
4138 // Clear instance cache other than user table data, which is already accurate
4139 $this->clearInstanceCache();
4141 $this->saveOptions();
4142 return Status
::newGood();
4146 * If this user is logged-in and blocked,
4147 * block any IP address they've successfully logged in from.
4148 * @return bool A block was spread
4150 public function spreadAnyEditBlock() {
4151 if ( $this->isLoggedIn() && $this->isBlocked() ) {
4152 return $this->spreadBlock();
4159 * If this (non-anonymous) user is blocked,
4160 * block the IP address they've successfully logged in from.
4161 * @return bool A block was spread
4163 protected function spreadBlock() {
4164 wfDebug( __METHOD__
. "()\n" );
4166 if ( $this->mId
== 0 ) {
4170 $userblock = Block
::newFromTarget( $this->getName() );
4171 if ( !$userblock ) {
4175 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
4179 * Get whether the user is explicitly blocked from account creation.
4180 * @return bool|Block
4182 public function isBlockedFromCreateAccount() {
4183 $this->getBlockedStatus();
4184 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
4185 return $this->mBlock
;
4188 # bug 13611: if the IP address the user is trying to create an account from is
4189 # blocked with createaccount disabled, prevent new account creation there even
4190 # when the user is logged in
4191 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
4192 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
4194 return $this->mBlockedFromCreateAccount
instanceof Block
4195 && $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
4196 ?
$this->mBlockedFromCreateAccount
4201 * Get whether the user is blocked from using Special:Emailuser.
4204 public function isBlockedFromEmailuser() {
4205 $this->getBlockedStatus();
4206 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
4210 * Get whether the user is allowed to create an account.
4213 public function isAllowedToCreateAccount() {
4214 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
4218 * Get this user's personal page title.
4220 * @return Title User's personal page title
4222 public function getUserPage() {
4223 return Title
::makeTitle( NS_USER
, $this->getName() );
4227 * Get this user's talk page title.
4229 * @return Title User's talk page title
4231 public function getTalkPage() {
4232 $title = $this->getUserPage();
4233 return $title->getTalkPage();
4237 * Determine whether the user is a newbie. Newbies are either
4238 * anonymous IPs, or the most recently created accounts.
4241 public function isNewbie() {
4242 return !$this->isAllowed( 'autoconfirmed' );
4246 * Check to see if the given clear-text password is one of the accepted passwords
4247 * @deprecated since 1.27, use AuthManager instead
4248 * @param string $password User password
4249 * @return bool True if the given password is correct, otherwise False
4251 public function checkPassword( $password ) {
4252 $manager = AuthManager
::singleton();
4253 $reqs = AuthenticationRequest
::loadRequestsFromSubmission(
4254 $manager->getAuthenticationRequests( AuthManager
::ACTION_LOGIN
),
4256 'username' => $this->getName(),
4257 'password' => $password,
4260 $res = AuthManager
::singleton()->beginAuthentication( $reqs, 'null:' );
4261 switch ( $res->status
) {
4262 case AuthenticationResponse
::PASS
:
4264 case AuthenticationResponse
::FAIL
:
4265 // Hope it's not a PreAuthenticationProvider that failed...
4266 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
4267 ->info( __METHOD__
. ': Authentication failed: ' . $res->message
->plain() );
4270 throw new BadMethodCallException(
4271 'AuthManager returned a response unsupported by ' . __METHOD__
4277 * Check if the given clear-text password matches the temporary password
4278 * sent by e-mail for password reset operations.
4280 * @deprecated since 1.27, use AuthManager instead
4281 * @param string $plaintext
4282 * @return bool True if matches, false otherwise
4284 public function checkTemporaryPassword( $plaintext ) {
4285 // Can't check the temporary password individually.
4286 return $this->checkPassword( $plaintext );
4290 * Initialize (if necessary) and return a session token value
4291 * which can be used in edit forms to show that the user's
4292 * login credentials aren't being hijacked with a foreign form
4296 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4297 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4298 * @return MediaWiki\Session\Token The new edit token
4300 public function getEditTokenObject( $salt = '', $request = null ) {
4301 if ( $this->isAnon() ) {
4302 return new LoggedOutEditToken();
4306 $request = $this->getRequest();
4308 return $request->getSession()->getToken( $salt );
4312 * Initialize (if necessary) and return a session token value
4313 * which can be used in edit forms to show that the user's
4314 * login credentials aren't being hijacked with a foreign form
4317 * The $salt for 'edit' and 'csrf' tokens is the default (empty string).
4320 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4321 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4322 * @return string The new edit token
4324 public function getEditToken( $salt = '', $request = null ) {
4325 return $this->getEditTokenObject( $salt, $request )->toString();
4329 * Get the embedded timestamp from a token.
4330 * @deprecated since 1.27, use \MediaWiki\Session\Token::getTimestamp instead.
4331 * @param string $val Input token
4334 public static function getEditTokenTimestamp( $val ) {
4335 wfDeprecated( __METHOD__
, '1.27' );
4336 return MediaWiki\Session\Token
::getTimestamp( $val );
4340 * Check given value against the token value stored in the session.
4341 * A match should confirm that the form was submitted from the
4342 * user's own login session, not a form submission from a third-party
4345 * @param string $val Input value to compare
4346 * @param string $salt Optional function-specific data for hashing
4347 * @param WebRequest|null $request Object to use or null to use $wgRequest
4348 * @param int $maxage Fail tokens older than this, in seconds
4349 * @return bool Whether the token matches
4351 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4352 return $this->getEditTokenObject( $salt, $request )->match( $val, $maxage );
4356 * Check given value against the token value stored in the session,
4357 * ignoring the suffix.
4359 * @param string $val Input value to compare
4360 * @param string $salt Optional function-specific data for hashing
4361 * @param WebRequest|null $request Object to use or null to use $wgRequest
4362 * @param int $maxage Fail tokens older than this, in seconds
4363 * @return bool Whether the token matches
4365 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4366 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . Token
::SUFFIX
;
4367 return $this->matchEditToken( $val, $salt, $request, $maxage );
4371 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4372 * mail to the user's given address.
4374 * @param string $type Message to send, either "created", "changed" or "set"
4377 public function sendConfirmationMail( $type = 'created' ) {
4379 $expiration = null; // gets passed-by-ref and defined in next line.
4380 $token = $this->confirmationToken( $expiration );
4381 $url = $this->confirmationTokenUrl( $token );
4382 $invalidateURL = $this->invalidationTokenUrl( $token );
4383 $this->saveSettings();
4385 if ( $type == 'created' ||
$type === false ) {
4386 $message = 'confirmemail_body';
4387 } elseif ( $type === true ) {
4388 $message = 'confirmemail_body_changed';
4390 // Messages: confirmemail_body_changed, confirmemail_body_set
4391 $message = 'confirmemail_body_' . $type;
4394 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4395 wfMessage( $message,
4396 $this->getRequest()->getIP(),
4399 $wgLang->userTimeAndDate( $expiration, $this ),
4401 $wgLang->userDate( $expiration, $this ),
4402 $wgLang->userTime( $expiration, $this ) )->text() );
4406 * Send an e-mail to this user's account. Does not check for
4407 * confirmed status or validity.
4409 * @param string $subject Message subject
4410 * @param string $body Message body
4411 * @param User|null $from Optional sending user; if unspecified, default
4412 * $wgPasswordSender will be used.
4413 * @param string $replyto Reply-To address
4416 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4417 global $wgPasswordSender;
4419 if ( $from instanceof User
) {
4420 $sender = MailAddress
::newFromUser( $from );
4422 $sender = new MailAddress( $wgPasswordSender,
4423 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4425 $to = MailAddress
::newFromUser( $this );
4427 return UserMailer
::send( $to, $sender, $subject, $body, [
4428 'replyTo' => $replyto,
4433 * Generate, store, and return a new e-mail confirmation code.
4434 * A hash (unsalted, since it's used as a key) is stored.
4436 * @note Call saveSettings() after calling this function to commit
4437 * this change to the database.
4439 * @param string &$expiration Accepts the expiration time
4440 * @return string New token
4442 protected function confirmationToken( &$expiration ) {
4443 global $wgUserEmailConfirmationTokenExpiry;
4445 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4446 $expiration = wfTimestamp( TS_MW
, $expires );
4448 $token = MWCryptRand
::generateHex( 32 );
4449 $hash = md5( $token );
4450 $this->mEmailToken
= $hash;
4451 $this->mEmailTokenExpires
= $expiration;
4456 * Return a URL the user can use to confirm their email address.
4457 * @param string $token Accepts the email confirmation token
4458 * @return string New token URL
4460 protected function confirmationTokenUrl( $token ) {
4461 return $this->getTokenUrl( 'ConfirmEmail', $token );
4465 * Return a URL the user can use to invalidate their email address.
4466 * @param string $token Accepts the email confirmation token
4467 * @return string New token URL
4469 protected function invalidationTokenUrl( $token ) {
4470 return $this->getTokenUrl( 'InvalidateEmail', $token );
4474 * Internal function to format the e-mail validation/invalidation URLs.
4475 * This uses a quickie hack to use the
4476 * hardcoded English names of the Special: pages, for ASCII safety.
4478 * @note Since these URLs get dropped directly into emails, using the
4479 * short English names avoids insanely long URL-encoded links, which
4480 * also sometimes can get corrupted in some browsers/mailers
4481 * (bug 6957 with Gmail and Internet Explorer).
4483 * @param string $page Special page
4484 * @param string $token Token
4485 * @return string Formatted URL
4487 protected function getTokenUrl( $page, $token ) {
4488 // Hack to bypass localization of 'Special:'
4489 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4490 return $title->getCanonicalURL();
4494 * Mark the e-mail address confirmed.
4496 * @note Call saveSettings() after calling this function to commit the change.
4500 public function confirmEmail() {
4501 // Check if it's already confirmed, so we don't touch the database
4502 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4503 if ( !$this->isEmailConfirmed() ) {
4504 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4505 Hooks
::run( 'ConfirmEmailComplete', [ $this ] );
4511 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4512 * address if it was already confirmed.
4514 * @note Call saveSettings() after calling this function to commit the change.
4515 * @return bool Returns true
4517 public function invalidateEmail() {
4519 $this->mEmailToken
= null;
4520 $this->mEmailTokenExpires
= null;
4521 $this->setEmailAuthenticationTimestamp( null );
4523 Hooks
::run( 'InvalidateEmailComplete', [ $this ] );
4528 * Set the e-mail authentication timestamp.
4529 * @param string $timestamp TS_MW timestamp
4531 public function setEmailAuthenticationTimestamp( $timestamp ) {
4533 $this->mEmailAuthenticated
= $timestamp;
4534 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
4538 * Is this user allowed to send e-mails within limits of current
4539 * site configuration?
4542 public function canSendEmail() {
4543 global $wgEnableEmail, $wgEnableUserEmail;
4544 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4547 $canSend = $this->isEmailConfirmed();
4548 // Avoid PHP 7.1 warning of passing $this by reference
4550 Hooks
::run( 'UserCanSendEmail', [ &$user, &$canSend ] );
4555 * Is this user allowed to receive e-mails within limits of current
4556 * site configuration?
4559 public function canReceiveEmail() {
4560 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4564 * Is this user's e-mail address valid-looking and confirmed within
4565 * limits of the current site configuration?
4567 * @note If $wgEmailAuthentication is on, this may require the user to have
4568 * confirmed their address by returning a code or using a password
4569 * sent to the address from the wiki.
4573 public function isEmailConfirmed() {
4574 global $wgEmailAuthentication;
4576 // Avoid PHP 7.1 warning of passing $this by reference
4579 if ( Hooks
::run( 'EmailConfirmed', [ &$user, &$confirmed ] ) ) {
4580 if ( $this->isAnon() ) {
4583 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4586 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4596 * Check whether there is an outstanding request for e-mail confirmation.
4599 public function isEmailConfirmationPending() {
4600 global $wgEmailAuthentication;
4601 return $wgEmailAuthentication &&
4602 !$this->isEmailConfirmed() &&
4603 $this->mEmailToken
&&
4604 $this->mEmailTokenExpires
> wfTimestamp();
4608 * Get the timestamp of account creation.
4610 * @return string|bool|null Timestamp of account creation, false for
4611 * non-existent/anonymous user accounts, or null if existing account
4612 * but information is not in database.
4614 public function getRegistration() {
4615 if ( $this->isAnon() ) {
4619 return $this->mRegistration
;
4623 * Get the timestamp of the first edit
4625 * @return string|bool Timestamp of first edit, or false for
4626 * non-existent/anonymous user accounts.
4628 public function getFirstEditTimestamp() {
4629 if ( $this->getId() == 0 ) {
4630 return false; // anons
4632 $dbr = wfGetDB( DB_REPLICA
);
4633 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4634 [ 'rev_user' => $this->getId() ],
4636 [ 'ORDER BY' => 'rev_timestamp ASC' ]
4639 return false; // no edits
4641 return wfTimestamp( TS_MW
, $time );
4645 * Get the permissions associated with a given list of groups
4647 * @param array $groups Array of Strings List of internal group names
4648 * @return array Array of Strings List of permission key names for given groups combined
4650 public static function getGroupPermissions( $groups ) {
4651 global $wgGroupPermissions, $wgRevokePermissions;
4653 // grant every granted permission first
4654 foreach ( $groups as $group ) {
4655 if ( isset( $wgGroupPermissions[$group] ) ) {
4656 $rights = array_merge( $rights,
4657 // array_filter removes empty items
4658 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4661 // now revoke the revoked permissions
4662 foreach ( $groups as $group ) {
4663 if ( isset( $wgRevokePermissions[$group] ) ) {
4664 $rights = array_diff( $rights,
4665 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4668 return array_unique( $rights );
4672 * Get all the groups who have a given permission
4674 * @param string $role Role to check
4675 * @return array Array of Strings List of internal group names with the given permission
4677 public static function getGroupsWithPermission( $role ) {
4678 global $wgGroupPermissions;
4679 $allowedGroups = [];
4680 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4681 if ( self
::groupHasPermission( $group, $role ) ) {
4682 $allowedGroups[] = $group;
4685 return $allowedGroups;
4689 * Check, if the given group has the given permission
4691 * If you're wanting to check whether all users have a permission, use
4692 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4696 * @param string $group Group to check
4697 * @param string $role Role to check
4700 public static function groupHasPermission( $group, $role ) {
4701 global $wgGroupPermissions, $wgRevokePermissions;
4702 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4703 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4707 * Check if all users may be assumed to have the given permission
4709 * We generally assume so if the right is granted to '*' and isn't revoked
4710 * on any group. It doesn't attempt to take grants or other extension
4711 * limitations on rights into account in the general case, though, as that
4712 * would require it to always return false and defeat the purpose.
4713 * Specifically, session-based rights restrictions (such as OAuth or bot
4714 * passwords) are applied based on the current session.
4717 * @param string $right Right to check
4720 public static function isEveryoneAllowed( $right ) {
4721 global $wgGroupPermissions, $wgRevokePermissions;
4724 // Use the cached results, except in unit tests which rely on
4725 // being able change the permission mid-request
4726 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4727 return $cache[$right];
4730 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4731 $cache[$right] = false;
4735 // If it's revoked anywhere, then everyone doesn't have it
4736 foreach ( $wgRevokePermissions as $rights ) {
4737 if ( isset( $rights[$right] ) && $rights[$right] ) {
4738 $cache[$right] = false;
4743 // Remove any rights that aren't allowed to the global-session user,
4744 // unless there are no sessions for this endpoint.
4745 if ( !defined( 'MW_NO_SESSION' ) ) {
4746 $allowedRights = SessionManager
::getGlobalSession()->getAllowedUserRights();
4747 if ( $allowedRights !== null && !in_array( $right, $allowedRights, true ) ) {
4748 $cache[$right] = false;
4753 // Allow extensions to say false
4754 if ( !Hooks
::run( 'UserIsEveryoneAllowed', [ $right ] ) ) {
4755 $cache[$right] = false;
4759 $cache[$right] = true;
4764 * Get the localized descriptive name for a group, if it exists
4765 * @deprecated since 1.29 Use UserGroupMembership::getGroupName instead
4767 * @param string $group Internal group name
4768 * @return string Localized descriptive group name
4770 public static function getGroupName( $group ) {
4771 wfDeprecated( __METHOD__
, '1.29' );
4772 return UserGroupMembership
::getGroupName( $group );
4776 * Get the localized descriptive name for a member of a group, if it exists
4777 * @deprecated since 1.29 Use UserGroupMembership::getGroupMemberName instead
4779 * @param string $group Internal group name
4780 * @param string $username Username for gender (since 1.19)
4781 * @return string Localized name for group member
4783 public static function getGroupMember( $group, $username = '#' ) {
4784 wfDeprecated( __METHOD__
, '1.29' );
4785 return UserGroupMembership
::getGroupMemberName( $group, $username );
4789 * Return the set of defined explicit groups.
4790 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4791 * are not included, as they are defined automatically, not in the database.
4792 * @return array Array of internal group names
4794 public static function getAllGroups() {
4795 global $wgGroupPermissions, $wgRevokePermissions;
4797 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4798 self
::getImplicitGroups()
4803 * Get a list of all available permissions.
4804 * @return string[] Array of permission names
4806 public static function getAllRights() {
4807 if ( self
::$mAllRights === false ) {
4808 global $wgAvailableRights;
4809 if ( count( $wgAvailableRights ) ) {
4810 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
4812 self
::$mAllRights = self
::$mCoreRights;
4814 Hooks
::run( 'UserGetAllRights', [ &self
::$mAllRights ] );
4816 return self
::$mAllRights;
4820 * Get a list of implicit groups
4821 * @return array Array of Strings Array of internal group names
4823 public static function getImplicitGroups() {
4824 global $wgImplicitGroups;
4826 $groups = $wgImplicitGroups;
4827 # Deprecated, use $wgImplicitGroups instead
4828 Hooks
::run( 'UserGetImplicitGroups', [ &$groups ], '1.25' );
4834 * Get the title of a page describing a particular group
4835 * @deprecated since 1.29 Use UserGroupMembership::getGroupPage instead
4837 * @param string $group Internal group name
4838 * @return Title|bool Title of the page if it exists, false otherwise
4840 public static function getGroupPage( $group ) {
4841 wfDeprecated( __METHOD__
, '1.29' );
4842 return UserGroupMembership
::getGroupPage( $group );
4846 * Create a link to the group in HTML, if available;
4847 * else return the group name.
4848 * @deprecated since 1.29 Use UserGroupMembership::getLink instead, or
4849 * make the link yourself if you need custom text
4851 * @param string $group Internal name of the group
4852 * @param string $text The text of the link
4853 * @return string HTML link to the group
4855 public static function makeGroupLinkHTML( $group, $text = '' ) {
4856 wfDeprecated( __METHOD__
, '1.29' );
4858 if ( $text == '' ) {
4859 $text = UserGroupMembership
::getGroupName( $group );
4861 $title = UserGroupMembership
::getGroupPage( $group );
4863 return Linker
::link( $title, htmlspecialchars( $text ) );
4865 return htmlspecialchars( $text );
4870 * Create a link to the group in Wikitext, if available;
4871 * else return the group name.
4872 * @deprecated since 1.29 Use UserGroupMembership::getLink instead, or
4873 * make the link yourself if you need custom text
4875 * @param string $group Internal name of the group
4876 * @param string $text The text of the link
4877 * @return string Wikilink to the group
4879 public static function makeGroupLinkWiki( $group, $text = '' ) {
4880 wfDeprecated( __METHOD__
, '1.29' );
4882 if ( $text == '' ) {
4883 $text = UserGroupMembership
::getGroupName( $group );
4885 $title = UserGroupMembership
::getGroupPage( $group );
4887 $page = $title->getFullText();
4888 return "[[$page|$text]]";
4895 * Returns an array of the groups that a particular group can add/remove.
4897 * @param string $group The group to check for whether it can add/remove
4898 * @return array Array( 'add' => array( addablegroups ),
4899 * 'remove' => array( removablegroups ),
4900 * 'add-self' => array( addablegroups to self),
4901 * 'remove-self' => array( removable groups from self) )
4903 public static function changeableByGroup( $group ) {
4904 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4913 if ( empty( $wgAddGroups[$group] ) ) {
4914 // Don't add anything to $groups
4915 } elseif ( $wgAddGroups[$group] === true ) {
4916 // You get everything
4917 $groups['add'] = self
::getAllGroups();
4918 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4919 $groups['add'] = $wgAddGroups[$group];
4922 // Same thing for remove
4923 if ( empty( $wgRemoveGroups[$group] ) ) {
4925 } elseif ( $wgRemoveGroups[$group] === true ) {
4926 $groups['remove'] = self
::getAllGroups();
4927 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4928 $groups['remove'] = $wgRemoveGroups[$group];
4931 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4932 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4933 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4934 if ( is_int( $key ) ) {
4935 $wgGroupsAddToSelf['user'][] = $value;
4940 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
4941 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4942 if ( is_int( $key ) ) {
4943 $wgGroupsRemoveFromSelf['user'][] = $value;
4948 // Now figure out what groups the user can add to him/herself
4949 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4951 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4952 // No idea WHY this would be used, but it's there
4953 $groups['add-self'] = User
::getAllGroups();
4954 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4955 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4958 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4960 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4961 $groups['remove-self'] = User
::getAllGroups();
4962 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4963 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4970 * Returns an array of groups that this user can add and remove
4971 * @return array Array( 'add' => array( addablegroups ),
4972 * 'remove' => array( removablegroups ),
4973 * 'add-self' => array( addablegroups to self),
4974 * 'remove-self' => array( removable groups from self) )
4976 public function changeableGroups() {
4977 if ( $this->isAllowed( 'userrights' ) ) {
4978 // This group gives the right to modify everything (reverse-
4979 // compatibility with old "userrights lets you change
4981 // Using array_merge to make the groups reindexed
4982 $all = array_merge( User
::getAllGroups() );
4991 // Okay, it's not so simple, we will have to go through the arrays
4998 $addergroups = $this->getEffectiveGroups();
5000 foreach ( $addergroups as $addergroup ) {
5001 $groups = array_merge_recursive(
5002 $groups, $this->changeableByGroup( $addergroup )
5004 $groups['add'] = array_unique( $groups['add'] );
5005 $groups['remove'] = array_unique( $groups['remove'] );
5006 $groups['add-self'] = array_unique( $groups['add-self'] );
5007 $groups['remove-self'] = array_unique( $groups['remove-self'] );
5013 * Deferred version of incEditCountImmediate()
5015 public function incEditCount() {
5016 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle(
5018 $this->incEditCountImmediate();
5025 * Increment the user's edit-count field.
5026 * Will have no effect for anonymous users.
5029 public function incEditCountImmediate() {
5030 if ( $this->isAnon() ) {
5034 $dbw = wfGetDB( DB_MASTER
);
5035 // No rows will be "affected" if user_editcount is NULL
5038 [ 'user_editcount=user_editcount+1' ],
5039 [ 'user_id' => $this->getId(), 'user_editcount IS NOT NULL' ],
5042 // Lazy initialization check...
5043 if ( $dbw->affectedRows() == 0 ) {
5044 // Now here's a goddamn hack...
5045 $dbr = wfGetDB( DB_REPLICA
);
5046 if ( $dbr !== $dbw ) {
5047 // If we actually have a replica DB server, the count is
5048 // at least one behind because the current transaction
5049 // has not been committed and replicated.
5050 $this->mEditCount
= $this->initEditCount( 1 );
5052 // But if DB_REPLICA is selecting the master, then the
5053 // count we just read includes the revision that was
5054 // just added in the working transaction.
5055 $this->mEditCount
= $this->initEditCount();
5058 if ( $this->mEditCount
=== null ) {
5059 $this->getEditCount();
5060 $dbr = wfGetDB( DB_REPLICA
);
5061 $this->mEditCount +
= ( $dbr !== $dbw ) ?
1 : 0;
5063 $this->mEditCount++
;
5066 // Edit count in user cache too
5067 $this->invalidateCache();
5071 * Initialize user_editcount from data out of the revision table
5073 * @param int $add Edits to add to the count from the revision table
5074 * @return int Number of edits
5076 protected function initEditCount( $add = 0 ) {
5077 // Pull from a replica DB to be less cruel to servers
5078 // Accuracy isn't the point anyway here
5079 $dbr = wfGetDB( DB_REPLICA
);
5080 $count = (int)$dbr->selectField(
5083 [ 'rev_user' => $this->getId() ],
5086 $count = $count +
$add;
5088 $dbw = wfGetDB( DB_MASTER
);
5091 [ 'user_editcount' => $count ],
5092 [ 'user_id' => $this->getId() ],
5100 * Get the description of a given right
5103 * @param string $right Right to query
5104 * @return string Localized description of the right
5106 public static function getRightDescription( $right ) {
5107 $key = "right-$right";
5108 $msg = wfMessage( $key );
5109 return $msg->isDisabled() ?
$right : $msg->text();
5113 * Get the name of a given grant
5116 * @param string $grant Grant to query
5117 * @return string Localized name of the grant
5119 public static function getGrantName( $grant ) {
5120 $key = "grant-$grant";
5121 $msg = wfMessage( $key );
5122 return $msg->isDisabled() ?
$grant : $msg->text();
5126 * Add a newuser log entry for this user.
5127 * Before 1.19 the return value was always true.
5129 * @deprecated since 1.27, AuthManager handles logging
5130 * @param string|bool $action Account creation type.
5131 * - String, one of the following values:
5132 * - 'create' for an anonymous user creating an account for himself.
5133 * This will force the action's performer to be the created user itself,
5134 * no matter the value of $wgUser
5135 * - 'create2' for a logged in user creating an account for someone else
5136 * - 'byemail' when the created user will receive its password by e-mail
5137 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
5138 * - Boolean means whether the account was created by e-mail (deprecated):
5139 * - true will be converted to 'byemail'
5140 * - false will be converted to 'create' if this object is the same as
5141 * $wgUser and to 'create2' otherwise
5142 * @param string $reason User supplied reason
5145 public function addNewUserLogEntry( $action = false, $reason = '' ) {
5146 return true; // disabled
5150 * Add an autocreate newuser log entry for this user
5151 * Used by things like CentralAuth and perhaps other authplugins.
5152 * Consider calling addNewUserLogEntry() directly instead.
5154 * @deprecated since 1.27, AuthManager handles logging
5157 public function addNewUserLogEntryAutoCreate() {
5158 $this->addNewUserLogEntry( 'autocreate' );
5164 * Load the user options either from cache, the database or an array
5166 * @param array $data Rows for the current user out of the user_properties table
5168 protected function loadOptions( $data = null ) {
5173 if ( $this->mOptionsLoaded
) {
5177 $this->mOptions
= self
::getDefaultOptions();
5179 if ( !$this->getId() ) {
5180 // For unlogged-in users, load language/variant options from request.
5181 // There's no need to do it for logged-in users: they can set preferences,
5182 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5183 // so don't override user's choice (especially when the user chooses site default).
5184 $variant = $wgContLang->getDefaultVariant();
5185 $this->mOptions
['variant'] = $variant;
5186 $this->mOptions
['language'] = $variant;
5187 $this->mOptionsLoaded
= true;
5191 // Maybe load from the object
5192 if ( !is_null( $this->mOptionOverrides
) ) {
5193 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5194 foreach ( $this->mOptionOverrides
as $key => $value ) {
5195 $this->mOptions
[$key] = $value;
5198 if ( !is_array( $data ) ) {
5199 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5200 // Load from database
5201 $dbr = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
5202 ?
wfGetDB( DB_MASTER
)
5203 : wfGetDB( DB_REPLICA
);
5205 $res = $dbr->select(
5207 [ 'up_property', 'up_value' ],
5208 [ 'up_user' => $this->getId() ],
5212 $this->mOptionOverrides
= [];
5214 foreach ( $res as $row ) {
5215 $data[$row->up_property
] = $row->up_value
;
5218 foreach ( $data as $property => $value ) {
5219 $this->mOptionOverrides
[$property] = $value;
5220 $this->mOptions
[$property] = $value;
5224 $this->mOptionsLoaded
= true;
5226 Hooks
::run( 'UserLoadOptions', [ $this, &$this->mOptions
] );
5230 * Saves the non-default options for this user, as previously set e.g. via
5231 * setOption(), in the database's "user_properties" (preferences) table.
5232 * Usually used via saveSettings().
5234 protected function saveOptions() {
5235 $this->loadOptions();
5237 // Not using getOptions(), to keep hidden preferences in database
5238 $saveOptions = $this->mOptions
;
5240 // Allow hooks to abort, for instance to save to a global profile.
5241 // Reset options to default state before saving.
5242 if ( !Hooks
::run( 'UserSaveOptions', [ $this, &$saveOptions ] ) ) {
5246 $userId = $this->getId();
5248 $insert_rows = []; // all the new preference rows
5249 foreach ( $saveOptions as $key => $value ) {
5250 // Don't bother storing default values
5251 $defaultOption = self
::getDefaultOption( $key );
5252 if ( ( $defaultOption === null && $value !== false && $value !== null )
5253 ||
$value != $defaultOption
5256 'up_user' => $userId,
5257 'up_property' => $key,
5258 'up_value' => $value,
5263 $dbw = wfGetDB( DB_MASTER
);
5265 $res = $dbw->select( 'user_properties',
5266 [ 'up_property', 'up_value' ], [ 'up_user' => $userId ], __METHOD__
);
5268 // Find prior rows that need to be removed or updated. These rows will
5269 // all be deleted (the latter so that INSERT IGNORE applies the new values).
5271 foreach ( $res as $row ) {
5272 if ( !isset( $saveOptions[$row->up_property
] )
5273 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
5275 $keysDelete[] = $row->up_property
;
5279 if ( count( $keysDelete ) ) {
5280 // Do the DELETE by PRIMARY KEY for prior rows.
5281 // In the past a very large portion of calls to this function are for setting
5282 // 'rememberpassword' for new accounts (a preference that has since been removed).
5283 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5284 // caused gap locks on [max user ID,+infinity) which caused high contention since
5285 // updates would pile up on each other as they are for higher (newer) user IDs.
5286 // It might not be necessary these days, but it shouldn't hurt either.
5287 $dbw->delete( 'user_properties',
5288 [ 'up_user' => $userId, 'up_property' => $keysDelete ], __METHOD__
);
5290 // Insert the new preference rows
5291 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, [ 'IGNORE' ] );
5295 * Lazily instantiate and return a factory object for making passwords
5297 * @deprecated since 1.27, create a PasswordFactory directly instead
5298 * @return PasswordFactory
5300 public static function getPasswordFactory() {
5301 wfDeprecated( __METHOD__
, '1.27' );
5302 $ret = new PasswordFactory();
5303 $ret->init( RequestContext
::getMain()->getConfig() );
5308 * Provide an array of HTML5 attributes to put on an input element
5309 * intended for the user to enter a new password. This may include
5310 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
5312 * Do *not* use this when asking the user to enter his current password!
5313 * Regardless of configuration, users may have invalid passwords for whatever
5314 * reason (e.g., they were set before requirements were tightened up).
5315 * Only use it when asking for a new password, like on account creation or
5318 * Obviously, you still need to do server-side checking.
5320 * NOTE: A combination of bugs in various browsers means that this function
5321 * actually just returns array() unconditionally at the moment. May as
5322 * well keep it around for when the browser bugs get fixed, though.
5324 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
5326 * @deprecated since 1.27
5327 * @return array Array of HTML attributes suitable for feeding to
5328 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
5329 * That will get confused by the boolean attribute syntax used.)
5331 public static function passwordChangeInputAttribs() {
5332 global $wgMinimalPasswordLength;
5334 if ( $wgMinimalPasswordLength == 0 ) {
5338 # Note that the pattern requirement will always be satisfied if the
5339 # input is empty, so we need required in all cases.
5341 # @todo FIXME: Bug 23769: This needs to not claim the password is required
5342 # if e-mail confirmation is being used. Since HTML5 input validation
5343 # is b0rked anyway in some browsers, just return nothing. When it's
5344 # re-enabled, fix this code to not output required for e-mail
5346 # $ret = array( 'required' );
5349 # We can't actually do this right now, because Opera 9.6 will print out
5350 # the entered password visibly in its error message! When other
5351 # browsers add support for this attribute, or Opera fixes its support,
5352 # we can add support with a version check to avoid doing this on Opera
5353 # versions where it will be a problem. Reported to Opera as
5354 # DSK-262266, but they don't have a public bug tracker for us to follow.
5356 if ( $wgMinimalPasswordLength > 1 ) {
5357 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
5358 $ret['title'] = wfMessage( 'passwordtooshort' )
5359 ->numParams( $wgMinimalPasswordLength )->text();
5367 * Return the list of user fields that should be selected to create
5368 * a new user object.
5371 public static function selectFields() {
5379 'user_email_authenticated',
5381 'user_email_token_expires',
5382 'user_registration',
5388 * Factory function for fatal permission-denied errors
5391 * @param string $permission User right required
5394 static function newFatalPermissionDeniedStatus( $permission ) {
5398 foreach ( User
::getGroupsWithPermission( $permission ) as $group ) {
5399 $groups[] = UserGroupMembership
::getLink( $group, RequestContext
::getMain(), 'wiki' );
5403 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5405 return Status
::newFatal( 'badaccess-group0' );
5410 * Get a new instance of this user that was loaded from the master via a locking read
5412 * Use this instead of the main context User when updating that user. This avoids races
5413 * where that user was loaded from a replica DB or even the master but without proper locks.
5415 * @return User|null Returns null if the user was not found in the DB
5418 public function getInstanceForUpdate() {
5419 if ( !$this->getId() ) {
5420 return null; // anon
5423 $user = self
::newFromId( $this->getId() );
5424 if ( !$user->loadFromId( self
::READ_EXCLUSIVE
) ) {
5432 * Checks if two user objects point to the same user.
5438 public function equals( User
$user ) {
5439 return $this->getName() === $user->getName();