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. (T25080)
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 (T14654)
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 );
1641 if ( !$block instanceof Block
) {
1642 $block = $this->getBlockFromCookieValue( $this->getRequest()->getCookie( 'BlockID' ) );
1646 if ( !$block instanceof Block
&& $ip !== null && !in_array( $ip, $wgProxyWhitelist ) ) {
1648 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1649 $block = new Block( [
1650 'byText' => wfMessage( 'proxyblocker' )->text(),
1651 'reason' => wfMessage( 'proxyblockreason' )->text(),
1653 'systemBlock' => 'proxy',
1655 $this->blockTrigger
= 'proxy-block';
1656 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1657 $block = new Block( [
1658 'byText' => wfMessage( 'sorbs' )->text(),
1659 'reason' => wfMessage( 'sorbsreason' )->text(),
1661 'systemBlock' => 'dnsbl',
1663 $this->blockTrigger
= 'openproxy-block';
1667 // (T25343) Apply IP blocks to the contents of XFF headers, if enabled
1668 if ( !$block instanceof Block
1669 && $wgApplyIpBlocksToXff
1671 && !in_array( $ip, $wgProxyWhitelist )
1673 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1674 $xff = array_map( 'trim', explode( ',', $xff ) );
1675 $xff = array_diff( $xff, [ $ip ] );
1676 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1677 $block = Block
::chooseBlock( $xffblocks, $xff );
1678 if ( $block instanceof Block
) {
1679 # Mangle the reason to alert the user that the block
1680 # originated from matching the X-Forwarded-For header.
1681 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->text();
1682 $this->blockTrigger
= 'xff-block';
1686 if ( !$block instanceof Block
1689 && IP
::isInRanges( $ip, $wgSoftBlockRanges )
1691 $block = new Block( [
1693 'byText' => 'MediaWiki default',
1694 'reason' => wfMessage( 'softblockrangesreason', $ip )->text(),
1696 'systemBlock' => 'wgSoftBlockRanges',
1698 $this->blockTrigger
= 'config-block';
1701 if ( $block instanceof Block
) {
1702 wfDebug( __METHOD__
. ": Found block.\n" );
1703 $this->mBlock
= $block;
1704 $this->mBlockedby
= $block->getByName();
1705 $this->mBlockreason
= $block->mReason
;
1706 $this->mHideName
= $block->mHideName
;
1707 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1709 $this->mBlockedby
= '';
1710 $this->mHideName
= 0;
1711 $this->mAllowUsertalk
= false;
1712 $this->blockTrigger
= false;
1715 // Avoid PHP 7.1 warning of passing $this by reference
1718 Hooks
::run( 'GetBlockedStatus', [ &$user ] );
1722 * Try to load a Block from an ID given in a cookie value.
1723 * @param string|null $blockCookieVal The cookie value to check.
1724 * @return Block|bool The Block object, or false if none could be loaded.
1726 protected function getBlockFromCookieValue( $blockCookieVal ) {
1727 // Make sure there's something to check. The cookie value must start with a number.
1728 if ( strlen( $blockCookieVal ) < 1 ||
!is_numeric( substr( $blockCookieVal, 0, 1 ) ) ) {
1731 // Load the Block from the ID in the cookie.
1732 $blockCookieId = Block
::getIdFromCookieValue( $blockCookieVal );
1733 if ( $blockCookieId !== null ) {
1734 // An ID was found in the cookie.
1735 $tmpBlock = Block
::newFromID( $blockCookieId );
1736 if ( $tmpBlock instanceof Block
) {
1737 // Check the validity of the block.
1738 $blockIsValid = $tmpBlock->getType() == Block
::TYPE_USER
1739 && !$tmpBlock->isExpired()
1740 && $tmpBlock->isAutoblocking();
1741 $config = RequestContext
::getMain()->getConfig();
1742 $useBlockCookie = ( $config->get( 'CookieSetOnAutoblock' ) === true );
1743 if ( $blockIsValid && $useBlockCookie ) {
1745 $this->blockTrigger
= 'cookie-block';
1748 // If the block is not valid, remove the cookie.
1749 Block
::clearCookie( $this->getRequest()->response() );
1752 // If the block doesn't exist, remove the cookie.
1753 Block
::clearCookie( $this->getRequest()->response() );
1760 * Whether the given IP is in a DNS blacklist.
1762 * @param string $ip IP to check
1763 * @param bool $checkWhitelist Whether to check the whitelist first
1764 * @return bool True if blacklisted.
1766 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1767 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1769 if ( !$wgEnableDnsBlacklist ) {
1773 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1777 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1781 * Whether the given IP is in a given DNS blacklist.
1783 * @param string $ip IP to check
1784 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1785 * @return bool True if blacklisted.
1787 public function inDnsBlacklist( $ip, $bases ) {
1789 // @todo FIXME: IPv6 ??? (https://bugs.php.net/bug.php?id=33170)
1790 if ( IP
::isIPv4( $ip ) ) {
1791 // Reverse IP, T23255
1792 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1794 foreach ( (array)$bases as $base ) {
1796 // If we have an access key, use that too (ProjectHoneypot, etc.)
1798 if ( is_array( $base ) ) {
1799 if ( count( $base ) >= 2 ) {
1800 // Access key is 1, base URL is 0
1801 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1803 $host = "$ipReversed.{$base[0]}";
1805 $basename = $base[0];
1807 $host = "$ipReversed.$base";
1811 $ipList = gethostbynamel( $host );
1814 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
1818 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
1827 * Check if an IP address is in the local proxy list
1833 public static function isLocallyBlockedProxy( $ip ) {
1834 global $wgProxyList;
1836 if ( !$wgProxyList ) {
1840 if ( !is_array( $wgProxyList ) ) {
1841 // Load values from the specified file
1842 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1845 if ( is_array( $wgProxyList ) ) {
1847 // Look for IP as value
1848 array_search( $ip, $wgProxyList ) !== false ||
1849 // Look for IP as key (for backwards-compatility)
1850 array_key_exists( $ip, $wgProxyList )
1860 * Is this user subject to rate limiting?
1862 * @return bool True if rate limited
1864 public function isPingLimitable() {
1865 global $wgRateLimitsExcludedIPs;
1866 if ( IP
::isInRanges( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1867 // No other good way currently to disable rate limits
1868 // for specific IPs. :P
1869 // But this is a crappy hack and should die.
1872 return !$this->isAllowed( 'noratelimit' );
1876 * Primitive rate limits: enforce maximum actions per time period
1877 * to put a brake on flooding.
1879 * The method generates both a generic profiling point and a per action one
1880 * (suffix being "-$action".
1882 * @note When using a shared cache like memcached, IP-address
1883 * last-hit counters will be shared across wikis.
1885 * @param string $action Action to enforce; 'edit' if unspecified
1886 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1887 * @return bool True if a rate limiter was tripped
1889 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1890 // Avoid PHP 7.1 warning of passing $this by reference
1892 // Call the 'PingLimiter' hook
1894 if ( !Hooks
::run( 'PingLimiter', [ &$user, $action, &$result, $incrBy ] ) ) {
1898 global $wgRateLimits;
1899 if ( !isset( $wgRateLimits[$action] ) ) {
1903 $limits = array_merge(
1904 [ '&can-bypass' => true ],
1905 $wgRateLimits[$action]
1908 // Some groups shouldn't trigger the ping limiter, ever
1909 if ( $limits['&can-bypass'] && !$this->isPingLimitable() ) {
1914 $id = $this->getId();
1916 $isNewbie = $this->isNewbie();
1920 if ( isset( $limits['anon'] ) ) {
1921 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1924 // limits for logged-in users
1925 if ( isset( $limits['user'] ) ) {
1926 $userLimit = $limits['user'];
1928 // limits for newbie logged-in users
1929 if ( $isNewbie && isset( $limits['newbie'] ) ) {
1930 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1934 // limits for anons and for newbie logged-in users
1937 if ( isset( $limits['ip'] ) ) {
1938 $ip = $this->getRequest()->getIP();
1939 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1941 // subnet-based limits
1942 if ( isset( $limits['subnet'] ) ) {
1943 $ip = $this->getRequest()->getIP();
1944 $subnet = IP
::getSubnet( $ip );
1945 if ( $subnet !== false ) {
1946 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1951 // Check for group-specific permissions
1952 // If more than one group applies, use the group with the highest limit ratio (max/period)
1953 foreach ( $this->getGroups() as $group ) {
1954 if ( isset( $limits[$group] ) ) {
1955 if ( $userLimit === false
1956 ||
$limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1958 $userLimit = $limits[$group];
1963 // Set the user limit key
1964 if ( $userLimit !== false ) {
1965 list( $max, $period ) = $userLimit;
1966 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
1967 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1970 // ip-based limits for all ping-limitable users
1971 if ( isset( $limits['ip-all'] ) ) {
1972 $ip = $this->getRequest()->getIP();
1973 // ignore if user limit is more permissive
1974 if ( $isNewbie ||
$userLimit === false
1975 ||
$limits['ip-all'][0] / $limits['ip-all'][1] > $userLimit[0] / $userLimit[1] ) {
1976 $keys["mediawiki:limiter:$action:ip-all:$ip"] = $limits['ip-all'];
1980 // subnet-based limits for all ping-limitable users
1981 if ( isset( $limits['subnet-all'] ) ) {
1982 $ip = $this->getRequest()->getIP();
1983 $subnet = IP
::getSubnet( $ip );
1984 if ( $subnet !== false ) {
1985 // ignore if user limit is more permissive
1986 if ( $isNewbie ||
$userLimit === false
1987 ||
$limits['ip-all'][0] / $limits['ip-all'][1]
1988 > $userLimit[0] / $userLimit[1] ) {
1989 $keys["mediawiki:limiter:$action:subnet-all:$subnet"] = $limits['subnet-all'];
1994 $cache = ObjectCache
::getLocalClusterInstance();
1997 foreach ( $keys as $key => $limit ) {
1998 list( $max, $period ) = $limit;
1999 $summary = "(limit $max in {$period}s)";
2000 $count = $cache->get( $key );
2003 if ( $count >= $max ) {
2004 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
2005 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
2008 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
2011 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
2012 if ( $incrBy > 0 ) {
2013 $cache->add( $key, 0, intval( $period ) ); // first ping
2016 if ( $incrBy > 0 ) {
2017 $cache->incr( $key, $incrBy );
2025 * Check if user is blocked
2027 * @param bool $bFromSlave Whether to check the replica DB instead of
2028 * the master. Hacked from false due to horrible probs on site.
2029 * @return bool True if blocked, false otherwise
2031 public function isBlocked( $bFromSlave = true ) {
2032 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
2036 * Get the block affecting the user, or null if the user is not blocked
2038 * @param bool $bFromSlave Whether to check the replica DB instead of the master
2039 * @return Block|null
2041 public function getBlock( $bFromSlave = true ) {
2042 $this->getBlockedStatus( $bFromSlave );
2043 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
2047 * Check if user is blocked from editing a particular article
2049 * @param Title $title Title to check
2050 * @param bool $bFromSlave Whether to check the replica DB instead of the master
2053 public function isBlockedFrom( $title, $bFromSlave = false ) {
2054 global $wgBlockAllowsUTEdit;
2056 $blocked = $this->isBlocked( $bFromSlave );
2057 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
2058 // If a user's name is suppressed, they cannot make edits anywhere
2059 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName()
2060 && $title->getNamespace() == NS_USER_TALK
) {
2062 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
2065 Hooks
::run( 'UserIsBlockedFrom', [ $this, $title, &$blocked, &$allowUsertalk ] );
2071 * If user is blocked, return the name of the user who placed the block
2072 * @return string Name of blocker
2074 public function blockedBy() {
2075 $this->getBlockedStatus();
2076 return $this->mBlockedby
;
2080 * If user is blocked, return the specified reason for the block
2081 * @return string Blocking reason
2083 public function blockedFor() {
2084 $this->getBlockedStatus();
2085 return $this->mBlockreason
;
2089 * If user is blocked, return the ID for the block
2090 * @return int Block ID
2092 public function getBlockId() {
2093 $this->getBlockedStatus();
2094 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
2098 * Check if user is blocked on all wikis.
2099 * Do not use for actual edit permission checks!
2100 * This is intended for quick UI checks.
2102 * @param string $ip IP address, uses current client if none given
2103 * @return bool True if blocked, false otherwise
2105 public function isBlockedGlobally( $ip = '' ) {
2106 return $this->getGlobalBlock( $ip ) instanceof Block
;
2110 * Check if user is blocked on all wikis.
2111 * Do not use for actual edit permission checks!
2112 * This is intended for quick UI checks.
2114 * @param string $ip IP address, uses current client if none given
2115 * @return Block|null Block object if blocked, null otherwise
2116 * @throws FatalError
2117 * @throws MWException
2119 public function getGlobalBlock( $ip = '' ) {
2120 if ( $this->mGlobalBlock
!== null ) {
2121 return $this->mGlobalBlock ?
: null;
2123 // User is already an IP?
2124 if ( IP
::isIPAddress( $this->getName() ) ) {
2125 $ip = $this->getName();
2127 $ip = $this->getRequest()->getIP();
2129 // Avoid PHP 7.1 warning of passing $this by reference
2133 Hooks
::run( 'UserIsBlockedGlobally', [ &$user, $ip, &$blocked, &$block ] );
2135 if ( $blocked && $block === null ) {
2136 // back-compat: UserIsBlockedGlobally didn't have $block param first
2137 $block = new Block( [
2139 'systemBlock' => 'global-block'
2143 $this->mGlobalBlock
= $blocked ?
$block : false;
2144 return $this->mGlobalBlock ?
: null;
2148 * Check if user account is locked
2150 * @return bool True if locked, false otherwise
2152 public function isLocked() {
2153 if ( $this->mLocked
!== null ) {
2154 return $this->mLocked
;
2156 // Avoid PHP 7.1 warning of passing $this by reference
2158 $authUser = AuthManager
::callLegacyAuthPlugin( 'getUserInstance', [ &$user ], null );
2159 $this->mLocked
= $authUser && $authUser->isLocked();
2160 Hooks
::run( 'UserIsLocked', [ $this, &$this->mLocked
] );
2161 return $this->mLocked
;
2165 * Check if user account is hidden
2167 * @return bool True if hidden, false otherwise
2169 public function isHidden() {
2170 if ( $this->mHideName
!== null ) {
2171 return $this->mHideName
;
2173 $this->getBlockedStatus();
2174 if ( !$this->mHideName
) {
2175 // Avoid PHP 7.1 warning of passing $this by reference
2177 $authUser = AuthManager
::callLegacyAuthPlugin( 'getUserInstance', [ &$user ], null );
2178 $this->mHideName
= $authUser && $authUser->isHidden();
2179 Hooks
::run( 'UserIsHidden', [ $this, &$this->mHideName
] );
2181 return $this->mHideName
;
2185 * Get the user's ID.
2186 * @return int The user's ID; 0 if the user is anonymous or nonexistent
2188 public function getId() {
2189 if ( $this->mId
=== null && $this->mName
!== null && User
::isIP( $this->mName
) ) {
2190 // Special case, we know the user is anonymous
2192 } elseif ( !$this->isItemLoaded( 'id' ) ) {
2193 // Don't load if this was initialized from an ID
2197 return (int)$this->mId
;
2201 * Set the user and reload all fields according to a given ID
2202 * @param int $v User ID to reload
2204 public function setId( $v ) {
2206 $this->clearInstanceCache( 'id' );
2210 * Get the user name, or the IP of an anonymous user
2211 * @return string User's name or IP address
2213 public function getName() {
2214 if ( $this->isItemLoaded( 'name', 'only' ) ) {
2215 // Special case optimisation
2216 return $this->mName
;
2219 if ( $this->mName
=== false ) {
2221 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
2223 return $this->mName
;
2228 * Set the user name.
2230 * This does not reload fields from the database according to the given
2231 * name. Rather, it is used to create a temporary "nonexistent user" for
2232 * later addition to the database. It can also be used to set the IP
2233 * address for an anonymous user to something other than the current
2236 * @note User::newFromName() has roughly the same function, when the named user
2238 * @param string $str New user name to set
2240 public function setName( $str ) {
2242 $this->mName
= $str;
2246 * Get the user's name escaped by underscores.
2247 * @return string Username escaped by underscores.
2249 public function getTitleKey() {
2250 return str_replace( ' ', '_', $this->getName() );
2254 * Check if the user has new messages.
2255 * @return bool True if the user has new messages
2257 public function getNewtalk() {
2260 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2261 if ( $this->mNewtalk
=== -1 ) {
2262 $this->mNewtalk
= false; # reset talk page status
2264 // Check memcached separately for anons, who have no
2265 // entire User object stored in there.
2266 if ( !$this->mId
) {
2267 global $wgDisableAnonTalk;
2268 if ( $wgDisableAnonTalk ) {
2269 // Anon newtalk disabled by configuration.
2270 $this->mNewtalk
= false;
2272 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
2275 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2279 return (bool)$this->mNewtalk
;
2283 * Return the data needed to construct links for new talk page message
2284 * alerts. If there are new messages, this will return an associative array
2285 * with the following data:
2286 * wiki: The database name of the wiki
2287 * link: Root-relative link to the user's talk page
2288 * rev: The last talk page revision that the user has seen or null. This
2289 * is useful for building diff links.
2290 * If there are no new messages, it returns an empty array.
2291 * @note This function was designed to accomodate multiple talk pages, but
2292 * currently only returns a single link and revision.
2295 public function getNewMessageLinks() {
2296 // Avoid PHP 7.1 warning of passing $this by reference
2299 if ( !Hooks
::run( 'UserRetrieveNewTalks', [ &$user, &$talks ] ) ) {
2301 } elseif ( !$this->getNewtalk() ) {
2304 $utp = $this->getTalkPage();
2305 $dbr = wfGetDB( DB_REPLICA
);
2306 // Get the "last viewed rev" timestamp from the oldest message notification
2307 $timestamp = $dbr->selectField( 'user_newtalk',
2308 'MIN(user_last_timestamp)',
2309 $this->isAnon() ?
[ 'user_ip' => $this->getName() ] : [ 'user_id' => $this->getId() ],
2311 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2312 return [ [ 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ] ];
2316 * Get the revision ID for the last talk page revision viewed by the talk
2318 * @return int|null Revision ID or null
2320 public function getNewMessageRevisionId() {
2321 $newMessageRevisionId = null;
2322 $newMessageLinks = $this->getNewMessageLinks();
2323 if ( $newMessageLinks ) {
2324 // Note: getNewMessageLinks() never returns more than a single link
2325 // and it is always for the same wiki, but we double-check here in
2326 // case that changes some time in the future.
2327 if ( count( $newMessageLinks ) === 1
2328 && $newMessageLinks[0]['wiki'] === wfWikiID()
2329 && $newMessageLinks[0]['rev']
2331 /** @var Revision $newMessageRevision */
2332 $newMessageRevision = $newMessageLinks[0]['rev'];
2333 $newMessageRevisionId = $newMessageRevision->getId();
2336 return $newMessageRevisionId;
2340 * Internal uncached check for new messages
2343 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2344 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2345 * @return bool True if the user has new messages
2347 protected function checkNewtalk( $field, $id ) {
2348 $dbr = wfGetDB( DB_REPLICA
);
2350 $ok = $dbr->selectField( 'user_newtalk', $field, [ $field => $id ], __METHOD__
);
2352 return $ok !== false;
2356 * Add or update the new messages flag
2357 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2358 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2359 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2360 * @return bool True if successful, false otherwise
2362 protected function updateNewtalk( $field, $id, $curRev = null ) {
2363 // Get timestamp of the talk page revision prior to the current one
2364 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2365 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2366 // Mark the user as having new messages since this revision
2367 $dbw = wfGetDB( DB_MASTER
);
2368 $dbw->insert( 'user_newtalk',
2369 [ $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ],
2372 if ( $dbw->affectedRows() ) {
2373 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2376 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2382 * Clear the new messages flag for the given user
2383 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2384 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2385 * @return bool True if successful, false otherwise
2387 protected function deleteNewtalk( $field, $id ) {
2388 $dbw = wfGetDB( DB_MASTER
);
2389 $dbw->delete( 'user_newtalk',
2392 if ( $dbw->affectedRows() ) {
2393 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2396 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2402 * Update the 'You have new messages!' status.
2403 * @param bool $val Whether the user has new messages
2404 * @param Revision $curRev New, as yet unseen revision of the user talk
2405 * page. Ignored if null or !$val.
2407 public function setNewtalk( $val, $curRev = null ) {
2408 if ( wfReadOnly() ) {
2413 $this->mNewtalk
= $val;
2415 if ( $this->isAnon() ) {
2417 $id = $this->getName();
2420 $id = $this->getId();
2424 $changed = $this->updateNewtalk( $field, $id, $curRev );
2426 $changed = $this->deleteNewtalk( $field, $id );
2430 $this->invalidateCache();
2435 * Generate a current or new-future timestamp to be stored in the
2436 * user_touched field when we update things.
2437 * @return string Timestamp in TS_MW format
2439 private function newTouchedTimestamp() {
2440 global $wgClockSkewFudge;
2442 $time = wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2443 if ( $this->mTouched
&& $time <= $this->mTouched
) {
2444 $time = wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $this->mTouched
) +
1 );
2451 * Clear user data from memcached
2453 * Use after applying updates to the database; caller's
2454 * responsibility to update user_touched if appropriate.
2456 * Called implicitly from invalidateCache() and saveSettings().
2458 * @param string $mode Use 'refresh' to clear now; otherwise before DB commit
2460 public function clearSharedCache( $mode = 'changed' ) {
2461 if ( !$this->getId() ) {
2465 $cache = ObjectCache
::getMainWANInstance();
2466 $key = $this->getCacheKey( $cache );
2467 if ( $mode === 'refresh' ) {
2468 $cache->delete( $key, 1 );
2470 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle(
2471 function() use ( $cache, $key ) {
2472 $cache->delete( $key );
2480 * Immediately touch the user data cache for this account
2482 * Calls touch() and removes account data from memcached
2484 public function invalidateCache() {
2486 $this->clearSharedCache();
2490 * Update the "touched" timestamp for the user
2492 * This is useful on various login/logout events when making sure that
2493 * a browser or proxy that has multiple tenants does not suffer cache
2494 * pollution where the new user sees the old users content. The value
2495 * of getTouched() is checked when determining 304 vs 200 responses.
2496 * Unlike invalidateCache(), this preserves the User object cache and
2497 * avoids database writes.
2501 public function touch() {
2502 $id = $this->getId();
2504 $key = wfMemcKey( 'user-quicktouched', 'id', $id );
2505 ObjectCache
::getMainWANInstance()->touchCheckKey( $key );
2506 $this->mQuickTouched
= null;
2511 * Validate the cache for this account.
2512 * @param string $timestamp A timestamp in TS_MW format
2515 public function validateCache( $timestamp ) {
2516 return ( $timestamp >= $this->getTouched() );
2520 * Get the user touched timestamp
2522 * Use this value only to validate caches via inequalities
2523 * such as in the case of HTTP If-Modified-Since response logic
2525 * @return string TS_MW Timestamp
2527 public function getTouched() {
2531 if ( $this->mQuickTouched
=== null ) {
2532 $key = wfMemcKey( 'user-quicktouched', 'id', $this->mId
);
2533 $cache = ObjectCache
::getMainWANInstance();
2535 $this->mQuickTouched
= wfTimestamp( TS_MW
, $cache->getCheckKeyTime( $key ) );
2538 return max( $this->mTouched
, $this->mQuickTouched
);
2541 return $this->mTouched
;
2545 * Get the user_touched timestamp field (time of last DB updates)
2546 * @return string TS_MW Timestamp
2549 public function getDBTouched() {
2552 return $this->mTouched
;
2556 * Set the password and reset the random token.
2557 * Calls through to authentication plugin if necessary;
2558 * will have no effect if the auth plugin refuses to
2559 * pass the change through or if the legal password
2562 * As a special case, setting the password to null
2563 * wipes it, so the account cannot be logged in until
2564 * a new password is set, for instance via e-mail.
2566 * @deprecated since 1.27, use AuthManager instead
2567 * @param string $str New password to set
2568 * @throws PasswordError On failure
2571 public function setPassword( $str ) {
2572 return $this->setPasswordInternal( $str );
2576 * Set the password and reset the random token unconditionally.
2578 * @deprecated since 1.27, use AuthManager instead
2579 * @param string|null $str New password to set or null to set an invalid
2580 * password hash meaning that the user will not be able to log in
2581 * through the web interface.
2583 public function setInternalPassword( $str ) {
2584 $this->setPasswordInternal( $str );
2588 * Actually set the password and such
2589 * @since 1.27 cannot set a password for a user not in the database
2590 * @param string|null $str New password to set or null to set an invalid
2591 * password hash meaning that the user will not be able to log in
2592 * through the web interface.
2593 * @return bool Success
2595 private function setPasswordInternal( $str ) {
2596 $manager = AuthManager
::singleton();
2598 // If the user doesn't exist yet, fail
2599 if ( !$manager->userExists( $this->getName() ) ) {
2600 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2603 $status = $this->changeAuthenticationData( [
2604 'username' => $this->getName(),
2608 if ( !$status->isGood() ) {
2609 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
2610 ->info( __METHOD__
. ': Password change rejected: '
2611 . $status->getWikiText( null, null, 'en' ) );
2615 $this->setOption( 'watchlisttoken', false );
2616 SessionManager
::singleton()->invalidateSessionsForUser( $this );
2622 * Changes credentials of the user.
2624 * This is a convenience wrapper around AuthManager::changeAuthenticationData.
2625 * Note that this can return a status that isOK() but not isGood() on certain types of failures,
2626 * e.g. when no provider handled the change.
2628 * @param array $data A set of authentication data in fieldname => value format. This is the
2629 * same data you would pass the changeauthenticationdata API - 'username', 'password' etc.
2633 public function changeAuthenticationData( array $data ) {
2634 $manager = AuthManager
::singleton();
2635 $reqs = $manager->getAuthenticationRequests( AuthManager
::ACTION_CHANGE
, $this );
2636 $reqs = AuthenticationRequest
::loadRequestsFromSubmission( $reqs, $data );
2638 $status = Status
::newGood( 'ignored' );
2639 foreach ( $reqs as $req ) {
2640 $status->merge( $manager->allowsAuthenticationDataChange( $req ), true );
2642 if ( $status->getValue() === 'ignored' ) {
2643 $status->warning( 'authenticationdatachange-ignored' );
2646 if ( $status->isGood() ) {
2647 foreach ( $reqs as $req ) {
2648 $manager->changeAuthenticationData( $req );
2655 * Get the user's current token.
2656 * @param bool $forceCreation Force the generation of a new token if the
2657 * user doesn't have one (default=true for backwards compatibility).
2658 * @return string|null Token
2660 public function getToken( $forceCreation = true ) {
2661 global $wgAuthenticationTokenVersion;
2664 if ( !$this->mToken
&& $forceCreation ) {
2668 if ( !$this->mToken
) {
2669 // The user doesn't have a token, return null to indicate that.
2671 } elseif ( $this->mToken
=== self
::INVALID_TOKEN
) {
2672 // We return a random value here so existing token checks are very
2674 return MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2675 } elseif ( $wgAuthenticationTokenVersion === null ) {
2676 // $wgAuthenticationTokenVersion not in use, so return the raw secret
2677 return $this->mToken
;
2679 // $wgAuthenticationTokenVersion in use, so hmac it.
2680 $ret = MWCryptHash
::hmac( $wgAuthenticationTokenVersion, $this->mToken
, false );
2682 // The raw hash can be overly long. Shorten it up.
2683 $len = max( 32, self
::TOKEN_LENGTH
);
2684 if ( strlen( $ret ) < $len ) {
2685 // Should never happen, even md5 is 128 bits
2686 throw new \
UnexpectedValueException( 'Hmac returned less than 128 bits' );
2688 return substr( $ret, -$len );
2693 * Set the random token (used for persistent authentication)
2694 * Called from loadDefaults() among other places.
2696 * @param string|bool $token If specified, set the token to this value
2698 public function setToken( $token = false ) {
2700 if ( $this->mToken
=== self
::INVALID_TOKEN
) {
2701 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
2702 ->debug( __METHOD__
. ": Ignoring attempt to set token for system user \"$this\"" );
2703 } elseif ( !$token ) {
2704 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2706 $this->mToken
= $token;
2711 * Set the password for a password reminder or new account email
2713 * @deprecated Removed in 1.27. Use PasswordReset instead.
2714 * @param string $str New password to set or null to set an invalid
2715 * password hash meaning that the user will not be able to use it
2716 * @param bool $throttle If true, reset the throttle timestamp to the present
2718 public function setNewpassword( $str, $throttle = true ) {
2719 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2723 * Get the user's e-mail address
2724 * @return string User's email address
2726 public function getEmail() {
2728 Hooks
::run( 'UserGetEmail', [ $this, &$this->mEmail
] );
2729 return $this->mEmail
;
2733 * Get the timestamp of the user's e-mail authentication
2734 * @return string TS_MW timestamp
2736 public function getEmailAuthenticationTimestamp() {
2738 Hooks
::run( 'UserGetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
2739 return $this->mEmailAuthenticated
;
2743 * Set the user's e-mail address
2744 * @param string $str New e-mail address
2746 public function setEmail( $str ) {
2748 if ( $str == $this->mEmail
) {
2751 $this->invalidateEmail();
2752 $this->mEmail
= $str;
2753 Hooks
::run( 'UserSetEmail', [ $this, &$this->mEmail
] );
2757 * Set the user's e-mail address and a confirmation mail if needed.
2760 * @param string $str New e-mail address
2763 public function setEmailWithConfirmation( $str ) {
2764 global $wgEnableEmail, $wgEmailAuthentication;
2766 if ( !$wgEnableEmail ) {
2767 return Status
::newFatal( 'emaildisabled' );
2770 $oldaddr = $this->getEmail();
2771 if ( $str === $oldaddr ) {
2772 return Status
::newGood( true );
2775 $type = $oldaddr != '' ?
'changed' : 'set';
2776 $notificationResult = null;
2778 if ( $wgEmailAuthentication ) {
2779 // Send the user an email notifying the user of the change in registered
2780 // email address on their previous email address
2781 if ( $type == 'changed' ) {
2782 $change = $str != '' ?
'changed' : 'removed';
2783 $notificationResult = $this->sendMail(
2784 wfMessage( 'notificationemail_subject_' . $change )->text(),
2785 wfMessage( 'notificationemail_body_' . $change,
2786 $this->getRequest()->getIP(),
2793 $this->setEmail( $str );
2795 if ( $str !== '' && $wgEmailAuthentication ) {
2796 // Send a confirmation request to the new address if needed
2797 $result = $this->sendConfirmationMail( $type );
2799 if ( $notificationResult !== null ) {
2800 $result->merge( $notificationResult );
2803 if ( $result->isGood() ) {
2804 // Say to the caller that a confirmation and notification mail has been sent
2805 $result->value
= 'eauth';
2808 $result = Status
::newGood( true );
2815 * Get the user's real name
2816 * @return string User's real name
2818 public function getRealName() {
2819 if ( !$this->isItemLoaded( 'realname' ) ) {
2823 return $this->mRealName
;
2827 * Set the user's real name
2828 * @param string $str New real name
2830 public function setRealName( $str ) {
2832 $this->mRealName
= $str;
2836 * Get the user's current setting for a given option.
2838 * @param string $oname The option to check
2839 * @param string $defaultOverride A default value returned if the option does not exist
2840 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2841 * @return string|null User's current value for the option
2842 * @see getBoolOption()
2843 * @see getIntOption()
2845 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2846 global $wgHiddenPrefs;
2847 $this->loadOptions();
2849 # We want 'disabled' preferences to always behave as the default value for
2850 # users, even if they have set the option explicitly in their settings (ie they
2851 # set it, and then it was disabled removing their ability to change it). But
2852 # we don't want to erase the preferences in the database in case the preference
2853 # is re-enabled again. So don't touch $mOptions, just override the returned value
2854 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2855 return self
::getDefaultOption( $oname );
2858 if ( array_key_exists( $oname, $this->mOptions
) ) {
2859 return $this->mOptions
[$oname];
2861 return $defaultOverride;
2866 * Get all user's options
2868 * @param int $flags Bitwise combination of:
2869 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2870 * to the default value. (Since 1.25)
2873 public function getOptions( $flags = 0 ) {
2874 global $wgHiddenPrefs;
2875 $this->loadOptions();
2876 $options = $this->mOptions
;
2878 # We want 'disabled' preferences to always behave as the default value for
2879 # users, even if they have set the option explicitly in their settings (ie they
2880 # set it, and then it was disabled removing their ability to change it). But
2881 # we don't want to erase the preferences in the database in case the preference
2882 # is re-enabled again. So don't touch $mOptions, just override the returned value
2883 foreach ( $wgHiddenPrefs as $pref ) {
2884 $default = self
::getDefaultOption( $pref );
2885 if ( $default !== null ) {
2886 $options[$pref] = $default;
2890 if ( $flags & self
::GETOPTIONS_EXCLUDE_DEFAULTS
) {
2891 $options = array_diff_assoc( $options, self
::getDefaultOptions() );
2898 * Get the user's current setting for a given option, as a boolean value.
2900 * @param string $oname The option to check
2901 * @return bool User's current value for the option
2904 public function getBoolOption( $oname ) {
2905 return (bool)$this->getOption( $oname );
2909 * Get the user's current setting for a given option, as an integer value.
2911 * @param string $oname The option to check
2912 * @param int $defaultOverride A default value returned if the option does not exist
2913 * @return int User's current value for the option
2916 public function getIntOption( $oname, $defaultOverride = 0 ) {
2917 $val = $this->getOption( $oname );
2919 $val = $defaultOverride;
2921 return intval( $val );
2925 * Set the given option for a user.
2927 * You need to call saveSettings() to actually write to the database.
2929 * @param string $oname The option to set
2930 * @param mixed $val New value to set
2932 public function setOption( $oname, $val ) {
2933 $this->loadOptions();
2935 // Explicitly NULL values should refer to defaults
2936 if ( is_null( $val ) ) {
2937 $val = self
::getDefaultOption( $oname );
2940 $this->mOptions
[$oname] = $val;
2944 * Get a token stored in the preferences (like the watchlist one),
2945 * resetting it if it's empty (and saving changes).
2947 * @param string $oname The option name to retrieve the token from
2948 * @return string|bool User's current value for the option, or false if this option is disabled.
2949 * @see resetTokenFromOption()
2951 * @deprecated since 1.26 Applications should use the OAuth extension
2953 public function getTokenFromOption( $oname ) {
2954 global $wgHiddenPrefs;
2956 $id = $this->getId();
2957 if ( !$id ||
in_array( $oname, $wgHiddenPrefs ) ) {
2961 $token = $this->getOption( $oname );
2963 // Default to a value based on the user token to avoid space
2964 // wasted on storing tokens for all users. When this option
2965 // is set manually by the user, only then is it stored.
2966 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
2973 * Reset a token stored in the preferences (like the watchlist one).
2974 * *Does not* save user's preferences (similarly to setOption()).
2976 * @param string $oname The option name to reset the token in
2977 * @return string|bool New token value, or false if this option is disabled.
2978 * @see getTokenFromOption()
2981 public function resetTokenFromOption( $oname ) {
2982 global $wgHiddenPrefs;
2983 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2987 $token = MWCryptRand
::generateHex( 40 );
2988 $this->setOption( $oname, $token );
2993 * Return a list of the types of user options currently returned by
2994 * User::getOptionKinds().
2996 * Currently, the option kinds are:
2997 * - 'registered' - preferences which are registered in core MediaWiki or
2998 * by extensions using the UserGetDefaultOptions hook.
2999 * - 'registered-multiselect' - as above, using the 'multiselect' type.
3000 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
3001 * - 'userjs' - preferences with names starting with 'userjs-', intended to
3002 * be used by user scripts.
3003 * - 'special' - "preferences" that are not accessible via User::getOptions
3004 * or User::setOptions.
3005 * - 'unused' - preferences about which MediaWiki doesn't know anything.
3006 * These are usually legacy options, removed in newer versions.
3008 * The API (and possibly others) use this function to determine the possible
3009 * option types for validation purposes, so make sure to update this when a
3010 * new option kind is added.
3012 * @see User::getOptionKinds
3013 * @return array Option kinds
3015 public static function listOptionKinds() {
3018 'registered-multiselect',
3019 'registered-checkmatrix',
3027 * Return an associative array mapping preferences keys to the kind of a preference they're
3028 * used for. Different kinds are handled differently when setting or reading preferences.
3030 * See User::listOptionKinds for the list of valid option types that can be provided.
3032 * @see User::listOptionKinds
3033 * @param IContextSource $context
3034 * @param array $options Assoc. array with options keys to check as keys.
3035 * Defaults to $this->mOptions.
3036 * @return array The key => kind mapping data
3038 public function getOptionKinds( IContextSource
$context, $options = null ) {
3039 $this->loadOptions();
3040 if ( $options === null ) {
3041 $options = $this->mOptions
;
3044 $prefs = Preferences
::getPreferences( $this, $context );
3047 // Pull out the "special" options, so they don't get converted as
3048 // multiselect or checkmatrix.
3049 $specialOptions = array_fill_keys( Preferences
::getSaveBlacklist(), true );
3050 foreach ( $specialOptions as $name => $value ) {
3051 unset( $prefs[$name] );
3054 // Multiselect and checkmatrix options are stored in the database with
3055 // one key per option, each having a boolean value. Extract those keys.
3056 $multiselectOptions = [];
3057 foreach ( $prefs as $name => $info ) {
3058 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
3059 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
3060 $opts = HTMLFormField
::flattenOptions( $info['options'] );
3061 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
3063 foreach ( $opts as $value ) {
3064 $multiselectOptions["$prefix$value"] = true;
3067 unset( $prefs[$name] );
3070 $checkmatrixOptions = [];
3071 foreach ( $prefs as $name => $info ) {
3072 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
3073 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
3074 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
3075 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
3076 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
3078 foreach ( $columns as $column ) {
3079 foreach ( $rows as $row ) {
3080 $checkmatrixOptions["$prefix$column-$row"] = true;
3084 unset( $prefs[$name] );
3088 // $value is ignored
3089 foreach ( $options as $key => $value ) {
3090 if ( isset( $prefs[$key] ) ) {
3091 $mapping[$key] = 'registered';
3092 } elseif ( isset( $multiselectOptions[$key] ) ) {
3093 $mapping[$key] = 'registered-multiselect';
3094 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
3095 $mapping[$key] = 'registered-checkmatrix';
3096 } elseif ( isset( $specialOptions[$key] ) ) {
3097 $mapping[$key] = 'special';
3098 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
3099 $mapping[$key] = 'userjs';
3101 $mapping[$key] = 'unused';
3109 * Reset certain (or all) options to the site defaults
3111 * The optional parameter determines which kinds of preferences will be reset.
3112 * Supported values are everything that can be reported by getOptionKinds()
3113 * and 'all', which forces a reset of *all* preferences and overrides everything else.
3115 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
3116 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
3117 * for backwards-compatibility.
3118 * @param IContextSource|null $context Context source used when $resetKinds
3119 * does not contain 'all', passed to getOptionKinds().
3120 * Defaults to RequestContext::getMain() when null.
3122 public function resetOptions(
3123 $resetKinds = [ 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ],
3124 IContextSource
$context = null
3127 $defaultOptions = self
::getDefaultOptions();
3129 if ( !is_array( $resetKinds ) ) {
3130 $resetKinds = [ $resetKinds ];
3133 if ( in_array( 'all', $resetKinds ) ) {
3134 $newOptions = $defaultOptions;
3136 if ( $context === null ) {
3137 $context = RequestContext
::getMain();
3140 $optionKinds = $this->getOptionKinds( $context );
3141 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
3144 // Use default values for the options that should be deleted, and
3145 // copy old values for the ones that shouldn't.
3146 foreach ( $this->mOptions
as $key => $value ) {
3147 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
3148 if ( array_key_exists( $key, $defaultOptions ) ) {
3149 $newOptions[$key] = $defaultOptions[$key];
3152 $newOptions[$key] = $value;
3157 Hooks
::run( 'UserResetAllOptions', [ $this, &$newOptions, $this->mOptions
, $resetKinds ] );
3159 $this->mOptions
= $newOptions;
3160 $this->mOptionsLoaded
= true;
3164 * Get the user's preferred date format.
3165 * @return string User's preferred date format
3167 public function getDatePreference() {
3168 // Important migration for old data rows
3169 if ( is_null( $this->mDatePreference
) ) {
3171 $value = $this->getOption( 'date' );
3172 $map = $wgLang->getDatePreferenceMigrationMap();
3173 if ( isset( $map[$value] ) ) {
3174 $value = $map[$value];
3176 $this->mDatePreference
= $value;
3178 return $this->mDatePreference
;
3182 * Determine based on the wiki configuration and the user's options,
3183 * whether this user must be over HTTPS no matter what.
3187 public function requiresHTTPS() {
3188 global $wgSecureLogin;
3189 if ( !$wgSecureLogin ) {
3192 $https = $this->getBoolOption( 'prefershttps' );
3193 Hooks
::run( 'UserRequiresHTTPS', [ $this, &$https ] );
3195 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
3202 * Get the user preferred stub threshold
3206 public function getStubThreshold() {
3207 global $wgMaxArticleSize; # Maximum article size, in Kb
3208 $threshold = $this->getIntOption( 'stubthreshold' );
3209 if ( $threshold > $wgMaxArticleSize * 1024 ) {
3210 // If they have set an impossible value, disable the preference
3211 // so we can use the parser cache again.
3218 * Get the permissions this user has.
3219 * @return string[] permission names
3221 public function getRights() {
3222 if ( is_null( $this->mRights
) ) {
3223 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
3224 Hooks
::run( 'UserGetRights', [ $this, &$this->mRights
] );
3226 // Deny any rights denied by the user's session, unless this
3227 // endpoint has no sessions.
3228 if ( !defined( 'MW_NO_SESSION' ) ) {
3229 $allowedRights = $this->getRequest()->getSession()->getAllowedUserRights();
3230 if ( $allowedRights !== null ) {
3231 $this->mRights
= array_intersect( $this->mRights
, $allowedRights );
3235 // Force reindexation of rights when a hook has unset one of them
3236 $this->mRights
= array_values( array_unique( $this->mRights
) );
3238 // If block disables login, we should also remove any
3239 // extra rights blocked users might have, in case the
3240 // blocked user has a pre-existing session (T129738).
3241 // This is checked here for cases where people only call
3242 // $user->isAllowed(). It is also checked in Title::checkUserBlock()
3243 // to give a better error message in the common case.
3244 $config = RequestContext
::getMain()->getConfig();
3246 $this->isLoggedIn() &&
3247 $config->get( 'BlockDisablesLogin' ) &&
3251 $this->mRights
= array_intersect( $this->mRights
, $anon->getRights() );
3254 return $this->mRights
;
3258 * Get the list of explicit group memberships this user has.
3259 * The implicit * and user groups are not included.
3260 * @return array Array of String internal group names
3262 public function getGroups() {
3264 $this->loadGroups();
3265 return array_keys( $this->mGroupMemberships
);
3269 * Get the list of explicit group memberships this user has, stored as
3270 * UserGroupMembership objects. Implicit groups are not included.
3272 * @return array Associative array of (group name as string => UserGroupMembership object)
3275 public function getGroupMemberships() {
3277 $this->loadGroups();
3278 return $this->mGroupMemberships
;
3282 * Get the list of implicit group memberships this user has.
3283 * This includes all explicit groups, plus 'user' if logged in,
3284 * '*' for all accounts, and autopromoted groups
3285 * @param bool $recache Whether to avoid the cache
3286 * @return array Array of String internal group names
3288 public function getEffectiveGroups( $recache = false ) {
3289 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
3290 $this->mEffectiveGroups
= array_unique( array_merge(
3291 $this->getGroups(), // explicit groups
3292 $this->getAutomaticGroups( $recache ) // implicit groups
3294 // Avoid PHP 7.1 warning of passing $this by reference
3296 // Hook for additional groups
3297 Hooks
::run( 'UserEffectiveGroups', [ &$user, &$this->mEffectiveGroups
] );
3298 // Force reindexation of groups when a hook has unset one of them
3299 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
3301 return $this->mEffectiveGroups
;
3305 * Get the list of implicit group memberships this user has.
3306 * This includes 'user' if logged in, '*' for all accounts,
3307 * and autopromoted groups
3308 * @param bool $recache Whether to avoid the cache
3309 * @return array Array of String internal group names
3311 public function getAutomaticGroups( $recache = false ) {
3312 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
3313 $this->mImplicitGroups
= [ '*' ];
3314 if ( $this->getId() ) {
3315 $this->mImplicitGroups
[] = 'user';
3317 $this->mImplicitGroups
= array_unique( array_merge(
3318 $this->mImplicitGroups
,
3319 Autopromote
::getAutopromoteGroups( $this )
3323 // Assure data consistency with rights/groups,
3324 // as getEffectiveGroups() depends on this function
3325 $this->mEffectiveGroups
= null;
3328 return $this->mImplicitGroups
;
3332 * Returns the groups the user has belonged to.
3334 * The user may still belong to the returned groups. Compare with getGroups().
3336 * The function will not return groups the user had belonged to before MW 1.17
3338 * @return array Names of the groups the user has belonged to.
3340 public function getFormerGroups() {
3343 if ( is_null( $this->mFormerGroups
) ) {
3344 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3345 ?
wfGetDB( DB_MASTER
)
3346 : wfGetDB( DB_REPLICA
);
3347 $res = $db->select( 'user_former_groups',
3349 [ 'ufg_user' => $this->mId
],
3351 $this->mFormerGroups
= [];
3352 foreach ( $res as $row ) {
3353 $this->mFormerGroups
[] = $row->ufg_group
;
3357 return $this->mFormerGroups
;
3361 * Get the user's edit count.
3362 * @return int|null Null for anonymous users
3364 public function getEditCount() {
3365 if ( !$this->getId() ) {
3369 if ( $this->mEditCount
=== null ) {
3370 /* Populate the count, if it has not been populated yet */
3371 $dbr = wfGetDB( DB_REPLICA
);
3372 // check if the user_editcount field has been initialized
3373 $count = $dbr->selectField(
3374 'user', 'user_editcount',
3375 [ 'user_id' => $this->mId
],
3379 if ( $count === null ) {
3380 // it has not been initialized. do so.
3381 $count = $this->initEditCount();
3383 $this->mEditCount
= $count;
3385 return (int)$this->mEditCount
;
3389 * Add the user to the given group. This takes immediate effect.
3390 * If the user is already in the group, the expiry time will be updated to the new
3391 * expiry time. (If $expiry is omitted or null, the membership will be altered to
3394 * @param string $group Name of the group to add
3395 * @param string $expiry Optional expiry timestamp in any format acceptable to
3396 * wfTimestamp(), or null if the group assignment should not expire
3399 public function addGroup( $group, $expiry = null ) {
3401 $this->loadGroups();
3404 $expiry = wfTimestamp( TS_MW
, $expiry );
3407 if ( !Hooks
::run( 'UserAddGroup', [ $this, &$group, &$expiry ] ) ) {
3411 // create the new UserGroupMembership and put it in the DB
3412 $ugm = new UserGroupMembership( $this->mId
, $group, $expiry );
3413 if ( !$ugm->insert( true ) ) {
3417 $this->mGroupMemberships
[$group] = $ugm;
3419 // Refresh the groups caches, and clear the rights cache so it will be
3420 // refreshed on the next call to $this->getRights().
3421 $this->getEffectiveGroups( true );
3422 $this->mRights
= null;
3424 $this->invalidateCache();
3430 * Remove the user from the given group.
3431 * This takes immediate effect.
3432 * @param string $group Name of the group to remove
3435 public function removeGroup( $group ) {
3438 if ( !Hooks
::run( 'UserRemoveGroup', [ $this, &$group ] ) ) {
3442 $ugm = UserGroupMembership
::getMembership( $this->mId
, $group );
3443 // delete the membership entry
3444 if ( !$ugm ||
!$ugm->delete() ) {
3448 $this->loadGroups();
3449 unset( $this->mGroupMemberships
[$group] );
3451 // Refresh the groups caches, and clear the rights cache so it will be
3452 // refreshed on the next call to $this->getRights().
3453 $this->getEffectiveGroups( true );
3454 $this->mRights
= null;
3456 $this->invalidateCache();
3462 * Get whether the user is logged in
3465 public function isLoggedIn() {
3466 return $this->getId() != 0;
3470 * Get whether the user is anonymous
3473 public function isAnon() {
3474 return !$this->isLoggedIn();
3478 * @return bool Whether this user is flagged as being a bot role account
3481 public function isBot() {
3482 if ( in_array( 'bot', $this->getGroups() ) && $this->isAllowed( 'bot' ) ) {
3487 Hooks
::run( "UserIsBot", [ $this, &$isBot ] );
3493 * Check if user is allowed to access a feature / make an action
3495 * @param string ... Permissions to test
3496 * @return bool True if user is allowed to perform *any* of the given actions
3498 public function isAllowedAny() {
3499 $permissions = func_get_args();
3500 foreach ( $permissions as $permission ) {
3501 if ( $this->isAllowed( $permission ) ) {
3510 * @param string ... Permissions to test
3511 * @return bool True if the user is allowed to perform *all* of the given actions
3513 public function isAllowedAll() {
3514 $permissions = func_get_args();
3515 foreach ( $permissions as $permission ) {
3516 if ( !$this->isAllowed( $permission ) ) {
3524 * Internal mechanics of testing a permission
3525 * @param string $action
3528 public function isAllowed( $action = '' ) {
3529 if ( $action === '' ) {
3530 return true; // In the spirit of DWIM
3532 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3533 // by misconfiguration: 0 == 'foo'
3534 return in_array( $action, $this->getRights(), true );
3538 * Check whether to enable recent changes patrol features for this user
3539 * @return bool True or false
3541 public function useRCPatrol() {
3542 global $wgUseRCPatrol;
3543 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3547 * Check whether to enable new pages patrol features for this user
3548 * @return bool True or false
3550 public function useNPPatrol() {
3551 global $wgUseRCPatrol, $wgUseNPPatrol;
3553 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3554 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3559 * Check whether to enable new files patrol features for this user
3560 * @return bool True or false
3562 public function useFilePatrol() {
3563 global $wgUseRCPatrol, $wgUseFilePatrol;
3565 ( $wgUseRCPatrol ||
$wgUseFilePatrol )
3566 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3571 * Get the WebRequest object to use with this object
3573 * @return WebRequest
3575 public function getRequest() {
3576 if ( $this->mRequest
) {
3577 return $this->mRequest
;
3585 * Check the watched status of an article.
3586 * @since 1.22 $checkRights parameter added
3587 * @param Title $title Title of the article to look at
3588 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3589 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3592 public function isWatched( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3593 if ( $title->isWatchable() && ( !$checkRights ||
$this->isAllowed( 'viewmywatchlist' ) ) ) {
3594 return MediaWikiServices
::getInstance()->getWatchedItemStore()->isWatched( $this, $title );
3601 * @since 1.22 $checkRights parameter added
3602 * @param Title $title Title of the article to look at
3603 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3604 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3606 public function addWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3607 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3608 MediaWikiServices
::getInstance()->getWatchedItemStore()->addWatchBatchForUser(
3610 [ $title->getSubjectPage(), $title->getTalkPage() ]
3613 $this->invalidateCache();
3617 * Stop watching an article.
3618 * @since 1.22 $checkRights parameter added
3619 * @param Title $title Title of the article to look at
3620 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3621 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3623 public function removeWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3624 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3625 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
3626 $store->removeWatch( $this, $title->getSubjectPage() );
3627 $store->removeWatch( $this, $title->getTalkPage() );
3629 $this->invalidateCache();
3633 * Clear the user's notification timestamp for the given title.
3634 * If e-notif e-mails are on, they will receive notification mails on
3635 * the next change of the page if it's watched etc.
3636 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3637 * @param Title $title Title of the article to look at
3638 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3640 public function clearNotification( &$title, $oldid = 0 ) {
3641 global $wgUseEnotif, $wgShowUpdatedMarker;
3643 // Do nothing if the database is locked to writes
3644 if ( wfReadOnly() ) {
3648 // Do nothing if not allowed to edit the watchlist
3649 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3653 // If we're working on user's talk page, we should update the talk page message indicator
3654 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3655 // Avoid PHP 7.1 warning of passing $this by reference
3657 if ( !Hooks
::run( 'UserClearNewTalkNotification', [ &$user, $oldid ] ) ) {
3661 // Try to update the DB post-send and only if needed...
3662 DeferredUpdates
::addCallableUpdate( function() use ( $title, $oldid ) {
3663 if ( !$this->getNewtalk() ) {
3664 return; // no notifications to clear
3667 // Delete the last notifications (they stack up)
3668 $this->setNewtalk( false );
3670 // If there is a new, unseen, revision, use its timestamp
3672 ?
$title->getNextRevisionID( $oldid, Title
::GAID_FOR_UPDATE
)
3675 $this->setNewtalk( true, Revision
::newFromId( $nextid ) );
3680 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3684 if ( $this->isAnon() ) {
3685 // Nothing else to do...
3689 // Only update the timestamp if the page is being watched.
3690 // The query to find out if it is watched is cached both in memcached and per-invocation,
3691 // and when it does have to be executed, it can be on a replica DB
3692 // If this is the user's newtalk page, we always update the timestamp
3694 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3698 MediaWikiServices
::getInstance()->getWatchedItemStore()
3699 ->resetNotificationTimestamp( $this, $title, $force, $oldid );
3703 * Resets all of the given user's page-change notification timestamps.
3704 * If e-notif e-mails are on, they will receive notification mails on
3705 * the next change of any watched page.
3706 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3708 public function clearAllNotifications() {
3709 global $wgUseEnotif, $wgShowUpdatedMarker;
3710 // Do nothing if not allowed to edit the watchlist
3711 if ( wfReadOnly() ||
!$this->isAllowed( 'editmywatchlist' ) ) {
3715 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3716 $this->setNewtalk( false );
3720 $id = $this->getId();
3725 $dbw = wfGetDB( DB_MASTER
);
3726 $asOfTimes = array_unique( $dbw->selectFieldValues(
3728 'wl_notificationtimestamp',
3729 [ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ],
3731 [ 'ORDER BY' => 'wl_notificationtimestamp DESC', 'LIMIT' => 500 ]
3733 if ( !$asOfTimes ) {
3736 // Immediately update the most recent touched rows, which hopefully covers what
3737 // the user sees on the watchlist page before pressing "mark all pages visited"....
3740 [ 'wl_notificationtimestamp' => null ],
3741 [ 'wl_user' => $id, 'wl_notificationtimestamp' => $asOfTimes ],
3744 // ...and finish the older ones in a post-send update with lag checks...
3745 DeferredUpdates
::addUpdate( new AutoCommitUpdate(
3748 function () use ( $dbw, $id ) {
3749 global $wgUpdateRowsPerQuery;
3751 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
3752 $ticket = $lbFactory->getEmptyTransactionTicket( __METHOD__
);
3753 $asOfTimes = array_unique( $dbw->selectFieldValues(
3755 'wl_notificationtimestamp',
3756 [ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ],
3759 foreach ( array_chunk( $asOfTimes, $wgUpdateRowsPerQuery ) as $asOfTimeBatch ) {
3762 [ 'wl_notificationtimestamp' => null ],
3763 [ 'wl_user' => $id, 'wl_notificationtimestamp' => $asOfTimeBatch ],
3766 $lbFactory->commitAndWaitForReplication( __METHOD__
, $ticket );
3770 // We also need to clear here the "you have new message" notification for the own
3771 // user_talk page; it's cleared one page view later in WikiPage::doViewUpdates().
3775 * Compute experienced level based on edit count and registration date.
3777 * @return string 'newcomer', 'learner', or 'experienced'
3779 public function getExperienceLevel() {
3780 global $wgLearnerEdits,
3781 $wgExperiencedUserEdits,
3782 $wgLearnerMemberSince,
3783 $wgExperiencedUserMemberSince;
3785 if ( $this->isAnon() ) {
3789 $editCount = $this->getEditCount();
3790 $registration = $this->getRegistration();
3792 $learnerRegistration = wfTimestamp( TS_MW
, $now - $wgLearnerMemberSince * 86400 );
3793 $experiencedRegistration = wfTimestamp( TS_MW
, $now - $wgExperiencedUserMemberSince * 86400 );
3796 $editCount < $wgLearnerEdits ||
3797 $registration > $learnerRegistration
3801 $editCount > $wgExperiencedUserEdits &&
3802 $registration <= $experiencedRegistration
3804 return 'experienced';
3811 * Set a cookie on the user's client. Wrapper for
3812 * WebResponse::setCookie
3813 * @deprecated since 1.27
3814 * @param string $name Name of the cookie to set
3815 * @param string $value Value to set
3816 * @param int $exp Expiration time, as a UNIX time value;
3817 * if 0 or not specified, use the default $wgCookieExpiration
3818 * @param bool $secure
3819 * true: Force setting the secure attribute when setting the cookie
3820 * false: Force NOT setting the secure attribute when setting the cookie
3821 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3822 * @param array $params Array of options sent passed to WebResponse::setcookie()
3823 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3826 protected function setCookie(
3827 $name, $value, $exp = 0, $secure = null, $params = [], $request = null
3829 wfDeprecated( __METHOD__
, '1.27' );
3830 if ( $request === null ) {
3831 $request = $this->getRequest();
3833 $params['secure'] = $secure;
3834 $request->response()->setCookie( $name, $value, $exp, $params );
3838 * Clear a cookie on the user's client
3839 * @deprecated since 1.27
3840 * @param string $name Name of the cookie to clear
3841 * @param bool $secure
3842 * true: Force setting the secure attribute when setting the cookie
3843 * false: Force NOT setting the secure attribute when setting the cookie
3844 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3845 * @param array $params Array of options sent passed to WebResponse::setcookie()
3847 protected function clearCookie( $name, $secure = null, $params = [] ) {
3848 wfDeprecated( __METHOD__
, '1.27' );
3849 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3853 * Set an extended login cookie on the user's client. The expiry of the cookie
3854 * is controlled by the $wgExtendedLoginCookieExpiration configuration
3857 * @see User::setCookie
3859 * @deprecated since 1.27
3860 * @param string $name Name of the cookie to set
3861 * @param string $value Value to set
3862 * @param bool $secure
3863 * true: Force setting the secure attribute when setting the cookie
3864 * false: Force NOT setting the secure attribute when setting the cookie
3865 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3867 protected function setExtendedLoginCookie( $name, $value, $secure ) {
3868 global $wgExtendedLoginCookieExpiration, $wgCookieExpiration;
3870 wfDeprecated( __METHOD__
, '1.27' );
3873 $exp +
= $wgExtendedLoginCookieExpiration !== null
3874 ?
$wgExtendedLoginCookieExpiration
3875 : $wgCookieExpiration;
3877 $this->setCookie( $name, $value, $exp, $secure );
3881 * Persist this user's session (e.g. set cookies)
3883 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3885 * @param bool $secure Whether to force secure/insecure cookies or use default
3886 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3888 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3890 if ( 0 == $this->mId
) {
3894 $session = $this->getRequest()->getSession();
3895 if ( $request && $session->getRequest() !== $request ) {
3896 $session = $session->sessionWithRequest( $request );
3898 $delay = $session->delaySave();
3900 if ( !$session->getUser()->equals( $this ) ) {
3901 if ( !$session->canSetUser() ) {
3902 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3903 ->warning( __METHOD__
.
3904 ": Cannot save user \"$this\" to a user \"{$session->getUser()}\"'s immutable session"
3908 $session->setUser( $this );
3911 $session->setRememberUser( $rememberMe );
3912 if ( $secure !== null ) {
3913 $session->setForceHTTPS( $secure );
3916 $session->persist();
3918 ScopedCallback
::consume( $delay );
3922 * Log this user out.
3924 public function logout() {
3925 // Avoid PHP 7.1 warning of passing $this by reference
3927 if ( Hooks
::run( 'UserLogout', [ &$user ] ) ) {
3933 * Clear the user's session, and reset the instance cache.
3936 public function doLogout() {
3937 $session = $this->getRequest()->getSession();
3938 if ( !$session->canSetUser() ) {
3939 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3940 ->warning( __METHOD__
. ": Cannot log out of an immutable session" );
3941 $error = 'immutable';
3942 } elseif ( !$session->getUser()->equals( $this ) ) {
3943 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3944 ->warning( __METHOD__
.
3945 ": Cannot log user \"$this\" out of a user \"{$session->getUser()}\"'s session"
3947 // But we still may as well make this user object anon
3948 $this->clearInstanceCache( 'defaults' );
3949 $error = 'wronguser';
3951 $this->clearInstanceCache( 'defaults' );
3952 $delay = $session->delaySave();
3953 $session->unpersist(); // Clear cookies (T127436)
3954 $session->setLoggedOutTimestamp( time() );
3955 $session->setUser( new User
);
3956 $session->set( 'wsUserID', 0 ); // Other code expects this
3957 $session->resetAllTokens();
3958 ScopedCallback
::consume( $delay );
3961 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authevents' )->info( 'Logout', [
3962 'event' => 'logout',
3963 'successful' => $error === false,
3964 'status' => $error ?
: 'success',
3969 * Save this user's settings into the database.
3970 * @todo Only rarely do all these fields need to be set!
3972 public function saveSettings() {
3973 if ( wfReadOnly() ) {
3974 // @TODO: caller should deal with this instead!
3975 // This should really just be an exception.
3976 MWExceptionHandler
::logException( new DBExpectedError(
3978 "Could not update user with ID '{$this->mId}'; DB is read-only."
3984 if ( 0 == $this->mId
) {
3988 // Get a new user_touched that is higher than the old one.
3989 // This will be used for a CAS check as a last-resort safety
3990 // check against race conditions and replica DB lag.
3991 $newTouched = $this->newTouchedTimestamp();
3993 $dbw = wfGetDB( DB_MASTER
);
3994 $dbw->update( 'user',
3996 'user_name' => $this->mName
,
3997 'user_real_name' => $this->mRealName
,
3998 'user_email' => $this->mEmail
,
3999 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
4000 'user_touched' => $dbw->timestamp( $newTouched ),
4001 'user_token' => strval( $this->mToken
),
4002 'user_email_token' => $this->mEmailToken
,
4003 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
4004 ], $this->makeUpdateConditions( $dbw, [ /* WHERE */
4005 'user_id' => $this->mId
,
4009 if ( !$dbw->affectedRows() ) {
4010 // Maybe the problem was a missed cache update; clear it to be safe
4011 $this->clearSharedCache( 'refresh' );
4012 // User was changed in the meantime or loaded with stale data
4013 $from = ( $this->queryFlagsUsed
& self
::READ_LATEST
) ?
'master' : 'replica';
4014 throw new MWException(
4015 "CAS update failed on user_touched for user ID '{$this->mId}' (read from $from);" .
4016 " the version of the user to be saved is older than the current version."
4020 $this->mTouched
= $newTouched;
4021 $this->saveOptions();
4023 Hooks
::run( 'UserSaveSettings', [ $this ] );
4024 $this->clearSharedCache();
4025 $this->getUserPage()->invalidateCache();
4029 * If only this user's username is known, and it exists, return the user ID.
4031 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
4034 public function idForName( $flags = 0 ) {
4035 $s = trim( $this->getName() );
4040 $db = ( ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
)
4041 ?
wfGetDB( DB_MASTER
)
4042 : wfGetDB( DB_REPLICA
);
4044 $options = ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
)
4045 ?
[ 'LOCK IN SHARE MODE' ]
4048 $id = $db->selectField( 'user',
4049 'user_id', [ 'user_name' => $s ], __METHOD__
, $options );
4055 * Add a user to the database, return the user object
4057 * @param string $name Username to add
4058 * @param array $params Array of Strings Non-default parameters to save to
4059 * the database as user_* fields:
4060 * - email: The user's email address.
4061 * - email_authenticated: The email authentication timestamp.
4062 * - real_name: The user's real name.
4063 * - options: An associative array of non-default options.
4064 * - token: Random authentication token. Do not set.
4065 * - registration: Registration timestamp. Do not set.
4067 * @return User|null User object, or null if the username already exists.
4069 public static function createNew( $name, $params = [] ) {
4070 foreach ( [ 'password', 'newpassword', 'newpass_time', 'password_expires' ] as $field ) {
4071 if ( isset( $params[$field] ) ) {
4072 wfDeprecated( __METHOD__
. " with param '$field'", '1.27' );
4073 unset( $params[$field] );
4079 $user->setToken(); // init token
4080 if ( isset( $params['options'] ) ) {
4081 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
4082 unset( $params['options'] );
4084 $dbw = wfGetDB( DB_MASTER
);
4085 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
4087 $noPass = PasswordFactory
::newInvalidPassword()->toString();
4090 'user_id' => $seqVal,
4091 'user_name' => $name,
4092 'user_password' => $noPass,
4093 'user_newpassword' => $noPass,
4094 'user_email' => $user->mEmail
,
4095 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
4096 'user_real_name' => $user->mRealName
,
4097 'user_token' => strval( $user->mToken
),
4098 'user_registration' => $dbw->timestamp( $user->mRegistration
),
4099 'user_editcount' => 0,
4100 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
4102 foreach ( $params as $name => $value ) {
4103 $fields["user_$name"] = $value;
4105 $dbw->insert( 'user', $fields, __METHOD__
, [ 'IGNORE' ] );
4106 if ( $dbw->affectedRows() ) {
4107 $newUser = User
::newFromId( $dbw->insertId() );
4115 * Add this existing user object to the database. If the user already
4116 * exists, a fatal status object is returned, and the user object is
4117 * initialised with the data from the database.
4119 * Previously, this function generated a DB error due to a key conflict
4120 * if the user already existed. Many extension callers use this function
4121 * in code along the lines of:
4123 * $user = User::newFromName( $name );
4124 * if ( !$user->isLoggedIn() ) {
4125 * $user->addToDatabase();
4127 * // do something with $user...
4129 * However, this was vulnerable to a race condition (T18020). By
4130 * initialising the user object if the user exists, we aim to support this
4131 * calling sequence as far as possible.
4133 * Note that if the user exists, this function will acquire a write lock,
4134 * so it is still advisable to make the call conditional on isLoggedIn(),
4135 * and to commit the transaction after calling.
4137 * @throws MWException
4140 public function addToDatabase() {
4142 if ( !$this->mToken
) {
4143 $this->setToken(); // init token
4146 $this->mTouched
= $this->newTouchedTimestamp();
4148 $noPass = PasswordFactory
::newInvalidPassword()->toString();
4150 $dbw = wfGetDB( DB_MASTER
);
4151 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
4152 $dbw->insert( 'user',
4154 'user_id' => $seqVal,
4155 'user_name' => $this->mName
,
4156 'user_password' => $noPass,
4157 'user_newpassword' => $noPass,
4158 'user_email' => $this->mEmail
,
4159 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
4160 'user_real_name' => $this->mRealName
,
4161 'user_token' => strval( $this->mToken
),
4162 'user_registration' => $dbw->timestamp( $this->mRegistration
),
4163 'user_editcount' => 0,
4164 'user_touched' => $dbw->timestamp( $this->mTouched
),
4168 if ( !$dbw->affectedRows() ) {
4169 // Use locking reads to bypass any REPEATABLE-READ snapshot.
4170 $this->mId
= $dbw->selectField(
4173 [ 'user_name' => $this->mName
],
4175 [ 'LOCK IN SHARE MODE' ]
4179 if ( $this->loadFromDatabase( self
::READ_LOCKING
) ) {
4184 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
4185 "to insert user '{$this->mName}' row, but it was not present in select!" );
4187 return Status
::newFatal( 'userexists' );
4189 $this->mId
= $dbw->insertId();
4190 self
::$idCacheByName[$this->mName
] = $this->mId
;
4192 // Clear instance cache other than user table data, which is already accurate
4193 $this->clearInstanceCache();
4195 $this->saveOptions();
4196 return Status
::newGood();
4200 * If this user is logged-in and blocked,
4201 * block any IP address they've successfully logged in from.
4202 * @return bool A block was spread
4204 public function spreadAnyEditBlock() {
4205 if ( $this->isLoggedIn() && $this->isBlocked() ) {
4206 return $this->spreadBlock();
4213 * If this (non-anonymous) user is blocked,
4214 * block the IP address they've successfully logged in from.
4215 * @return bool A block was spread
4217 protected function spreadBlock() {
4218 wfDebug( __METHOD__
. "()\n" );
4220 if ( $this->mId
== 0 ) {
4224 $userblock = Block
::newFromTarget( $this->getName() );
4225 if ( !$userblock ) {
4229 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
4233 * Get whether the user is explicitly blocked from account creation.
4234 * @return bool|Block
4236 public function isBlockedFromCreateAccount() {
4237 $this->getBlockedStatus();
4238 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
4239 return $this->mBlock
;
4242 # T15611: if the IP address the user is trying to create an account from is
4243 # blocked with createaccount disabled, prevent new account creation there even
4244 # when the user is logged in
4245 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
4246 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
4248 return $this->mBlockedFromCreateAccount
instanceof Block
4249 && $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
4250 ?
$this->mBlockedFromCreateAccount
4255 * Get whether the user is blocked from using Special:Emailuser.
4258 public function isBlockedFromEmailuser() {
4259 $this->getBlockedStatus();
4260 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
4264 * Get whether the user is allowed to create an account.
4267 public function isAllowedToCreateAccount() {
4268 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
4272 * Get this user's personal page title.
4274 * @return Title User's personal page title
4276 public function getUserPage() {
4277 return Title
::makeTitle( NS_USER
, $this->getName() );
4281 * Get this user's talk page title.
4283 * @return Title User's talk page title
4285 public function getTalkPage() {
4286 $title = $this->getUserPage();
4287 return $title->getTalkPage();
4291 * Determine whether the user is a newbie. Newbies are either
4292 * anonymous IPs, or the most recently created accounts.
4295 public function isNewbie() {
4296 return !$this->isAllowed( 'autoconfirmed' );
4300 * Check to see if the given clear-text password is one of the accepted passwords
4301 * @deprecated since 1.27, use AuthManager instead
4302 * @param string $password User password
4303 * @return bool True if the given password is correct, otherwise False
4305 public function checkPassword( $password ) {
4306 $manager = AuthManager
::singleton();
4307 $reqs = AuthenticationRequest
::loadRequestsFromSubmission(
4308 $manager->getAuthenticationRequests( AuthManager
::ACTION_LOGIN
),
4310 'username' => $this->getName(),
4311 'password' => $password,
4314 $res = AuthManager
::singleton()->beginAuthentication( $reqs, 'null:' );
4315 switch ( $res->status
) {
4316 case AuthenticationResponse
::PASS
:
4318 case AuthenticationResponse
::FAIL
:
4319 // Hope it's not a PreAuthenticationProvider that failed...
4320 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
4321 ->info( __METHOD__
. ': Authentication failed: ' . $res->message
->plain() );
4324 throw new BadMethodCallException(
4325 'AuthManager returned a response unsupported by ' . __METHOD__
4331 * Check if the given clear-text password matches the temporary password
4332 * sent by e-mail for password reset operations.
4334 * @deprecated since 1.27, use AuthManager instead
4335 * @param string $plaintext
4336 * @return bool True if matches, false otherwise
4338 public function checkTemporaryPassword( $plaintext ) {
4339 // Can't check the temporary password individually.
4340 return $this->checkPassword( $plaintext );
4344 * Initialize (if necessary) and return a session token value
4345 * which can be used in edit forms to show that the user's
4346 * login credentials aren't being hijacked with a foreign form
4350 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4351 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4352 * @return MediaWiki\Session\Token The new edit token
4354 public function getEditTokenObject( $salt = '', $request = null ) {
4355 if ( $this->isAnon() ) {
4356 return new LoggedOutEditToken();
4360 $request = $this->getRequest();
4362 return $request->getSession()->getToken( $salt );
4366 * Initialize (if necessary) and return a session token value
4367 * which can be used in edit forms to show that the user's
4368 * login credentials aren't being hijacked with a foreign form
4371 * The $salt for 'edit' and 'csrf' tokens is the default (empty string).
4374 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4375 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4376 * @return string The new edit token
4378 public function getEditToken( $salt = '', $request = null ) {
4379 return $this->getEditTokenObject( $salt, $request )->toString();
4383 * Get the embedded timestamp from a token.
4384 * @deprecated since 1.27, use \MediaWiki\Session\Token::getTimestamp instead.
4385 * @param string $val Input token
4388 public static function getEditTokenTimestamp( $val ) {
4389 wfDeprecated( __METHOD__
, '1.27' );
4390 return MediaWiki\Session\Token
::getTimestamp( $val );
4394 * Check given value against the token value stored in the session.
4395 * A match should confirm that the form was submitted from the
4396 * user's own login session, not a form submission from a third-party
4399 * @param string $val Input value to compare
4400 * @param string $salt Optional function-specific data for hashing
4401 * @param WebRequest|null $request Object to use or null to use $wgRequest
4402 * @param int $maxage Fail tokens older than this, in seconds
4403 * @return bool Whether the token matches
4405 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4406 return $this->getEditTokenObject( $salt, $request )->match( $val, $maxage );
4410 * Check given value against the token value stored in the session,
4411 * ignoring the suffix.
4413 * @param string $val Input value to compare
4414 * @param string $salt Optional function-specific data for hashing
4415 * @param WebRequest|null $request Object to use or null to use $wgRequest
4416 * @param int $maxage Fail tokens older than this, in seconds
4417 * @return bool Whether the token matches
4419 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4420 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . Token
::SUFFIX
;
4421 return $this->matchEditToken( $val, $salt, $request, $maxage );
4425 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4426 * mail to the user's given address.
4428 * @param string $type Message to send, either "created", "changed" or "set"
4431 public function sendConfirmationMail( $type = 'created' ) {
4433 $expiration = null; // gets passed-by-ref and defined in next line.
4434 $token = $this->confirmationToken( $expiration );
4435 $url = $this->confirmationTokenUrl( $token );
4436 $invalidateURL = $this->invalidationTokenUrl( $token );
4437 $this->saveSettings();
4439 if ( $type == 'created' ||
$type === false ) {
4440 $message = 'confirmemail_body';
4441 } elseif ( $type === true ) {
4442 $message = 'confirmemail_body_changed';
4444 // Messages: confirmemail_body_changed, confirmemail_body_set
4445 $message = 'confirmemail_body_' . $type;
4448 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4449 wfMessage( $message,
4450 $this->getRequest()->getIP(),
4453 $wgLang->userTimeAndDate( $expiration, $this ),
4455 $wgLang->userDate( $expiration, $this ),
4456 $wgLang->userTime( $expiration, $this ) )->text() );
4460 * Send an e-mail to this user's account. Does not check for
4461 * confirmed status or validity.
4463 * @param string $subject Message subject
4464 * @param string $body Message body
4465 * @param User|null $from Optional sending user; if unspecified, default
4466 * $wgPasswordSender will be used.
4467 * @param string $replyto Reply-To address
4470 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4471 global $wgPasswordSender;
4473 if ( $from instanceof User
) {
4474 $sender = MailAddress
::newFromUser( $from );
4476 $sender = new MailAddress( $wgPasswordSender,
4477 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4479 $to = MailAddress
::newFromUser( $this );
4481 return UserMailer
::send( $to, $sender, $subject, $body, [
4482 'replyTo' => $replyto,
4487 * Generate, store, and return a new e-mail confirmation code.
4488 * A hash (unsalted, since it's used as a key) is stored.
4490 * @note Call saveSettings() after calling this function to commit
4491 * this change to the database.
4493 * @param string &$expiration Accepts the expiration time
4494 * @return string New token
4496 protected function confirmationToken( &$expiration ) {
4497 global $wgUserEmailConfirmationTokenExpiry;
4499 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4500 $expiration = wfTimestamp( TS_MW
, $expires );
4502 $token = MWCryptRand
::generateHex( 32 );
4503 $hash = md5( $token );
4504 $this->mEmailToken
= $hash;
4505 $this->mEmailTokenExpires
= $expiration;
4510 * Return a URL the user can use to confirm their email address.
4511 * @param string $token Accepts the email confirmation token
4512 * @return string New token URL
4514 protected function confirmationTokenUrl( $token ) {
4515 return $this->getTokenUrl( 'ConfirmEmail', $token );
4519 * Return a URL the user can use to invalidate their email address.
4520 * @param string $token Accepts the email confirmation token
4521 * @return string New token URL
4523 protected function invalidationTokenUrl( $token ) {
4524 return $this->getTokenUrl( 'InvalidateEmail', $token );
4528 * Internal function to format the e-mail validation/invalidation URLs.
4529 * This uses a quickie hack to use the
4530 * hardcoded English names of the Special: pages, for ASCII safety.
4532 * @note Since these URLs get dropped directly into emails, using the
4533 * short English names avoids insanely long URL-encoded links, which
4534 * also sometimes can get corrupted in some browsers/mailers
4535 * (T8957 with Gmail and Internet Explorer).
4537 * @param string $page Special page
4538 * @param string $token Token
4539 * @return string Formatted URL
4541 protected function getTokenUrl( $page, $token ) {
4542 // Hack to bypass localization of 'Special:'
4543 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4544 return $title->getCanonicalURL();
4548 * Mark the e-mail address confirmed.
4550 * @note Call saveSettings() after calling this function to commit the change.
4554 public function confirmEmail() {
4555 // Check if it's already confirmed, so we don't touch the database
4556 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4557 if ( !$this->isEmailConfirmed() ) {
4558 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4559 Hooks
::run( 'ConfirmEmailComplete', [ $this ] );
4565 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4566 * address if it was already confirmed.
4568 * @note Call saveSettings() after calling this function to commit the change.
4569 * @return bool Returns true
4571 public function invalidateEmail() {
4573 $this->mEmailToken
= null;
4574 $this->mEmailTokenExpires
= null;
4575 $this->setEmailAuthenticationTimestamp( null );
4577 Hooks
::run( 'InvalidateEmailComplete', [ $this ] );
4582 * Set the e-mail authentication timestamp.
4583 * @param string $timestamp TS_MW timestamp
4585 public function setEmailAuthenticationTimestamp( $timestamp ) {
4587 $this->mEmailAuthenticated
= $timestamp;
4588 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
4592 * Is this user allowed to send e-mails within limits of current
4593 * site configuration?
4596 public function canSendEmail() {
4597 global $wgEnableEmail, $wgEnableUserEmail;
4598 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4601 $canSend = $this->isEmailConfirmed();
4602 // Avoid PHP 7.1 warning of passing $this by reference
4604 Hooks
::run( 'UserCanSendEmail', [ &$user, &$canSend ] );
4609 * Is this user allowed to receive e-mails within limits of current
4610 * site configuration?
4613 public function canReceiveEmail() {
4614 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4618 * Is this user's e-mail address valid-looking and confirmed within
4619 * limits of the current site configuration?
4621 * @note If $wgEmailAuthentication is on, this may require the user to have
4622 * confirmed their address by returning a code or using a password
4623 * sent to the address from the wiki.
4627 public function isEmailConfirmed() {
4628 global $wgEmailAuthentication;
4630 // Avoid PHP 7.1 warning of passing $this by reference
4633 if ( Hooks
::run( 'EmailConfirmed', [ &$user, &$confirmed ] ) ) {
4634 if ( $this->isAnon() ) {
4637 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4640 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4650 * Check whether there is an outstanding request for e-mail confirmation.
4653 public function isEmailConfirmationPending() {
4654 global $wgEmailAuthentication;
4655 return $wgEmailAuthentication &&
4656 !$this->isEmailConfirmed() &&
4657 $this->mEmailToken
&&
4658 $this->mEmailTokenExpires
> wfTimestamp();
4662 * Get the timestamp of account creation.
4664 * @return string|bool|null Timestamp of account creation, false for
4665 * non-existent/anonymous user accounts, or null if existing account
4666 * but information is not in database.
4668 public function getRegistration() {
4669 if ( $this->isAnon() ) {
4673 return $this->mRegistration
;
4677 * Get the timestamp of the first edit
4679 * @return string|bool Timestamp of first edit, or false for
4680 * non-existent/anonymous user accounts.
4682 public function getFirstEditTimestamp() {
4683 if ( $this->getId() == 0 ) {
4684 return false; // anons
4686 $dbr = wfGetDB( DB_REPLICA
);
4687 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4688 [ 'rev_user' => $this->getId() ],
4690 [ 'ORDER BY' => 'rev_timestamp ASC' ]
4693 return false; // no edits
4695 return wfTimestamp( TS_MW
, $time );
4699 * Get the permissions associated with a given list of groups
4701 * @param array $groups Array of Strings List of internal group names
4702 * @return array Array of Strings List of permission key names for given groups combined
4704 public static function getGroupPermissions( $groups ) {
4705 global $wgGroupPermissions, $wgRevokePermissions;
4707 // grant every granted permission first
4708 foreach ( $groups as $group ) {
4709 if ( isset( $wgGroupPermissions[$group] ) ) {
4710 $rights = array_merge( $rights,
4711 // array_filter removes empty items
4712 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4715 // now revoke the revoked permissions
4716 foreach ( $groups as $group ) {
4717 if ( isset( $wgRevokePermissions[$group] ) ) {
4718 $rights = array_diff( $rights,
4719 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4722 return array_unique( $rights );
4726 * Get all the groups who have a given permission
4728 * @param string $role Role to check
4729 * @return array Array of Strings List of internal group names with the given permission
4731 public static function getGroupsWithPermission( $role ) {
4732 global $wgGroupPermissions;
4733 $allowedGroups = [];
4734 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4735 if ( self
::groupHasPermission( $group, $role ) ) {
4736 $allowedGroups[] = $group;
4739 return $allowedGroups;
4743 * Check, if the given group has the given permission
4745 * If you're wanting to check whether all users have a permission, use
4746 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4750 * @param string $group Group to check
4751 * @param string $role Role to check
4754 public static function groupHasPermission( $group, $role ) {
4755 global $wgGroupPermissions, $wgRevokePermissions;
4756 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4757 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4761 * Check if all users may be assumed to have the given permission
4763 * We generally assume so if the right is granted to '*' and isn't revoked
4764 * on any group. It doesn't attempt to take grants or other extension
4765 * limitations on rights into account in the general case, though, as that
4766 * would require it to always return false and defeat the purpose.
4767 * Specifically, session-based rights restrictions (such as OAuth or bot
4768 * passwords) are applied based on the current session.
4771 * @param string $right Right to check
4774 public static function isEveryoneAllowed( $right ) {
4775 global $wgGroupPermissions, $wgRevokePermissions;
4778 // Use the cached results, except in unit tests which rely on
4779 // being able change the permission mid-request
4780 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4781 return $cache[$right];
4784 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4785 $cache[$right] = false;
4789 // If it's revoked anywhere, then everyone doesn't have it
4790 foreach ( $wgRevokePermissions as $rights ) {
4791 if ( isset( $rights[$right] ) && $rights[$right] ) {
4792 $cache[$right] = false;
4797 // Remove any rights that aren't allowed to the global-session user,
4798 // unless there are no sessions for this endpoint.
4799 if ( !defined( 'MW_NO_SESSION' ) ) {
4800 $allowedRights = SessionManager
::getGlobalSession()->getAllowedUserRights();
4801 if ( $allowedRights !== null && !in_array( $right, $allowedRights, true ) ) {
4802 $cache[$right] = false;
4807 // Allow extensions to say false
4808 if ( !Hooks
::run( 'UserIsEveryoneAllowed', [ $right ] ) ) {
4809 $cache[$right] = false;
4813 $cache[$right] = true;
4818 * Get the localized descriptive name for a group, if it exists
4819 * @deprecated since 1.29 Use UserGroupMembership::getGroupName instead
4821 * @param string $group Internal group name
4822 * @return string Localized descriptive group name
4824 public static function getGroupName( $group ) {
4825 wfDeprecated( __METHOD__
, '1.29' );
4826 return UserGroupMembership
::getGroupName( $group );
4830 * Get the localized descriptive name for a member of a group, if it exists
4831 * @deprecated since 1.29 Use UserGroupMembership::getGroupMemberName instead
4833 * @param string $group Internal group name
4834 * @param string $username Username for gender (since 1.19)
4835 * @return string Localized name for group member
4837 public static function getGroupMember( $group, $username = '#' ) {
4838 wfDeprecated( __METHOD__
, '1.29' );
4839 return UserGroupMembership
::getGroupMemberName( $group, $username );
4843 * Return the set of defined explicit groups.
4844 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4845 * are not included, as they are defined automatically, not in the database.
4846 * @return array Array of internal group names
4848 public static function getAllGroups() {
4849 global $wgGroupPermissions, $wgRevokePermissions;
4851 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4852 self
::getImplicitGroups()
4857 * Get a list of all available permissions.
4858 * @return string[] Array of permission names
4860 public static function getAllRights() {
4861 if ( self
::$mAllRights === false ) {
4862 global $wgAvailableRights;
4863 if ( count( $wgAvailableRights ) ) {
4864 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
4866 self
::$mAllRights = self
::$mCoreRights;
4868 Hooks
::run( 'UserGetAllRights', [ &self
::$mAllRights ] );
4870 return self
::$mAllRights;
4874 * Get a list of implicit groups
4875 * @return array Array of Strings Array of internal group names
4877 public static function getImplicitGroups() {
4878 global $wgImplicitGroups;
4880 $groups = $wgImplicitGroups;
4881 # Deprecated, use $wgImplicitGroups instead
4882 Hooks
::run( 'UserGetImplicitGroups', [ &$groups ], '1.25' );
4888 * Get the title of a page describing a particular group
4889 * @deprecated since 1.29 Use UserGroupMembership::getGroupPage instead
4891 * @param string $group Internal group name
4892 * @return Title|bool Title of the page if it exists, false otherwise
4894 public static function getGroupPage( $group ) {
4895 wfDeprecated( __METHOD__
, '1.29' );
4896 return UserGroupMembership
::getGroupPage( $group );
4900 * Create a link to the group in HTML, if available;
4901 * else return the group name.
4902 * @deprecated since 1.29 Use UserGroupMembership::getLink instead, or
4903 * make the link yourself if you need custom text
4905 * @param string $group Internal name of the group
4906 * @param string $text The text of the link
4907 * @return string HTML link to the group
4909 public static function makeGroupLinkHTML( $group, $text = '' ) {
4910 wfDeprecated( __METHOD__
, '1.29' );
4912 if ( $text == '' ) {
4913 $text = UserGroupMembership
::getGroupName( $group );
4915 $title = UserGroupMembership
::getGroupPage( $group );
4917 return Linker
::link( $title, htmlspecialchars( $text ) );
4919 return htmlspecialchars( $text );
4924 * Create a link to the group in Wikitext, if available;
4925 * else return the group name.
4926 * @deprecated since 1.29 Use UserGroupMembership::getLink instead, or
4927 * make the link yourself if you need custom text
4929 * @param string $group Internal name of the group
4930 * @param string $text The text of the link
4931 * @return string Wikilink to the group
4933 public static function makeGroupLinkWiki( $group, $text = '' ) {
4934 wfDeprecated( __METHOD__
, '1.29' );
4936 if ( $text == '' ) {
4937 $text = UserGroupMembership
::getGroupName( $group );
4939 $title = UserGroupMembership
::getGroupPage( $group );
4941 $page = $title->getFullText();
4942 return "[[$page|$text]]";
4949 * Returns an array of the groups that a particular group can add/remove.
4951 * @param string $group The group to check for whether it can add/remove
4952 * @return array Array( 'add' => array( addablegroups ),
4953 * 'remove' => array( removablegroups ),
4954 * 'add-self' => array( addablegroups to self),
4955 * 'remove-self' => array( removable groups from self) )
4957 public static function changeableByGroup( $group ) {
4958 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4967 if ( empty( $wgAddGroups[$group] ) ) {
4968 // Don't add anything to $groups
4969 } elseif ( $wgAddGroups[$group] === true ) {
4970 // You get everything
4971 $groups['add'] = self
::getAllGroups();
4972 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4973 $groups['add'] = $wgAddGroups[$group];
4976 // Same thing for remove
4977 if ( empty( $wgRemoveGroups[$group] ) ) {
4979 } elseif ( $wgRemoveGroups[$group] === true ) {
4980 $groups['remove'] = self
::getAllGroups();
4981 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4982 $groups['remove'] = $wgRemoveGroups[$group];
4985 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4986 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4987 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4988 if ( is_int( $key ) ) {
4989 $wgGroupsAddToSelf['user'][] = $value;
4994 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
4995 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4996 if ( is_int( $key ) ) {
4997 $wgGroupsRemoveFromSelf['user'][] = $value;
5002 // Now figure out what groups the user can add to him/herself
5003 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
5005 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
5006 // No idea WHY this would be used, but it's there
5007 $groups['add-self'] = User
::getAllGroups();
5008 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
5009 $groups['add-self'] = $wgGroupsAddToSelf[$group];
5012 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
5014 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
5015 $groups['remove-self'] = User
::getAllGroups();
5016 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
5017 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
5024 * Returns an array of groups that this user can add and remove
5025 * @return array Array( 'add' => array( addablegroups ),
5026 * 'remove' => array( removablegroups ),
5027 * 'add-self' => array( addablegroups to self),
5028 * 'remove-self' => array( removable groups from self) )
5030 public function changeableGroups() {
5031 if ( $this->isAllowed( 'userrights' ) ) {
5032 // This group gives the right to modify everything (reverse-
5033 // compatibility with old "userrights lets you change
5035 // Using array_merge to make the groups reindexed
5036 $all = array_merge( User
::getAllGroups() );
5045 // Okay, it's not so simple, we will have to go through the arrays
5052 $addergroups = $this->getEffectiveGroups();
5054 foreach ( $addergroups as $addergroup ) {
5055 $groups = array_merge_recursive(
5056 $groups, $this->changeableByGroup( $addergroup )
5058 $groups['add'] = array_unique( $groups['add'] );
5059 $groups['remove'] = array_unique( $groups['remove'] );
5060 $groups['add-self'] = array_unique( $groups['add-self'] );
5061 $groups['remove-self'] = array_unique( $groups['remove-self'] );
5067 * Deferred version of incEditCountImmediate()
5069 public function incEditCount() {
5070 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle(
5072 $this->incEditCountImmediate();
5079 * Increment the user's edit-count field.
5080 * Will have no effect for anonymous users.
5083 public function incEditCountImmediate() {
5084 if ( $this->isAnon() ) {
5088 $dbw = wfGetDB( DB_MASTER
);
5089 // No rows will be "affected" if user_editcount is NULL
5092 [ 'user_editcount=user_editcount+1' ],
5093 [ 'user_id' => $this->getId(), 'user_editcount IS NOT NULL' ],
5096 // Lazy initialization check...
5097 if ( $dbw->affectedRows() == 0 ) {
5098 // Now here's a goddamn hack...
5099 $dbr = wfGetDB( DB_REPLICA
);
5100 if ( $dbr !== $dbw ) {
5101 // If we actually have a replica DB server, the count is
5102 // at least one behind because the current transaction
5103 // has not been committed and replicated.
5104 $this->mEditCount
= $this->initEditCount( 1 );
5106 // But if DB_REPLICA is selecting the master, then the
5107 // count we just read includes the revision that was
5108 // just added in the working transaction.
5109 $this->mEditCount
= $this->initEditCount();
5112 if ( $this->mEditCount
=== null ) {
5113 $this->getEditCount();
5114 $dbr = wfGetDB( DB_REPLICA
);
5115 $this->mEditCount +
= ( $dbr !== $dbw ) ?
1 : 0;
5117 $this->mEditCount++
;
5120 // Edit count in user cache too
5121 $this->invalidateCache();
5125 * Initialize user_editcount from data out of the revision table
5127 * @param int $add Edits to add to the count from the revision table
5128 * @return int Number of edits
5130 protected function initEditCount( $add = 0 ) {
5131 // Pull from a replica DB to be less cruel to servers
5132 // Accuracy isn't the point anyway here
5133 $dbr = wfGetDB( DB_REPLICA
);
5134 $count = (int)$dbr->selectField(
5137 [ 'rev_user' => $this->getId() ],
5140 $count = $count +
$add;
5142 $dbw = wfGetDB( DB_MASTER
);
5145 [ 'user_editcount' => $count ],
5146 [ 'user_id' => $this->getId() ],
5154 * Get the description of a given right
5157 * @param string $right Right to query
5158 * @return string Localized description of the right
5160 public static function getRightDescription( $right ) {
5161 $key = "right-$right";
5162 $msg = wfMessage( $key );
5163 return $msg->isDisabled() ?
$right : $msg->text();
5167 * Get the name of a given grant
5170 * @param string $grant Grant to query
5171 * @return string Localized name of the grant
5173 public static function getGrantName( $grant ) {
5174 $key = "grant-$grant";
5175 $msg = wfMessage( $key );
5176 return $msg->isDisabled() ?
$grant : $msg->text();
5180 * Add a newuser log entry for this user.
5181 * Before 1.19 the return value was always true.
5183 * @deprecated since 1.27, AuthManager handles logging
5184 * @param string|bool $action Account creation type.
5185 * - String, one of the following values:
5186 * - 'create' for an anonymous user creating an account for himself.
5187 * This will force the action's performer to be the created user itself,
5188 * no matter the value of $wgUser
5189 * - 'create2' for a logged in user creating an account for someone else
5190 * - 'byemail' when the created user will receive its password by e-mail
5191 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
5192 * - Boolean means whether the account was created by e-mail (deprecated):
5193 * - true will be converted to 'byemail'
5194 * - false will be converted to 'create' if this object is the same as
5195 * $wgUser and to 'create2' otherwise
5196 * @param string $reason User supplied reason
5199 public function addNewUserLogEntry( $action = false, $reason = '' ) {
5200 return true; // disabled
5204 * Add an autocreate newuser log entry for this user
5205 * Used by things like CentralAuth and perhaps other authplugins.
5206 * Consider calling addNewUserLogEntry() directly instead.
5208 * @deprecated since 1.27, AuthManager handles logging
5211 public function addNewUserLogEntryAutoCreate() {
5212 $this->addNewUserLogEntry( 'autocreate' );
5218 * Load the user options either from cache, the database or an array
5220 * @param array $data Rows for the current user out of the user_properties table
5222 protected function loadOptions( $data = null ) {
5227 if ( $this->mOptionsLoaded
) {
5231 $this->mOptions
= self
::getDefaultOptions();
5233 if ( !$this->getId() ) {
5234 // For unlogged-in users, load language/variant options from request.
5235 // There's no need to do it for logged-in users: they can set preferences,
5236 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5237 // so don't override user's choice (especially when the user chooses site default).
5238 $variant = $wgContLang->getDefaultVariant();
5239 $this->mOptions
['variant'] = $variant;
5240 $this->mOptions
['language'] = $variant;
5241 $this->mOptionsLoaded
= true;
5245 // Maybe load from the object
5246 if ( !is_null( $this->mOptionOverrides
) ) {
5247 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5248 foreach ( $this->mOptionOverrides
as $key => $value ) {
5249 $this->mOptions
[$key] = $value;
5252 if ( !is_array( $data ) ) {
5253 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5254 // Load from database
5255 $dbr = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
5256 ?
wfGetDB( DB_MASTER
)
5257 : wfGetDB( DB_REPLICA
);
5259 $res = $dbr->select(
5261 [ 'up_property', 'up_value' ],
5262 [ 'up_user' => $this->getId() ],
5266 $this->mOptionOverrides
= [];
5268 foreach ( $res as $row ) {
5269 // Convert '0' to 0. PHP's boolean conversion considers them both
5270 // false, but e.g. JavaScript considers the former as true.
5271 // @todo: T54542 Somehow determine the desired type (string/int/bool)
5272 // and convert all values here.
5273 if ( $row->up_value
=== '0' ) {
5276 $data[$row->up_property
] = $row->up_value
;
5279 foreach ( $data as $property => $value ) {
5280 $this->mOptionOverrides
[$property] = $value;
5281 $this->mOptions
[$property] = $value;
5285 $this->mOptionsLoaded
= true;
5287 Hooks
::run( 'UserLoadOptions', [ $this, &$this->mOptions
] );
5291 * Saves the non-default options for this user, as previously set e.g. via
5292 * setOption(), in the database's "user_properties" (preferences) table.
5293 * Usually used via saveSettings().
5295 protected function saveOptions() {
5296 $this->loadOptions();
5298 // Not using getOptions(), to keep hidden preferences in database
5299 $saveOptions = $this->mOptions
;
5301 // Allow hooks to abort, for instance to save to a global profile.
5302 // Reset options to default state before saving.
5303 if ( !Hooks
::run( 'UserSaveOptions', [ $this, &$saveOptions ] ) ) {
5307 $userId = $this->getId();
5309 $insert_rows = []; // all the new preference rows
5310 foreach ( $saveOptions as $key => $value ) {
5311 // Don't bother storing default values
5312 $defaultOption = self
::getDefaultOption( $key );
5313 if ( ( $defaultOption === null && $value !== false && $value !== null )
5314 ||
$value != $defaultOption
5317 'up_user' => $userId,
5318 'up_property' => $key,
5319 'up_value' => $value,
5324 $dbw = wfGetDB( DB_MASTER
);
5326 $res = $dbw->select( 'user_properties',
5327 [ 'up_property', 'up_value' ], [ 'up_user' => $userId ], __METHOD__
);
5329 // Find prior rows that need to be removed or updated. These rows will
5330 // all be deleted (the latter so that INSERT IGNORE applies the new values).
5332 foreach ( $res as $row ) {
5333 if ( !isset( $saveOptions[$row->up_property
] )
5334 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
5336 $keysDelete[] = $row->up_property
;
5340 if ( count( $keysDelete ) ) {
5341 // Do the DELETE by PRIMARY KEY for prior rows.
5342 // In the past a very large portion of calls to this function are for setting
5343 // 'rememberpassword' for new accounts (a preference that has since been removed).
5344 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5345 // caused gap locks on [max user ID,+infinity) which caused high contention since
5346 // updates would pile up on each other as they are for higher (newer) user IDs.
5347 // It might not be necessary these days, but it shouldn't hurt either.
5348 $dbw->delete( 'user_properties',
5349 [ 'up_user' => $userId, 'up_property' => $keysDelete ], __METHOD__
);
5351 // Insert the new preference rows
5352 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, [ 'IGNORE' ] );
5356 * Lazily instantiate and return a factory object for making passwords
5358 * @deprecated since 1.27, create a PasswordFactory directly instead
5359 * @return PasswordFactory
5361 public static function getPasswordFactory() {
5362 wfDeprecated( __METHOD__
, '1.27' );
5363 $ret = new PasswordFactory();
5364 $ret->init( RequestContext
::getMain()->getConfig() );
5369 * Provide an array of HTML5 attributes to put on an input element
5370 * intended for the user to enter a new password. This may include
5371 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
5373 * Do *not* use this when asking the user to enter his current password!
5374 * Regardless of configuration, users may have invalid passwords for whatever
5375 * reason (e.g., they were set before requirements were tightened up).
5376 * Only use it when asking for a new password, like on account creation or
5379 * Obviously, you still need to do server-side checking.
5381 * NOTE: A combination of bugs in various browsers means that this function
5382 * actually just returns array() unconditionally at the moment. May as
5383 * well keep it around for when the browser bugs get fixed, though.
5385 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
5387 * @deprecated since 1.27
5388 * @return array Array of HTML attributes suitable for feeding to
5389 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
5390 * That will get confused by the boolean attribute syntax used.)
5392 public static function passwordChangeInputAttribs() {
5393 global $wgMinimalPasswordLength;
5395 if ( $wgMinimalPasswordLength == 0 ) {
5399 # Note that the pattern requirement will always be satisfied if the
5400 # input is empty, so we need required in all cases.
5402 # @todo FIXME: T25769: This needs to not claim the password is required
5403 # if e-mail confirmation is being used. Since HTML5 input validation
5404 # is b0rked anyway in some browsers, just return nothing. When it's
5405 # re-enabled, fix this code to not output required for e-mail
5407 # $ret = array( 'required' );
5410 # We can't actually do this right now, because Opera 9.6 will print out
5411 # the entered password visibly in its error message! When other
5412 # browsers add support for this attribute, or Opera fixes its support,
5413 # we can add support with a version check to avoid doing this on Opera
5414 # versions where it will be a problem. Reported to Opera as
5415 # DSK-262266, but they don't have a public bug tracker for us to follow.
5417 if ( $wgMinimalPasswordLength > 1 ) {
5418 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
5419 $ret['title'] = wfMessage( 'passwordtooshort' )
5420 ->numParams( $wgMinimalPasswordLength )->text();
5428 * Return the list of user fields that should be selected to create
5429 * a new user object.
5432 public static function selectFields() {
5440 'user_email_authenticated',
5442 'user_email_token_expires',
5443 'user_registration',
5449 * Factory function for fatal permission-denied errors
5452 * @param string $permission User right required
5455 static function newFatalPermissionDeniedStatus( $permission ) {
5459 foreach ( User
::getGroupsWithPermission( $permission ) as $group ) {
5460 $groups[] = UserGroupMembership
::getLink( $group, RequestContext
::getMain(), 'wiki' );
5464 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5466 return Status
::newFatal( 'badaccess-group0' );
5471 * Get a new instance of this user that was loaded from the master via a locking read
5473 * Use this instead of the main context User when updating that user. This avoids races
5474 * where that user was loaded from a replica DB or even the master but without proper locks.
5476 * @return User|null Returns null if the user was not found in the DB
5479 public function getInstanceForUpdate() {
5480 if ( !$this->getId() ) {
5481 return null; // anon
5484 $user = self
::newFromId( $this->getId() );
5485 if ( !$user->loadFromId( self
::READ_EXCLUSIVE
) ) {
5493 * Checks if two user objects point to the same user.
5499 public function equals( User
$user ) {
5500 return $this->getName() === $user->getName();