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;
231 protected $mOptionOverrides;
235 * Bool Whether the cache variables have been loaded.
238 public $mOptionsLoaded;
241 * Array with already loaded items or true if all items have been loaded.
243 protected $mLoadedItems = [];
247 * String Initialization data source if mLoadedItems!==true. May be one of:
248 * - 'defaults' anonymous user initialised from class defaults
249 * - 'name' initialise from mName
250 * - 'id' initialise from mId
251 * - 'session' log in from session if possible
253 * Use the User::newFrom*() family of functions to set this.
258 * Lazy-initialized variables, invalidated with clearInstanceCache
262 protected $mDatePreference;
270 protected $mBlockreason;
272 protected $mEffectiveGroups;
274 protected $mImplicitGroups;
276 protected $mFormerGroups;
278 protected $mGlobalBlock;
295 protected $mAllowUsertalk;
298 private $mBlockedFromCreateAccount = false;
300 /** @var integer User::READ_* constant bitfield used to load data */
301 protected $queryFlagsUsed = self
::READ_NORMAL
;
303 /** @var string Indicates type of block (used for eventlogging)
304 * Permitted values: 'cookie-block', 'proxy-block', 'openproxy-block', 'xff-block',
307 public $blockTrigger = false;
309 public static $idCacheByName = [];
312 * Lightweight constructor for an anonymous user.
313 * Use the User::newFrom* factory functions for other kinds of users.
317 * @see newFromConfirmationCode()
318 * @see newFromSession()
321 public function __construct() {
322 $this->clearInstanceCache( 'defaults' );
328 public function __toString() {
329 return (string)$this->getName();
333 * Test if it's safe to load this User object.
335 * You should typically check this before using $wgUser or
336 * RequestContext::getUser in a method that might be called before the
337 * system has been fully initialized. If the object is unsafe, you should
338 * use an anonymous user:
340 * $user = $wgUser->isSafeToLoad() ? $wgUser : new User;
346 public function isSafeToLoad() {
347 global $wgFullyInitialised;
349 // The user is safe to load if:
350 // * MW_NO_SESSION is undefined AND $wgFullyInitialised is true (safe to use session data)
351 // * mLoadedItems === true (already loaded)
352 // * mFrom !== 'session' (sessions not involved at all)
354 return ( !defined( 'MW_NO_SESSION' ) && $wgFullyInitialised ) ||
355 $this->mLoadedItems
=== true ||
$this->mFrom
!== 'session';
359 * Load the user table data for this object from the source given by mFrom.
361 * @param integer $flags User::READ_* constant bitfield
363 public function load( $flags = self
::READ_NORMAL
) {
364 global $wgFullyInitialised;
366 if ( $this->mLoadedItems
=== true ) {
370 // Set it now to avoid infinite recursion in accessors
371 $oldLoadedItems = $this->mLoadedItems
;
372 $this->mLoadedItems
= true;
373 $this->queryFlagsUsed
= $flags;
375 // If this is called too early, things are likely to break.
376 if ( !$wgFullyInitialised && $this->mFrom
=== 'session' ) {
377 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
378 ->warning( 'User::loadFromSession called before the end of Setup.php', [
379 'exception' => new Exception( 'User::loadFromSession called before the end of Setup.php' ),
381 $this->loadDefaults();
382 $this->mLoadedItems
= $oldLoadedItems;
386 switch ( $this->mFrom
) {
388 $this->loadDefaults();
391 // Make sure this thread sees its own changes
392 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
393 $flags |
= self
::READ_LATEST
;
394 $this->queryFlagsUsed
= $flags;
397 $this->mId
= self
::idFromName( $this->mName
, $flags );
399 // Nonexistent user placeholder object
400 $this->loadDefaults( $this->mName
);
402 $this->loadFromId( $flags );
406 $this->loadFromId( $flags );
409 if ( !$this->loadFromSession() ) {
410 // Loading from session failed. Load defaults.
411 $this->loadDefaults();
413 Hooks
::run( 'UserLoadAfterLoadFromSession', [ $this ] );
416 throw new UnexpectedValueException(
417 "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
422 * Load user table data, given mId has already been set.
423 * @param integer $flags User::READ_* constant bitfield
424 * @return bool False if the ID does not exist, true otherwise
426 public function loadFromId( $flags = self
::READ_NORMAL
) {
427 if ( $this->mId
== 0 ) {
428 // Anonymous users are not in the database (don't need cache)
429 $this->loadDefaults();
433 // Try cache (unless this needs data from the master DB).
434 // NOTE: if this thread called saveSettings(), the cache was cleared.
435 $latest = DBAccessObjectUtils
::hasFlags( $flags, self
::READ_LATEST
);
437 if ( !$this->loadFromDatabase( $flags ) ) {
438 // Can't load from ID
442 $this->loadFromCache();
445 $this->mLoadedItems
= true;
446 $this->queryFlagsUsed
= $flags;
453 * @param string $wikiId
454 * @param integer $userId
456 public static function purge( $wikiId, $userId ) {
457 $cache = ObjectCache
::getMainWANInstance();
458 $key = $cache->makeGlobalKey( 'user', 'id', $wikiId, $userId );
459 $cache->delete( $key );
464 * @param WANObjectCache $cache
467 protected function getCacheKey( WANObjectCache
$cache ) {
468 return $cache->makeGlobalKey( 'user', 'id', wfWikiID(), $this->mId
);
472 * @param WANObjectCache $cache
476 public function getMutableCacheKeys( WANObjectCache
$cache ) {
477 $id = $this->getId();
479 return $id ?
[ $this->getCacheKey( $cache ) ] : [];
483 * Load user data from shared cache, given mId has already been set.
488 protected function loadFromCache() {
489 $cache = ObjectCache
::getMainWANInstance();
490 $data = $cache->getWithSetCallback(
491 $this->getCacheKey( $cache ),
493 function ( $oldValue, &$ttl, array &$setOpts ) use ( $cache ) {
494 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
495 wfDebug( "User: cache miss for user {$this->mId}\n" );
497 $this->loadFromDatabase( self
::READ_NORMAL
);
499 $this->loadOptions();
502 foreach ( self
::$mCacheVars as $name ) {
503 $data[$name] = $this->$name;
506 $ttl = $cache->adaptiveTTL( wfTimestamp( TS_UNIX
, $this->mTouched
), $ttl );
511 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'version' => self
::VERSION
]
514 // Restore from cache
515 foreach ( self
::$mCacheVars as $name ) {
516 $this->$name = $data[$name];
522 /** @name newFrom*() static factory methods */
526 * Static factory method for creation from username.
528 * This is slightly less efficient than newFromId(), so use newFromId() if
529 * you have both an ID and a name handy.
531 * @param string $name Username, validated by Title::newFromText()
532 * @param string|bool $validate Validate username. Takes the same parameters as
533 * User::getCanonicalName(), except that true is accepted as an alias
534 * for 'valid', for BC.
536 * @return User|bool User object, or false if the username is invalid
537 * (e.g. if it contains illegal characters or is an IP address). If the
538 * username is not present in the database, the result will be a user object
539 * with a name, zero user ID and default settings.
541 public static function newFromName( $name, $validate = 'valid' ) {
542 if ( $validate === true ) {
545 $name = self
::getCanonicalName( $name, $validate );
546 if ( $name === false ) {
549 // Create unloaded user object
553 $u->setItemLoaded( 'name' );
559 * Static factory method for creation from a given user ID.
561 * @param int $id Valid user ID
562 * @return User The corresponding User object
564 public static function newFromId( $id ) {
568 $u->setItemLoaded( 'id' );
573 * Factory method to fetch whichever user has a given email confirmation code.
574 * This code is generated when an account is created or its e-mail address
577 * If the code is invalid or has expired, returns NULL.
579 * @param string $code Confirmation code
580 * @param int $flags User::READ_* bitfield
583 public static function newFromConfirmationCode( $code, $flags = 0 ) {
584 $db = ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
585 ?
wfGetDB( DB_MASTER
)
586 : wfGetDB( DB_REPLICA
);
588 $id = $db->selectField(
592 'user_email_token' => md5( $code ),
593 'user_email_token_expires > ' . $db->addQuotes( $db->timestamp() ),
597 return $id ? User
::newFromId( $id ) : null;
601 * Create a new user object using data from session. If the login
602 * credentials are invalid, the result is an anonymous user.
604 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
607 public static function newFromSession( WebRequest
$request = null ) {
609 $user->mFrom
= 'session';
610 $user->mRequest
= $request;
615 * Create a new user object from a user row.
616 * The row should have the following fields from the user table in it:
617 * - either user_name or user_id to load further data if needed (or both)
619 * - all other fields (email, etc.)
620 * It is useless to provide the remaining fields if either user_id,
621 * user_name and user_real_name are not provided because the whole row
622 * will be loaded once more from the database when accessing them.
624 * @param stdClass $row A row from the user table
625 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
628 public static function newFromRow( $row, $data = null ) {
630 $user->loadFromRow( $row, $data );
635 * Static factory method for creation of a "system" user from username.
637 * A "system" user is an account that's used to attribute logged actions
638 * taken by MediaWiki itself, as opposed to a bot or human user. Examples
639 * might include the 'Maintenance script' or 'Conversion script' accounts
640 * used by various scripts in the maintenance/ directory or accounts such
641 * as 'MediaWiki message delivery' used by the MassMessage extension.
643 * This can optionally create the user if it doesn't exist, and "steal" the
644 * account if it does exist.
646 * "Stealing" an existing user is intended to make it impossible for normal
647 * authentication processes to use the account, effectively disabling the
648 * account for normal use:
649 * - Email is invalidated, to prevent account recovery by emailing a
650 * temporary password and to disassociate the account from the existing
652 * - The token is set to a magic invalid value, to kill existing sessions
653 * and to prevent $this->setToken() calls from resetting the token to a
655 * - SessionManager is instructed to prevent new sessions for the user, to
656 * do things like deauthorizing OAuth consumers.
657 * - AuthManager is instructed to revoke access, to invalidate or remove
658 * passwords and other credentials.
660 * @param string $name Username
661 * @param array $options Options are:
662 * - validate: As for User::getCanonicalName(), default 'valid'
663 * - create: Whether to create the user if it doesn't already exist, default true
664 * - steal: Whether to "disable" the account for normal use if it already
665 * exists, default false
669 public static function newSystemUser( $name, $options = [] ) {
671 'validate' => 'valid',
676 $name = self
::getCanonicalName( $name, $options['validate'] );
677 if ( $name === false ) {
681 $fields = self
::selectFields();
683 $dbw = wfGetDB( DB_MASTER
);
684 $row = $dbw->selectRow(
687 [ 'user_name' => $name ],
691 // No user. Create it?
692 return $options['create'] ? self
::createNew( $name, [ 'token' => self
::INVALID_TOKEN
] ) : null;
694 $user = self
::newFromRow( $row );
696 // A user is considered to exist as a non-system user if it can
697 // authenticate, or has an email set, or has a non-invalid token.
698 if ( $user->mEmail ||
$user->mToken
!== self
::INVALID_TOKEN ||
699 AuthManager
::singleton()->userCanAuthenticate( $name )
701 // User exists. Steal it?
702 if ( !$options['steal'] ) {
706 AuthManager
::singleton()->revokeAccessForUser( $name );
708 $user->invalidateEmail();
709 $user->mToken
= self
::INVALID_TOKEN
;
710 $user->saveSettings();
711 SessionManager
::singleton()->preventSessionsForUser( $user->getName() );
720 * Get the username corresponding to a given user ID
721 * @param int $id User ID
722 * @return string|bool The corresponding username
724 public static function whoIs( $id ) {
725 return UserCache
::singleton()->getProp( $id, 'name' );
729 * Get the real name of a user given their user ID
731 * @param int $id User ID
732 * @return string|bool The corresponding user's real name
734 public static function whoIsReal( $id ) {
735 return UserCache
::singleton()->getProp( $id, 'real_name' );
739 * Get database id given a user name
740 * @param string $name Username
741 * @param integer $flags User::READ_* constant bitfield
742 * @return int|null The corresponding user's ID, or null if user is nonexistent
744 public static function idFromName( $name, $flags = self
::READ_NORMAL
) {
745 $nt = Title
::makeTitleSafe( NS_USER
, $name );
746 if ( is_null( $nt ) ) {
751 if ( !( $flags & self
::READ_LATEST
) && isset( self
::$idCacheByName[$name] ) ) {
752 return self
::$idCacheByName[$name];
755 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
756 $db = wfGetDB( $index );
761 [ 'user_name' => $nt->getText() ],
766 if ( $s === false ) {
769 $result = $s->user_id
;
772 self
::$idCacheByName[$name] = $result;
774 if ( count( self
::$idCacheByName ) > 1000 ) {
775 self
::$idCacheByName = [];
782 * Reset the cache used in idFromName(). For use in tests.
784 public static function resetIdByNameCache() {
785 self
::$idCacheByName = [];
789 * Does the string match an anonymous IP address?
791 * This function exists for username validation, in order to reject
792 * usernames which are similar in form to IP addresses. Strings such
793 * as 300.300.300.300 will return true because it looks like an IP
794 * address, despite not being strictly valid.
796 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
797 * address because the usemod software would "cloak" anonymous IP
798 * addresses like this, if we allowed accounts like this to be created
799 * new users could get the old edits of these anonymous users.
801 * @param string $name Name to match
804 public static function isIP( $name ) {
805 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
806 || IP
::isIPv6( $name );
810 * Is the input a valid username?
812 * Checks if the input is a valid username, we don't want an empty string,
813 * an IP address, anything that contains slashes (would mess up subpages),
814 * is longer than the maximum allowed username size or doesn't begin with
817 * @param string $name Name to match
820 public static function isValidUserName( $name ) {
821 global $wgContLang, $wgMaxNameChars;
824 || User
::isIP( $name )
825 ||
strpos( $name, '/' ) !== false
826 ||
strlen( $name ) > $wgMaxNameChars
827 ||
$name != $wgContLang->ucfirst( $name )
832 // Ensure that the name can't be misresolved as a different title,
833 // such as with extra namespace keys at the start.
834 $parsed = Title
::newFromText( $name );
835 if ( is_null( $parsed )
836 ||
$parsed->getNamespace()
837 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
841 // Check an additional blacklist of troublemaker characters.
842 // Should these be merged into the title char list?
843 $unicodeBlacklist = '/[' .
844 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
845 '\x{00a0}' . # non-breaking space
846 '\x{2000}-\x{200f}' . # various whitespace
847 '\x{2028}-\x{202f}' . # breaks and control chars
848 '\x{3000}' . # ideographic space
849 '\x{e000}-\x{f8ff}' . # private use
851 if ( preg_match( $unicodeBlacklist, $name ) ) {
859 * Usernames which fail to pass this function will be blocked
860 * from user login and new account registrations, but may be used
861 * internally by batch processes.
863 * If an account already exists in this form, login will be blocked
864 * by a failure to pass this function.
866 * @param string $name Name to match
869 public static function isUsableName( $name ) {
870 global $wgReservedUsernames;
871 // Must be a valid username, obviously ;)
872 if ( !self
::isValidUserName( $name ) ) {
876 static $reservedUsernames = false;
877 if ( !$reservedUsernames ) {
878 $reservedUsernames = $wgReservedUsernames;
879 Hooks
::run( 'UserGetReservedNames', [ &$reservedUsernames ] );
882 // Certain names may be reserved for batch processes.
883 foreach ( $reservedUsernames as $reserved ) {
884 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
885 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
887 if ( $reserved == $name ) {
895 * Return the users who are members of the given group(s). In case of multiple groups,
896 * users who are members of at least one of them are returned.
898 * @param string|array $groups A single group name or an array of group names
899 * @param int $limit Max number of users to return. The actual limit will never exceed 5000
900 * records; larger values are ignored.
901 * @param int $after ID the user to start after
902 * @return UserArrayFromResult
904 public static function findUsersByGroup( $groups, $limit = 5000, $after = null ) {
905 if ( $groups === [] ) {
906 return UserArrayFromResult
::newFromIDs( [] );
909 $groups = array_unique( (array)$groups );
910 $limit = min( 5000, $limit );
912 $conds = [ 'ug_group' => $groups ];
913 if ( $after !== null ) {
914 $conds[] = 'ug_user > ' . (int)$after;
917 $dbr = wfGetDB( DB_REPLICA
);
918 $ids = $dbr->selectFieldValues(
925 'ORDER BY' => 'ug_user',
929 return UserArray
::newFromIDs( $ids );
933 * Usernames which fail to pass this function will be blocked
934 * from new account registrations, but may be used internally
935 * either by batch processes or by user accounts which have
936 * already been created.
938 * Additional blacklisting may be added here rather than in
939 * isValidUserName() to avoid disrupting existing accounts.
941 * @param string $name String to match
944 public static function isCreatableName( $name ) {
945 global $wgInvalidUsernameCharacters;
947 // Ensure that the username isn't longer than 235 bytes, so that
948 // (at least for the builtin skins) user javascript and css files
949 // will work. (bug 23080)
950 if ( strlen( $name ) > 235 ) {
951 wfDebugLog( 'username', __METHOD__
.
952 ": '$name' invalid due to length" );
956 // Preg yells if you try to give it an empty string
957 if ( $wgInvalidUsernameCharacters !== '' ) {
958 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
959 wfDebugLog( 'username', __METHOD__
.
960 ": '$name' invalid due to wgInvalidUsernameCharacters" );
965 return self
::isUsableName( $name );
969 * Is the input a valid password for this user?
971 * @param string $password Desired password
974 public function isValidPassword( $password ) {
975 // simple boolean wrapper for getPasswordValidity
976 return $this->getPasswordValidity( $password ) === true;
980 * Given unvalidated password input, return error message on failure.
982 * @param string $password Desired password
983 * @return bool|string|array True on success, string or array of error message on failure
985 public function getPasswordValidity( $password ) {
986 $result = $this->checkPasswordValidity( $password );
987 if ( $result->isGood() ) {
991 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
992 $messages[] = $error['message'];
994 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
995 $messages[] = $warning['message'];
997 if ( count( $messages ) === 1 ) {
1005 * Check if this is a valid password for this user
1007 * Create a Status object based on the password's validity.
1008 * The Status should be set to fatal if the user should not
1009 * be allowed to log in, and should have any errors that
1010 * would block changing the password.
1012 * If the return value of this is not OK, the password
1013 * should not be checked. If the return value is not Good,
1014 * the password can be checked, but the user should not be
1015 * able to set their password to this.
1017 * @param string $password Desired password
1021 public function checkPasswordValidity( $password ) {
1022 global $wgPasswordPolicy;
1024 $upp = new UserPasswordPolicy(
1025 $wgPasswordPolicy['policies'],
1026 $wgPasswordPolicy['checks']
1029 $status = Status
::newGood();
1030 $result = false; // init $result to false for the internal checks
1032 if ( !Hooks
::run( 'isValidPassword', [ $password, &$result, $this ] ) ) {
1033 $status->error( $result );
1037 if ( $result === false ) {
1038 $status->merge( $upp->checkUserPassword( $this, $password ) );
1040 } elseif ( $result === true ) {
1043 $status->error( $result );
1044 return $status; // the isValidPassword hook set a string $result and returned true
1049 * Given unvalidated user input, return a canonical username, or false if
1050 * the username is invalid.
1051 * @param string $name User input
1052 * @param string|bool $validate Type of validation to use:
1053 * - false No validation
1054 * - 'valid' Valid for batch processes
1055 * - 'usable' Valid for batch processes and login
1056 * - 'creatable' Valid for batch processes, login and account creation
1058 * @throws InvalidArgumentException
1059 * @return bool|string
1061 public static function getCanonicalName( $name, $validate = 'valid' ) {
1062 // Force usernames to capital
1064 $name = $wgContLang->ucfirst( $name );
1066 # Reject names containing '#'; these will be cleaned up
1067 # with title normalisation, but then it's too late to
1069 if ( strpos( $name, '#' ) !== false ) {
1073 // Clean up name according to title rules,
1074 // but only when validation is requested (bug 12654)
1075 $t = ( $validate !== false ) ?
1076 Title
::newFromText( $name, NS_USER
) : Title
::makeTitle( NS_USER
, $name );
1077 // Check for invalid titles
1078 if ( is_null( $t ) ||
$t->getNamespace() !== NS_USER ||
$t->isExternal() ) {
1082 // Reject various classes of invalid names
1083 $name = AuthManager
::callLegacyAuthPlugin(
1084 'getCanonicalName', [ $t->getText() ], $t->getText()
1087 switch ( $validate ) {
1091 if ( !User
::isValidUserName( $name ) ) {
1096 if ( !User
::isUsableName( $name ) ) {
1101 if ( !User
::isCreatableName( $name ) ) {
1106 throw new InvalidArgumentException(
1107 'Invalid parameter value for $validate in ' . __METHOD__
);
1113 * Return a random password.
1115 * @deprecated since 1.27, use PasswordFactory::generateRandomPasswordString()
1116 * @return string New random password
1118 public static function randomPassword() {
1119 global $wgMinimalPasswordLength;
1120 return PasswordFactory
::generateRandomPasswordString( $wgMinimalPasswordLength );
1124 * Set cached properties to default.
1126 * @note This no longer clears uncached lazy-initialised properties;
1127 * the constructor does that instead.
1129 * @param string|bool $name
1131 public function loadDefaults( $name = false ) {
1133 $this->mName
= $name;
1134 $this->mRealName
= '';
1136 $this->mOptionOverrides
= null;
1137 $this->mOptionsLoaded
= false;
1139 $loggedOut = $this->mRequest
&& !defined( 'MW_NO_SESSION' )
1140 ?
$this->mRequest
->getSession()->getLoggedOutTimestamp() : 0;
1141 if ( $loggedOut !== 0 ) {
1142 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1144 $this->mTouched
= '1'; # Allow any pages to be cached
1147 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1148 $this->mEmailAuthenticated
= null;
1149 $this->mEmailToken
= '';
1150 $this->mEmailTokenExpires
= null;
1151 $this->mRegistration
= wfTimestamp( TS_MW
);
1152 $this->mGroups
= [];
1154 Hooks
::run( 'UserLoadDefaults', [ $this, $name ] );
1158 * Return whether an item has been loaded.
1160 * @param string $item Item to check. Current possibilities:
1164 * @param string $all 'all' to check if the whole object has been loaded
1165 * or any other string to check if only the item is available (e.g.
1169 public function isItemLoaded( $item, $all = 'all' ) {
1170 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1171 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1175 * Set that an item has been loaded
1177 * @param string $item
1179 protected function setItemLoaded( $item ) {
1180 if ( is_array( $this->mLoadedItems
) ) {
1181 $this->mLoadedItems
[$item] = true;
1186 * Load user data from the session.
1188 * @return bool True if the user is logged in, false otherwise.
1190 private function loadFromSession() {
1193 Hooks
::run( 'UserLoadFromSession', [ $this, &$result ], '1.27' );
1194 if ( $result !== null ) {
1198 // MediaWiki\Session\Session already did the necessary authentication of the user
1199 // returned here, so just use it if applicable.
1200 $session = $this->getRequest()->getSession();
1201 $user = $session->getUser();
1202 if ( $user->isLoggedIn() ) {
1203 $this->loadFromUserObject( $user );
1205 // If this user is autoblocked, set a cookie to track the Block. This has to be done on
1206 // every session load, because an autoblocked editor might not edit again from the same
1207 // IP address after being blocked.
1208 $config = RequestContext
::getMain()->getConfig();
1209 if ( $config->get( 'CookieSetOnAutoblock' ) === true ) {
1210 $block = $this->getBlock();
1211 $shouldSetCookie = $this->getRequest()->getCookie( 'BlockID' ) === null
1213 && $block->getType() === Block
::TYPE_USER
1214 && $block->isAutoblocking();
1215 if ( $shouldSetCookie ) {
1216 wfDebug( __METHOD__
. ': User is autoblocked, setting cookie to track' );
1217 $block->setCookie( $this->getRequest()->response() );
1221 // Other code expects these to be set in the session, so set them.
1222 $session->set( 'wsUserID', $this->getId() );
1223 $session->set( 'wsUserName', $this->getName() );
1224 $session->set( 'wsToken', $this->getToken() );
1231 * Load user and user_group data from the database.
1232 * $this->mId must be set, this is how the user is identified.
1234 * @param integer $flags User::READ_* constant bitfield
1235 * @return bool True if the user exists, false if the user is anonymous
1237 public function loadFromDatabase( $flags = self
::READ_LATEST
) {
1239 $this->mId
= intval( $this->mId
);
1241 if ( !$this->mId
) {
1242 // Anonymous users are not in the database
1243 $this->loadDefaults();
1247 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
1248 $db = wfGetDB( $index );
1250 $s = $db->selectRow(
1252 self
::selectFields(),
1253 [ 'user_id' => $this->mId
],
1258 $this->queryFlagsUsed
= $flags;
1259 Hooks
::run( 'UserLoadFromDatabase', [ $this, &$s ] );
1261 if ( $s !== false ) {
1262 // Initialise user table data
1263 $this->loadFromRow( $s );
1264 $this->mGroups
= null; // deferred
1265 $this->getEditCount(); // revalidation for nulls
1270 $this->loadDefaults();
1276 * Initialize this object from a row from the user table.
1278 * @param stdClass $row Row from the user table to load.
1279 * @param array $data Further user data to load into the object
1281 * user_groups Array with groups out of the user_groups table
1282 * user_properties Array with properties out of the user_properties table
1284 protected function loadFromRow( $row, $data = null ) {
1287 $this->mGroups
= null; // deferred
1289 if ( isset( $row->user_name
) ) {
1290 $this->mName
= $row->user_name
;
1291 $this->mFrom
= 'name';
1292 $this->setItemLoaded( 'name' );
1297 if ( isset( $row->user_real_name
) ) {
1298 $this->mRealName
= $row->user_real_name
;
1299 $this->setItemLoaded( 'realname' );
1304 if ( isset( $row->user_id
) ) {
1305 $this->mId
= intval( $row->user_id
);
1306 $this->mFrom
= 'id';
1307 $this->setItemLoaded( 'id' );
1312 if ( isset( $row->user_id
) && isset( $row->user_name
) ) {
1313 self
::$idCacheByName[$row->user_name
] = $row->user_id
;
1316 if ( isset( $row->user_editcount
) ) {
1317 $this->mEditCount
= $row->user_editcount
;
1322 if ( isset( $row->user_touched
) ) {
1323 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1328 if ( isset( $row->user_token
) ) {
1329 // The definition for the column is binary(32), so trim the NULs
1330 // that appends. The previous definition was char(32), so trim
1332 $this->mToken
= rtrim( $row->user_token
, " \0" );
1333 if ( $this->mToken
=== '' ) {
1334 $this->mToken
= null;
1340 if ( isset( $row->user_email
) ) {
1341 $this->mEmail
= $row->user_email
;
1342 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1343 $this->mEmailToken
= $row->user_email_token
;
1344 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1345 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1351 $this->mLoadedItems
= true;
1354 if ( is_array( $data ) ) {
1355 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1356 $this->mGroups
= $data['user_groups'];
1358 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1359 $this->loadOptions( $data['user_properties'] );
1365 * Load the data for this user object from another user object.
1369 protected function loadFromUserObject( $user ) {
1371 foreach ( self
::$mCacheVars as $var ) {
1372 $this->$var = $user->$var;
1377 * Load the groups from the database if they aren't already loaded.
1379 private function loadGroups() {
1380 if ( is_null( $this->mGroups
) ) {
1381 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
1382 ?
wfGetDB( DB_MASTER
)
1383 : wfGetDB( DB_REPLICA
);
1384 $res = $db->select( 'user_groups',
1386 [ 'ug_user' => $this->mId
],
1388 $this->mGroups
= [];
1389 foreach ( $res as $row ) {
1390 $this->mGroups
[] = $row->ug_group
;
1396 * Add the user to the group if he/she meets given criteria.
1398 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1399 * possible to remove manually via Special:UserRights. In such case it
1400 * will not be re-added automatically. The user will also not lose the
1401 * group if they no longer meet the criteria.
1403 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1405 * @return array Array of groups the user has been promoted to.
1407 * @see $wgAutopromoteOnce
1409 public function addAutopromoteOnceGroups( $event ) {
1410 global $wgAutopromoteOnceLogInRC;
1412 if ( wfReadOnly() ||
!$this->getId() ) {
1416 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1417 if ( !count( $toPromote ) ) {
1421 if ( !$this->checkAndSetTouched() ) {
1422 return []; // raced out (bug T48834)
1425 $oldGroups = $this->getGroups(); // previous groups
1426 foreach ( $toPromote as $group ) {
1427 $this->addGroup( $group );
1429 // update groups in external authentication database
1430 Hooks
::run( 'UserGroupsChanged', [ $this, $toPromote, [], false, false ] );
1431 AuthManager
::callLegacyAuthPlugin( 'updateExternalDBGroups', [ $this, $toPromote ] );
1433 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1435 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1436 $logEntry->setPerformer( $this );
1437 $logEntry->setTarget( $this->getUserPage() );
1438 $logEntry->setParameters( [
1439 '4::oldgroups' => $oldGroups,
1440 '5::newgroups' => $newGroups,
1442 $logid = $logEntry->insert();
1443 if ( $wgAutopromoteOnceLogInRC ) {
1444 $logEntry->publish( $logid );
1451 * Builds update conditions. Additional conditions may be added to $conditions to
1452 * protected against race conditions using a compare-and-set (CAS) mechanism
1453 * based on comparing $this->mTouched with the user_touched field.
1455 * @param Database $db
1456 * @param array $conditions WHERE conditions for use with Database::update
1457 * @return array WHERE conditions for use with Database::update
1459 protected function makeUpdateConditions( Database
$db, array $conditions ) {
1460 if ( $this->mTouched
) {
1461 // CAS check: only update if the row wasn't changed sicne it was loaded.
1462 $conditions['user_touched'] = $db->timestamp( $this->mTouched
);
1469 * Bump user_touched if it didn't change since this object was loaded
1471 * On success, the mTouched field is updated.
1472 * The user serialization cache is always cleared.
1474 * @return bool Whether user_touched was actually updated
1477 protected function checkAndSetTouched() {
1480 if ( !$this->mId
) {
1481 return false; // anon
1484 // Get a new user_touched that is higher than the old one
1485 $newTouched = $this->newTouchedTimestamp();
1487 $dbw = wfGetDB( DB_MASTER
);
1488 $dbw->update( 'user',
1489 [ 'user_touched' => $dbw->timestamp( $newTouched ) ],
1490 $this->makeUpdateConditions( $dbw, [
1491 'user_id' => $this->mId
,
1495 $success = ( $dbw->affectedRows() > 0 );
1498 $this->mTouched
= $newTouched;
1499 $this->clearSharedCache();
1501 // Clears on failure too since that is desired if the cache is stale
1502 $this->clearSharedCache( 'refresh' );
1509 * Clear various cached data stored in this object. The cache of the user table
1510 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1512 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1513 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1515 public function clearInstanceCache( $reloadFrom = false ) {
1516 $this->mNewtalk
= -1;
1517 $this->mDatePreference
= null;
1518 $this->mBlockedby
= -1; # Unset
1519 $this->mHash
= false;
1520 $this->mRights
= null;
1521 $this->mEffectiveGroups
= null;
1522 $this->mImplicitGroups
= null;
1523 $this->mGroups
= null;
1524 $this->mOptions
= null;
1525 $this->mOptionsLoaded
= false;
1526 $this->mEditCount
= null;
1528 if ( $reloadFrom ) {
1529 $this->mLoadedItems
= [];
1530 $this->mFrom
= $reloadFrom;
1535 * Combine the language default options with any site-specific options
1536 * and add the default language variants.
1538 * @return array Array of String options
1540 public static function getDefaultOptions() {
1541 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1543 static $defOpt = null;
1544 static $defOptLang = null;
1546 if ( $defOpt !== null && $defOptLang === $wgContLang->getCode() ) {
1547 // $wgContLang does not change (and should not change) mid-request,
1548 // but the unit tests change it anyway, and expect this method to
1549 // return values relevant to the current $wgContLang.
1553 $defOpt = $wgDefaultUserOptions;
1554 // Default language setting
1555 $defOptLang = $wgContLang->getCode();
1556 $defOpt['language'] = $defOptLang;
1557 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1558 $defOpt[$langCode == $wgContLang->getCode() ?
'variant' : "variant-$langCode"] = $langCode;
1561 // NOTE: don't use SearchEngineConfig::getSearchableNamespaces here,
1562 // since extensions may change the set of searchable namespaces depending
1563 // on user groups/permissions.
1564 foreach ( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
1565 $defOpt['searchNs' . $nsnum] = (boolean
)$val;
1567 $defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1569 Hooks
::run( 'UserGetDefaultOptions', [ &$defOpt ] );
1575 * Get a given default option value.
1577 * @param string $opt Name of option to retrieve
1578 * @return string Default option value
1580 public static function getDefaultOption( $opt ) {
1581 $defOpts = self
::getDefaultOptions();
1582 if ( isset( $defOpts[$opt] ) ) {
1583 return $defOpts[$opt];
1590 * Get blocking information
1591 * @param bool $bFromSlave Whether to check the replica DB first.
1592 * To improve performance, non-critical checks are done against replica DBs.
1593 * Check when actually saving should be done against master.
1595 private function getBlockedStatus( $bFromSlave = true ) {
1596 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff, $wgSoftBlockRanges;
1598 if ( -1 != $this->mBlockedby
) {
1602 wfDebug( __METHOD__
. ": checking...\n" );
1604 // Initialize data...
1605 // Otherwise something ends up stomping on $this->mBlockedby when
1606 // things get lazy-loaded later, causing false positive block hits
1607 // due to -1 !== 0. Probably session-related... Nothing should be
1608 // overwriting mBlockedby, surely?
1611 # We only need to worry about passing the IP address to the Block generator if the
1612 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1613 # know which IP address they're actually coming from
1615 if ( !$this->isAllowed( 'ipblock-exempt' ) ) {
1616 // $wgUser->getName() only works after the end of Setup.php. Until
1617 // then, assume it's a logged-out user.
1618 $globalUserName = $wgUser->isSafeToLoad()
1619 ?
$wgUser->getName()
1620 : IP
::sanitizeIP( $wgUser->getRequest()->getIP() );
1621 if ( $this->getName() === $globalUserName ) {
1622 $ip = $this->getRequest()->getIP();
1627 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1629 // If no block has been found, check for a cookie indicating that the user is blocked.
1630 $blockCookieVal = (int)$this->getRequest()->getCookie( 'BlockID' );
1631 if ( !$block instanceof Block
&& $blockCookieVal > 0 ) {
1632 // Load the Block from the ID in the cookie.
1633 $tmpBlock = Block
::newFromID( $blockCookieVal );
1634 if ( $tmpBlock instanceof Block
) {
1635 // Check the validity of the block.
1636 $blockIsValid = $tmpBlock->getType() == Block
::TYPE_USER
1637 && !$tmpBlock->isExpired()
1638 && $tmpBlock->isAutoblocking();
1639 $config = RequestContext
::getMain()->getConfig();
1640 $useBlockCookie = ( $config->get( 'CookieSetOnAutoblock' ) === true );
1641 if ( $blockIsValid && $useBlockCookie ) {
1644 $this->blockTrigger
= 'cookie-block';
1646 // If the block is not valid, clear the block cookie (but don't delete it,
1647 // because it needs to be cleared from LocalStorage as well and an empty string
1648 // value is checked for in the mediawiki.user.blockcookie module).
1649 $tmpBlock->setCookie( $this->getRequest()->response(), true );
1655 if ( !$block instanceof Block
&& $ip !== null && !in_array( $ip, $wgProxyWhitelist ) ) {
1657 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1658 $block = new Block( [
1659 'byText' => wfMessage( 'proxyblocker' )->text(),
1660 'reason' => wfMessage( 'proxyblockreason' )->text(),
1662 'systemBlock' => 'proxy',
1664 $this->blockTrigger
= 'proxy-block';
1665 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1666 $block = new Block( [
1667 'byText' => wfMessage( 'sorbs' )->text(),
1668 'reason' => wfMessage( 'sorbsreason' )->text(),
1670 'systemBlock' => 'dnsbl',
1672 $this->blockTrigger
= 'openproxy-block';
1676 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1677 if ( !$block instanceof Block
1678 && $wgApplyIpBlocksToXff
1680 && !in_array( $ip, $wgProxyWhitelist )
1682 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1683 $xff = array_map( 'trim', explode( ',', $xff ) );
1684 $xff = array_diff( $xff, [ $ip ] );
1685 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1686 $block = Block
::chooseBlock( $xffblocks, $xff );
1687 if ( $block instanceof Block
) {
1688 # Mangle the reason to alert the user that the block
1689 # originated from matching the X-Forwarded-For header.
1690 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->text();
1691 $this->blockTrigger
= 'xff-block';
1695 if ( !$block instanceof Block
1698 && IP
::isInRanges( $ip, $wgSoftBlockRanges )
1700 $block = new Block( [
1702 'byText' => 'MediaWiki default',
1703 'reason' => wfMessage( 'softblockrangesreason', $ip )->text(),
1705 'systemBlock' => 'wgSoftBlockRanges',
1707 $this->blockTrigger
= 'config-block';
1710 if ( $block instanceof Block
) {
1711 wfDebug( __METHOD__
. ": Found block.\n" );
1712 $this->mBlock
= $block;
1713 $this->mBlockedby
= $block->getByName();
1714 $this->mBlockreason
= $block->mReason
;
1715 $this->mHideName
= $block->mHideName
;
1716 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1718 $this->mBlockedby
= '';
1719 $this->mHideName
= 0;
1720 $this->mAllowUsertalk
= false;
1721 $this->blockTrigger
= false;
1724 // Avoid PHP 7.1 warning of passing $this by reference
1727 Hooks
::run( 'GetBlockedStatus', [ &$user ] );
1731 * Whether the given IP is in a DNS blacklist.
1733 * @param string $ip IP to check
1734 * @param bool $checkWhitelist Whether to check the whitelist first
1735 * @return bool True if blacklisted.
1737 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1738 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1740 if ( !$wgEnableDnsBlacklist ) {
1744 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1748 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1752 * Whether the given IP is in a given DNS blacklist.
1754 * @param string $ip IP to check
1755 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1756 * @return bool True if blacklisted.
1758 public function inDnsBlacklist( $ip, $bases ) {
1760 // @todo FIXME: IPv6 ??? (https://bugs.php.net/bug.php?id=33170)
1761 if ( IP
::isIPv4( $ip ) ) {
1762 // Reverse IP, bug 21255
1763 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1765 foreach ( (array)$bases as $base ) {
1767 // If we have an access key, use that too (ProjectHoneypot, etc.)
1769 if ( is_array( $base ) ) {
1770 if ( count( $base ) >= 2 ) {
1771 // Access key is 1, base URL is 0
1772 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1774 $host = "$ipReversed.{$base[0]}";
1776 $basename = $base[0];
1778 $host = "$ipReversed.$base";
1782 $ipList = gethostbynamel( $host );
1785 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
1789 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
1798 * Check if an IP address is in the local proxy list
1804 public static function isLocallyBlockedProxy( $ip ) {
1805 global $wgProxyList;
1807 if ( !$wgProxyList ) {
1811 if ( !is_array( $wgProxyList ) ) {
1812 // Load values from the specified file
1813 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1816 if ( is_array( $wgProxyList ) ) {
1818 // Look for IP as value
1819 array_search( $ip, $wgProxyList ) !== false ||
1820 // Look for IP as key (for backwards-compatility)
1821 array_key_exists( $ip, $wgProxyList )
1831 * Is this user subject to rate limiting?
1833 * @return bool True if rate limited
1835 public function isPingLimitable() {
1836 global $wgRateLimitsExcludedIPs;
1837 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1838 // No other good way currently to disable rate limits
1839 // for specific IPs. :P
1840 // But this is a crappy hack and should die.
1843 return !$this->isAllowed( 'noratelimit' );
1847 * Primitive rate limits: enforce maximum actions per time period
1848 * to put a brake on flooding.
1850 * The method generates both a generic profiling point and a per action one
1851 * (suffix being "-$action".
1853 * @note When using a shared cache like memcached, IP-address
1854 * last-hit counters will be shared across wikis.
1856 * @param string $action Action to enforce; 'edit' if unspecified
1857 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1858 * @return bool True if a rate limiter was tripped
1860 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1861 // Avoid PHP 7.1 warning of passing $this by reference
1863 // Call the 'PingLimiter' hook
1865 if ( !Hooks
::run( 'PingLimiter', [ &$user, $action, &$result, $incrBy ] ) ) {
1869 global $wgRateLimits;
1870 if ( !isset( $wgRateLimits[$action] ) ) {
1874 $limits = array_merge(
1875 [ '&can-bypass' => true ],
1876 $wgRateLimits[$action]
1879 // Some groups shouldn't trigger the ping limiter, ever
1880 if ( $limits['&can-bypass'] && !$this->isPingLimitable() ) {
1885 $id = $this->getId();
1887 $isNewbie = $this->isNewbie();
1891 if ( isset( $limits['anon'] ) ) {
1892 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1895 // limits for logged-in users
1896 if ( isset( $limits['user'] ) ) {
1897 $userLimit = $limits['user'];
1899 // limits for newbie logged-in users
1900 if ( $isNewbie && isset( $limits['newbie'] ) ) {
1901 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1905 // limits for anons and for newbie logged-in users
1908 if ( isset( $limits['ip'] ) ) {
1909 $ip = $this->getRequest()->getIP();
1910 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1912 // subnet-based limits
1913 if ( isset( $limits['subnet'] ) ) {
1914 $ip = $this->getRequest()->getIP();
1915 $subnet = IP
::getSubnet( $ip );
1916 if ( $subnet !== false ) {
1917 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1922 // Check for group-specific permissions
1923 // If more than one group applies, use the group with the highest limit ratio (max/period)
1924 foreach ( $this->getGroups() as $group ) {
1925 if ( isset( $limits[$group] ) ) {
1926 if ( $userLimit === false
1927 ||
$limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1929 $userLimit = $limits[$group];
1934 // Set the user limit key
1935 if ( $userLimit !== false ) {
1936 list( $max, $period ) = $userLimit;
1937 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
1938 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1941 // ip-based limits for all ping-limitable users
1942 if ( isset( $limits['ip-all'] ) ) {
1943 $ip = $this->getRequest()->getIP();
1944 // ignore if user limit is more permissive
1945 if ( $isNewbie ||
$userLimit === false
1946 ||
$limits['ip-all'][0] / $limits['ip-all'][1] > $userLimit[0] / $userLimit[1] ) {
1947 $keys["mediawiki:limiter:$action:ip-all:$ip"] = $limits['ip-all'];
1951 // subnet-based limits for all ping-limitable users
1952 if ( isset( $limits['subnet-all'] ) ) {
1953 $ip = $this->getRequest()->getIP();
1954 $subnet = IP
::getSubnet( $ip );
1955 if ( $subnet !== false ) {
1956 // ignore if user limit is more permissive
1957 if ( $isNewbie ||
$userLimit === false
1958 ||
$limits['ip-all'][0] / $limits['ip-all'][1]
1959 > $userLimit[0] / $userLimit[1] ) {
1960 $keys["mediawiki:limiter:$action:subnet-all:$subnet"] = $limits['subnet-all'];
1965 $cache = ObjectCache
::getLocalClusterInstance();
1968 foreach ( $keys as $key => $limit ) {
1969 list( $max, $period ) = $limit;
1970 $summary = "(limit $max in {$period}s)";
1971 $count = $cache->get( $key );
1974 if ( $count >= $max ) {
1975 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1976 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1979 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1982 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1983 if ( $incrBy > 0 ) {
1984 $cache->add( $key, 0, intval( $period ) ); // first ping
1987 if ( $incrBy > 0 ) {
1988 $cache->incr( $key, $incrBy );
1996 * Check if user is blocked
1998 * @param bool $bFromSlave Whether to check the replica DB instead of
1999 * the master. Hacked from false due to horrible probs on site.
2000 * @return bool True if blocked, false otherwise
2002 public function isBlocked( $bFromSlave = true ) {
2003 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
2007 * Get the block affecting the user, or null if the user is not blocked
2009 * @param bool $bFromSlave Whether to check the replica DB instead of the master
2010 * @return Block|null
2012 public function getBlock( $bFromSlave = true ) {
2013 $this->getBlockedStatus( $bFromSlave );
2014 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
2018 * Check if user is blocked from editing a particular article
2020 * @param Title $title Title to check
2021 * @param bool $bFromSlave Whether to check the replica DB instead of the master
2024 public function isBlockedFrom( $title, $bFromSlave = false ) {
2025 global $wgBlockAllowsUTEdit;
2027 $blocked = $this->isBlocked( $bFromSlave );
2028 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
2029 // If a user's name is suppressed, they cannot make edits anywhere
2030 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName()
2031 && $title->getNamespace() == NS_USER_TALK
) {
2033 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
2036 Hooks
::run( 'UserIsBlockedFrom', [ $this, $title, &$blocked, &$allowUsertalk ] );
2042 * If user is blocked, return the name of the user who placed the block
2043 * @return string Name of blocker
2045 public function blockedBy() {
2046 $this->getBlockedStatus();
2047 return $this->mBlockedby
;
2051 * If user is blocked, return the specified reason for the block
2052 * @return string Blocking reason
2054 public function blockedFor() {
2055 $this->getBlockedStatus();
2056 return $this->mBlockreason
;
2060 * If user is blocked, return the ID for the block
2061 * @return int Block ID
2063 public function getBlockId() {
2064 $this->getBlockedStatus();
2065 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
2069 * Check if user is blocked on all wikis.
2070 * Do not use for actual edit permission checks!
2071 * This is intended for quick UI checks.
2073 * @param string $ip IP address, uses current client if none given
2074 * @return bool True if blocked, false otherwise
2076 public function isBlockedGlobally( $ip = '' ) {
2077 return $this->getGlobalBlock( $ip ) instanceof Block
;
2081 * Check if user is blocked on all wikis.
2082 * Do not use for actual edit permission checks!
2083 * This is intended for quick UI checks.
2085 * @param string $ip IP address, uses current client if none given
2086 * @return Block|null Block object if blocked, null otherwise
2087 * @throws FatalError
2088 * @throws MWException
2090 public function getGlobalBlock( $ip = '' ) {
2091 if ( $this->mGlobalBlock
!== null ) {
2092 return $this->mGlobalBlock ?
: null;
2094 // User is already an IP?
2095 if ( IP
::isIPAddress( $this->getName() ) ) {
2096 $ip = $this->getName();
2098 $ip = $this->getRequest()->getIP();
2100 // Avoid PHP 7.1 warning of passing $this by reference
2104 Hooks
::run( 'UserIsBlockedGlobally', [ &$user, $ip, &$blocked, &$block ] );
2106 if ( $blocked && $block === null ) {
2107 // back-compat: UserIsBlockedGlobally didn't have $block param first
2108 $block = new Block( [
2110 'systemBlock' => 'global-block'
2114 $this->mGlobalBlock
= $blocked ?
$block : false;
2115 return $this->mGlobalBlock ?
: null;
2119 * Check if user account is locked
2121 * @return bool True if locked, false otherwise
2123 public function isLocked() {
2124 if ( $this->mLocked
!== null ) {
2125 return $this->mLocked
;
2127 // Avoid PHP 7.1 warning of passing $this by reference
2129 $authUser = AuthManager
::callLegacyAuthPlugin( 'getUserInstance', [ &$user ], null );
2130 $this->mLocked
= $authUser && $authUser->isLocked();
2131 Hooks
::run( 'UserIsLocked', [ $this, &$this->mLocked
] );
2132 return $this->mLocked
;
2136 * Check if user account is hidden
2138 * @return bool True if hidden, false otherwise
2140 public function isHidden() {
2141 if ( $this->mHideName
!== null ) {
2142 return $this->mHideName
;
2144 $this->getBlockedStatus();
2145 if ( !$this->mHideName
) {
2146 // Avoid PHP 7.1 warning of passing $this by reference
2148 $authUser = AuthManager
::callLegacyAuthPlugin( 'getUserInstance', [ &$user ], null );
2149 $this->mHideName
= $authUser && $authUser->isHidden();
2150 Hooks
::run( 'UserIsHidden', [ $this, &$this->mHideName
] );
2152 return $this->mHideName
;
2156 * Get the user's ID.
2157 * @return int The user's ID; 0 if the user is anonymous or nonexistent
2159 public function getId() {
2160 if ( $this->mId
=== null && $this->mName
!== null && User
::isIP( $this->mName
) ) {
2161 // Special case, we know the user is anonymous
2163 } elseif ( !$this->isItemLoaded( 'id' ) ) {
2164 // Don't load if this was initialized from an ID
2168 return (int)$this->mId
;
2172 * Set the user and reload all fields according to a given ID
2173 * @param int $v User ID to reload
2175 public function setId( $v ) {
2177 $this->clearInstanceCache( 'id' );
2181 * Get the user name, or the IP of an anonymous user
2182 * @return string User's name or IP address
2184 public function getName() {
2185 if ( $this->isItemLoaded( 'name', 'only' ) ) {
2186 // Special case optimisation
2187 return $this->mName
;
2190 if ( $this->mName
=== false ) {
2192 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
2194 return $this->mName
;
2199 * Set the user name.
2201 * This does not reload fields from the database according to the given
2202 * name. Rather, it is used to create a temporary "nonexistent user" for
2203 * later addition to the database. It can also be used to set the IP
2204 * address for an anonymous user to something other than the current
2207 * @note User::newFromName() has roughly the same function, when the named user
2209 * @param string $str New user name to set
2211 public function setName( $str ) {
2213 $this->mName
= $str;
2217 * Get the user's name escaped by underscores.
2218 * @return string Username escaped by underscores.
2220 public function getTitleKey() {
2221 return str_replace( ' ', '_', $this->getName() );
2225 * Check if the user has new messages.
2226 * @return bool True if the user has new messages
2228 public function getNewtalk() {
2231 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2232 if ( $this->mNewtalk
=== -1 ) {
2233 $this->mNewtalk
= false; # reset talk page status
2235 // Check memcached separately for anons, who have no
2236 // entire User object stored in there.
2237 if ( !$this->mId
) {
2238 global $wgDisableAnonTalk;
2239 if ( $wgDisableAnonTalk ) {
2240 // Anon newtalk disabled by configuration.
2241 $this->mNewtalk
= false;
2243 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
2246 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2250 return (bool)$this->mNewtalk
;
2254 * Return the data needed to construct links for new talk page message
2255 * alerts. If there are new messages, this will return an associative array
2256 * with the following data:
2257 * wiki: The database name of the wiki
2258 * link: Root-relative link to the user's talk page
2259 * rev: The last talk page revision that the user has seen or null. This
2260 * is useful for building diff links.
2261 * If there are no new messages, it returns an empty array.
2262 * @note This function was designed to accomodate multiple talk pages, but
2263 * currently only returns a single link and revision.
2266 public function getNewMessageLinks() {
2267 // Avoid PHP 7.1 warning of passing $this by reference
2270 if ( !Hooks
::run( 'UserRetrieveNewTalks', [ &$user, &$talks ] ) ) {
2272 } elseif ( !$this->getNewtalk() ) {
2275 $utp = $this->getTalkPage();
2276 $dbr = wfGetDB( DB_REPLICA
);
2277 // Get the "last viewed rev" timestamp from the oldest message notification
2278 $timestamp = $dbr->selectField( 'user_newtalk',
2279 'MIN(user_last_timestamp)',
2280 $this->isAnon() ?
[ 'user_ip' => $this->getName() ] : [ 'user_id' => $this->getId() ],
2282 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2283 return [ [ 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ] ];
2287 * Get the revision ID for the last talk page revision viewed by the talk
2289 * @return int|null Revision ID or null
2291 public function getNewMessageRevisionId() {
2292 $newMessageRevisionId = null;
2293 $newMessageLinks = $this->getNewMessageLinks();
2294 if ( $newMessageLinks ) {
2295 // Note: getNewMessageLinks() never returns more than a single link
2296 // and it is always for the same wiki, but we double-check here in
2297 // case that changes some time in the future.
2298 if ( count( $newMessageLinks ) === 1
2299 && $newMessageLinks[0]['wiki'] === wfWikiID()
2300 && $newMessageLinks[0]['rev']
2302 /** @var Revision $newMessageRevision */
2303 $newMessageRevision = $newMessageLinks[0]['rev'];
2304 $newMessageRevisionId = $newMessageRevision->getId();
2307 return $newMessageRevisionId;
2311 * Internal uncached check for new messages
2314 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2315 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2316 * @return bool True if the user has new messages
2318 protected function checkNewtalk( $field, $id ) {
2319 $dbr = wfGetDB( DB_REPLICA
);
2321 $ok = $dbr->selectField( 'user_newtalk', $field, [ $field => $id ], __METHOD__
);
2323 return $ok !== false;
2327 * Add or update the new messages flag
2328 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2329 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2330 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2331 * @return bool True if successful, false otherwise
2333 protected function updateNewtalk( $field, $id, $curRev = null ) {
2334 // Get timestamp of the talk page revision prior to the current one
2335 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2336 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2337 // Mark the user as having new messages since this revision
2338 $dbw = wfGetDB( DB_MASTER
);
2339 $dbw->insert( 'user_newtalk',
2340 [ $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ],
2343 if ( $dbw->affectedRows() ) {
2344 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2347 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2353 * Clear the new messages flag for the given user
2354 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2355 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2356 * @return bool True if successful, false otherwise
2358 protected function deleteNewtalk( $field, $id ) {
2359 $dbw = wfGetDB( DB_MASTER
);
2360 $dbw->delete( 'user_newtalk',
2363 if ( $dbw->affectedRows() ) {
2364 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2367 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2373 * Update the 'You have new messages!' status.
2374 * @param bool $val Whether the user has new messages
2375 * @param Revision $curRev New, as yet unseen revision of the user talk
2376 * page. Ignored if null or !$val.
2378 public function setNewtalk( $val, $curRev = null ) {
2379 if ( wfReadOnly() ) {
2384 $this->mNewtalk
= $val;
2386 if ( $this->isAnon() ) {
2388 $id = $this->getName();
2391 $id = $this->getId();
2395 $changed = $this->updateNewtalk( $field, $id, $curRev );
2397 $changed = $this->deleteNewtalk( $field, $id );
2401 $this->invalidateCache();
2406 * Generate a current or new-future timestamp to be stored in the
2407 * user_touched field when we update things.
2408 * @return string Timestamp in TS_MW format
2410 private function newTouchedTimestamp() {
2411 global $wgClockSkewFudge;
2413 $time = wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2414 if ( $this->mTouched
&& $time <= $this->mTouched
) {
2415 $time = wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $this->mTouched
) +
1 );
2422 * Clear user data from memcached
2424 * Use after applying updates to the database; caller's
2425 * responsibility to update user_touched if appropriate.
2427 * Called implicitly from invalidateCache() and saveSettings().
2429 * @param string $mode Use 'refresh' to clear now; otherwise before DB commit
2431 public function clearSharedCache( $mode = 'changed' ) {
2432 if ( !$this->getId() ) {
2436 $cache = ObjectCache
::getMainWANInstance();
2437 $key = $this->getCacheKey( $cache );
2438 if ( $mode === 'refresh' ) {
2439 $cache->delete( $key, 1 );
2441 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle(
2442 function() use ( $cache, $key ) {
2443 $cache->delete( $key );
2451 * Immediately touch the user data cache for this account
2453 * Calls touch() and removes account data from memcached
2455 public function invalidateCache() {
2457 $this->clearSharedCache();
2461 * Update the "touched" timestamp for the user
2463 * This is useful on various login/logout events when making sure that
2464 * a browser or proxy that has multiple tenants does not suffer cache
2465 * pollution where the new user sees the old users content. The value
2466 * of getTouched() is checked when determining 304 vs 200 responses.
2467 * Unlike invalidateCache(), this preserves the User object cache and
2468 * avoids database writes.
2472 public function touch() {
2473 $id = $this->getId();
2475 $key = wfMemcKey( 'user-quicktouched', 'id', $id );
2476 ObjectCache
::getMainWANInstance()->touchCheckKey( $key );
2477 $this->mQuickTouched
= null;
2482 * Validate the cache for this account.
2483 * @param string $timestamp A timestamp in TS_MW format
2486 public function validateCache( $timestamp ) {
2487 return ( $timestamp >= $this->getTouched() );
2491 * Get the user touched timestamp
2493 * Use this value only to validate caches via inequalities
2494 * such as in the case of HTTP If-Modified-Since response logic
2496 * @return string TS_MW Timestamp
2498 public function getTouched() {
2502 if ( $this->mQuickTouched
=== null ) {
2503 $key = wfMemcKey( 'user-quicktouched', 'id', $this->mId
);
2504 $cache = ObjectCache
::getMainWANInstance();
2506 $this->mQuickTouched
= wfTimestamp( TS_MW
, $cache->getCheckKeyTime( $key ) );
2509 return max( $this->mTouched
, $this->mQuickTouched
);
2512 return $this->mTouched
;
2516 * Get the user_touched timestamp field (time of last DB updates)
2517 * @return string TS_MW Timestamp
2520 public function getDBTouched() {
2523 return $this->mTouched
;
2527 * Set the password and reset the random token.
2528 * Calls through to authentication plugin if necessary;
2529 * will have no effect if the auth plugin refuses to
2530 * pass the change through or if the legal password
2533 * As a special case, setting the password to null
2534 * wipes it, so the account cannot be logged in until
2535 * a new password is set, for instance via e-mail.
2537 * @deprecated since 1.27, use AuthManager instead
2538 * @param string $str New password to set
2539 * @throws PasswordError On failure
2542 public function setPassword( $str ) {
2543 return $this->setPasswordInternal( $str );
2547 * Set the password and reset the random token unconditionally.
2549 * @deprecated since 1.27, use AuthManager instead
2550 * @param string|null $str New password to set or null to set an invalid
2551 * password hash meaning that the user will not be able to log in
2552 * through the web interface.
2554 public function setInternalPassword( $str ) {
2555 $this->setPasswordInternal( $str );
2559 * Actually set the password and such
2560 * @since 1.27 cannot set a password for a user not in the database
2561 * @param string|null $str New password to set or null to set an invalid
2562 * password hash meaning that the user will not be able to log in
2563 * through the web interface.
2564 * @return bool Success
2566 private function setPasswordInternal( $str ) {
2567 $manager = AuthManager
::singleton();
2569 // If the user doesn't exist yet, fail
2570 if ( !$manager->userExists( $this->getName() ) ) {
2571 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2574 $status = $this->changeAuthenticationData( [
2575 'username' => $this->getName(),
2579 if ( !$status->isGood() ) {
2580 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
2581 ->info( __METHOD__
. ': Password change rejected: '
2582 . $status->getWikiText( null, null, 'en' ) );
2586 $this->setOption( 'watchlisttoken', false );
2587 SessionManager
::singleton()->invalidateSessionsForUser( $this );
2593 * Changes credentials of the user.
2595 * This is a convenience wrapper around AuthManager::changeAuthenticationData.
2596 * Note that this can return a status that isOK() but not isGood() on certain types of failures,
2597 * e.g. when no provider handled the change.
2599 * @param array $data A set of authentication data in fieldname => value format. This is the
2600 * same data you would pass the changeauthenticationdata API - 'username', 'password' etc.
2604 public function changeAuthenticationData( array $data ) {
2605 $manager = AuthManager
::singleton();
2606 $reqs = $manager->getAuthenticationRequests( AuthManager
::ACTION_CHANGE
, $this );
2607 $reqs = AuthenticationRequest
::loadRequestsFromSubmission( $reqs, $data );
2609 $status = Status
::newGood( 'ignored' );
2610 foreach ( $reqs as $req ) {
2611 $status->merge( $manager->allowsAuthenticationDataChange( $req ), true );
2613 if ( $status->getValue() === 'ignored' ) {
2614 $status->warning( 'authenticationdatachange-ignored' );
2617 if ( $status->isGood() ) {
2618 foreach ( $reqs as $req ) {
2619 $manager->changeAuthenticationData( $req );
2626 * Get the user's current token.
2627 * @param bool $forceCreation Force the generation of a new token if the
2628 * user doesn't have one (default=true for backwards compatibility).
2629 * @return string|null Token
2631 public function getToken( $forceCreation = true ) {
2632 global $wgAuthenticationTokenVersion;
2635 if ( !$this->mToken
&& $forceCreation ) {
2639 if ( !$this->mToken
) {
2640 // The user doesn't have a token, return null to indicate that.
2642 } elseif ( $this->mToken
=== self
::INVALID_TOKEN
) {
2643 // We return a random value here so existing token checks are very
2645 return MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2646 } elseif ( $wgAuthenticationTokenVersion === null ) {
2647 // $wgAuthenticationTokenVersion not in use, so return the raw secret
2648 return $this->mToken
;
2650 // $wgAuthenticationTokenVersion in use, so hmac it.
2651 $ret = MWCryptHash
::hmac( $wgAuthenticationTokenVersion, $this->mToken
, false );
2653 // The raw hash can be overly long. Shorten it up.
2654 $len = max( 32, self
::TOKEN_LENGTH
);
2655 if ( strlen( $ret ) < $len ) {
2656 // Should never happen, even md5 is 128 bits
2657 throw new \
UnexpectedValueException( 'Hmac returned less than 128 bits' );
2659 return substr( $ret, -$len );
2664 * Set the random token (used for persistent authentication)
2665 * Called from loadDefaults() among other places.
2667 * @param string|bool $token If specified, set the token to this value
2669 public function setToken( $token = false ) {
2671 if ( $this->mToken
=== self
::INVALID_TOKEN
) {
2672 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
2673 ->debug( __METHOD__
. ": Ignoring attempt to set token for system user \"$this\"" );
2674 } elseif ( !$token ) {
2675 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2677 $this->mToken
= $token;
2682 * Set the password for a password reminder or new account email
2684 * @deprecated Removed in 1.27. Use PasswordReset instead.
2685 * @param string $str New password to set or null to set an invalid
2686 * password hash meaning that the user will not be able to use it
2687 * @param bool $throttle If true, reset the throttle timestamp to the present
2689 public function setNewpassword( $str, $throttle = true ) {
2690 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2694 * Get the user's e-mail address
2695 * @return string User's email address
2697 public function getEmail() {
2699 Hooks
::run( 'UserGetEmail', [ $this, &$this->mEmail
] );
2700 return $this->mEmail
;
2704 * Get the timestamp of the user's e-mail authentication
2705 * @return string TS_MW timestamp
2707 public function getEmailAuthenticationTimestamp() {
2709 Hooks
::run( 'UserGetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
2710 return $this->mEmailAuthenticated
;
2714 * Set the user's e-mail address
2715 * @param string $str New e-mail address
2717 public function setEmail( $str ) {
2719 if ( $str == $this->mEmail
) {
2722 $this->invalidateEmail();
2723 $this->mEmail
= $str;
2724 Hooks
::run( 'UserSetEmail', [ $this, &$this->mEmail
] );
2728 * Set the user's e-mail address and a confirmation mail if needed.
2731 * @param string $str New e-mail address
2734 public function setEmailWithConfirmation( $str ) {
2735 global $wgEnableEmail, $wgEmailAuthentication;
2737 if ( !$wgEnableEmail ) {
2738 return Status
::newFatal( 'emaildisabled' );
2741 $oldaddr = $this->getEmail();
2742 if ( $str === $oldaddr ) {
2743 return Status
::newGood( true );
2746 $type = $oldaddr != '' ?
'changed' : 'set';
2747 $notificationResult = null;
2749 if ( $wgEmailAuthentication ) {
2750 // Send the user an email notifying the user of the change in registered
2751 // email address on their previous email address
2752 if ( $type == 'changed' ) {
2753 $change = $str != '' ?
'changed' : 'removed';
2754 $notificationResult = $this->sendMail(
2755 wfMessage( 'notificationemail_subject_' . $change )->text(),
2756 wfMessage( 'notificationemail_body_' . $change,
2757 $this->getRequest()->getIP(),
2764 $this->setEmail( $str );
2766 if ( $str !== '' && $wgEmailAuthentication ) {
2767 // Send a confirmation request to the new address if needed
2768 $result = $this->sendConfirmationMail( $type );
2770 if ( $notificationResult !== null ) {
2771 $result->merge( $notificationResult );
2774 if ( $result->isGood() ) {
2775 // Say to the caller that a confirmation and notification mail has been sent
2776 $result->value
= 'eauth';
2779 $result = Status
::newGood( true );
2786 * Get the user's real name
2787 * @return string User's real name
2789 public function getRealName() {
2790 if ( !$this->isItemLoaded( 'realname' ) ) {
2794 return $this->mRealName
;
2798 * Set the user's real name
2799 * @param string $str New real name
2801 public function setRealName( $str ) {
2803 $this->mRealName
= $str;
2807 * Get the user's current setting for a given option.
2809 * @param string $oname The option to check
2810 * @param string $defaultOverride A default value returned if the option does not exist
2811 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2812 * @return string|null User's current value for the option
2813 * @see getBoolOption()
2814 * @see getIntOption()
2816 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2817 global $wgHiddenPrefs;
2818 $this->loadOptions();
2820 # We want 'disabled' preferences to always behave as the default value for
2821 # users, even if they have set the option explicitly in their settings (ie they
2822 # set it, and then it was disabled removing their ability to change it). But
2823 # we don't want to erase the preferences in the database in case the preference
2824 # is re-enabled again. So don't touch $mOptions, just override the returned value
2825 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2826 return self
::getDefaultOption( $oname );
2829 if ( array_key_exists( $oname, $this->mOptions
) ) {
2830 return $this->mOptions
[$oname];
2832 return $defaultOverride;
2837 * Get all user's options
2839 * @param int $flags Bitwise combination of:
2840 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2841 * to the default value. (Since 1.25)
2844 public function getOptions( $flags = 0 ) {
2845 global $wgHiddenPrefs;
2846 $this->loadOptions();
2847 $options = $this->mOptions
;
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 foreach ( $wgHiddenPrefs as $pref ) {
2855 $default = self
::getDefaultOption( $pref );
2856 if ( $default !== null ) {
2857 $options[$pref] = $default;
2861 if ( $flags & self
::GETOPTIONS_EXCLUDE_DEFAULTS
) {
2862 $options = array_diff_assoc( $options, self
::getDefaultOptions() );
2869 * Get the user's current setting for a given option, as a boolean value.
2871 * @param string $oname The option to check
2872 * @return bool User's current value for the option
2875 public function getBoolOption( $oname ) {
2876 return (bool)$this->getOption( $oname );
2880 * Get the user's current setting for a given option, as an integer value.
2882 * @param string $oname The option to check
2883 * @param int $defaultOverride A default value returned if the option does not exist
2884 * @return int User's current value for the option
2887 public function getIntOption( $oname, $defaultOverride = 0 ) {
2888 $val = $this->getOption( $oname );
2890 $val = $defaultOverride;
2892 return intval( $val );
2896 * Set the given option for a user.
2898 * You need to call saveSettings() to actually write to the database.
2900 * @param string $oname The option to set
2901 * @param mixed $val New value to set
2903 public function setOption( $oname, $val ) {
2904 $this->loadOptions();
2906 // Explicitly NULL values should refer to defaults
2907 if ( is_null( $val ) ) {
2908 $val = self
::getDefaultOption( $oname );
2911 $this->mOptions
[$oname] = $val;
2915 * Get a token stored in the preferences (like the watchlist one),
2916 * resetting it if it's empty (and saving changes).
2918 * @param string $oname The option name to retrieve the token from
2919 * @return string|bool User's current value for the option, or false if this option is disabled.
2920 * @see resetTokenFromOption()
2922 * @deprecated since 1.26 Applications should use the OAuth extension
2924 public function getTokenFromOption( $oname ) {
2925 global $wgHiddenPrefs;
2927 $id = $this->getId();
2928 if ( !$id ||
in_array( $oname, $wgHiddenPrefs ) ) {
2932 $token = $this->getOption( $oname );
2934 // Default to a value based on the user token to avoid space
2935 // wasted on storing tokens for all users. When this option
2936 // is set manually by the user, only then is it stored.
2937 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
2944 * Reset a token stored in the preferences (like the watchlist one).
2945 * *Does not* save user's preferences (similarly to setOption()).
2947 * @param string $oname The option name to reset the token in
2948 * @return string|bool New token value, or false if this option is disabled.
2949 * @see getTokenFromOption()
2952 public function resetTokenFromOption( $oname ) {
2953 global $wgHiddenPrefs;
2954 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2958 $token = MWCryptRand
::generateHex( 40 );
2959 $this->setOption( $oname, $token );
2964 * Return a list of the types of user options currently returned by
2965 * User::getOptionKinds().
2967 * Currently, the option kinds are:
2968 * - 'registered' - preferences which are registered in core MediaWiki or
2969 * by extensions using the UserGetDefaultOptions hook.
2970 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2971 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2972 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2973 * be used by user scripts.
2974 * - 'special' - "preferences" that are not accessible via User::getOptions
2975 * or User::setOptions.
2976 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2977 * These are usually legacy options, removed in newer versions.
2979 * The API (and possibly others) use this function to determine the possible
2980 * option types for validation purposes, so make sure to update this when a
2981 * new option kind is added.
2983 * @see User::getOptionKinds
2984 * @return array Option kinds
2986 public static function listOptionKinds() {
2989 'registered-multiselect',
2990 'registered-checkmatrix',
2998 * Return an associative array mapping preferences keys to the kind of a preference they're
2999 * used for. Different kinds are handled differently when setting or reading preferences.
3001 * See User::listOptionKinds for the list of valid option types that can be provided.
3003 * @see User::listOptionKinds
3004 * @param IContextSource $context
3005 * @param array $options Assoc. array with options keys to check as keys.
3006 * Defaults to $this->mOptions.
3007 * @return array The key => kind mapping data
3009 public function getOptionKinds( IContextSource
$context, $options = null ) {
3010 $this->loadOptions();
3011 if ( $options === null ) {
3012 $options = $this->mOptions
;
3015 $prefs = Preferences
::getPreferences( $this, $context );
3018 // Pull out the "special" options, so they don't get converted as
3019 // multiselect or checkmatrix.
3020 $specialOptions = array_fill_keys( Preferences
::getSaveBlacklist(), true );
3021 foreach ( $specialOptions as $name => $value ) {
3022 unset( $prefs[$name] );
3025 // Multiselect and checkmatrix options are stored in the database with
3026 // one key per option, each having a boolean value. Extract those keys.
3027 $multiselectOptions = [];
3028 foreach ( $prefs as $name => $info ) {
3029 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
3030 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
3031 $opts = HTMLFormField
::flattenOptions( $info['options'] );
3032 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
3034 foreach ( $opts as $value ) {
3035 $multiselectOptions["$prefix$value"] = true;
3038 unset( $prefs[$name] );
3041 $checkmatrixOptions = [];
3042 foreach ( $prefs as $name => $info ) {
3043 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
3044 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
3045 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
3046 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
3047 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
3049 foreach ( $columns as $column ) {
3050 foreach ( $rows as $row ) {
3051 $checkmatrixOptions["$prefix$column-$row"] = true;
3055 unset( $prefs[$name] );
3059 // $value is ignored
3060 foreach ( $options as $key => $value ) {
3061 if ( isset( $prefs[$key] ) ) {
3062 $mapping[$key] = 'registered';
3063 } elseif ( isset( $multiselectOptions[$key] ) ) {
3064 $mapping[$key] = 'registered-multiselect';
3065 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
3066 $mapping[$key] = 'registered-checkmatrix';
3067 } elseif ( isset( $specialOptions[$key] ) ) {
3068 $mapping[$key] = 'special';
3069 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
3070 $mapping[$key] = 'userjs';
3072 $mapping[$key] = 'unused';
3080 * Reset certain (or all) options to the site defaults
3082 * The optional parameter determines which kinds of preferences will be reset.
3083 * Supported values are everything that can be reported by getOptionKinds()
3084 * and 'all', which forces a reset of *all* preferences and overrides everything else.
3086 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
3087 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
3088 * for backwards-compatibility.
3089 * @param IContextSource|null $context Context source used when $resetKinds
3090 * does not contain 'all', passed to getOptionKinds().
3091 * Defaults to RequestContext::getMain() when null.
3093 public function resetOptions(
3094 $resetKinds = [ 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ],
3095 IContextSource
$context = null
3098 $defaultOptions = self
::getDefaultOptions();
3100 if ( !is_array( $resetKinds ) ) {
3101 $resetKinds = [ $resetKinds ];
3104 if ( in_array( 'all', $resetKinds ) ) {
3105 $newOptions = $defaultOptions;
3107 if ( $context === null ) {
3108 $context = RequestContext
::getMain();
3111 $optionKinds = $this->getOptionKinds( $context );
3112 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
3115 // Use default values for the options that should be deleted, and
3116 // copy old values for the ones that shouldn't.
3117 foreach ( $this->mOptions
as $key => $value ) {
3118 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
3119 if ( array_key_exists( $key, $defaultOptions ) ) {
3120 $newOptions[$key] = $defaultOptions[$key];
3123 $newOptions[$key] = $value;
3128 Hooks
::run( 'UserResetAllOptions', [ $this, &$newOptions, $this->mOptions
, $resetKinds ] );
3130 $this->mOptions
= $newOptions;
3131 $this->mOptionsLoaded
= true;
3135 * Get the user's preferred date format.
3136 * @return string User's preferred date format
3138 public function getDatePreference() {
3139 // Important migration for old data rows
3140 if ( is_null( $this->mDatePreference
) ) {
3142 $value = $this->getOption( 'date' );
3143 $map = $wgLang->getDatePreferenceMigrationMap();
3144 if ( isset( $map[$value] ) ) {
3145 $value = $map[$value];
3147 $this->mDatePreference
= $value;
3149 return $this->mDatePreference
;
3153 * Determine based on the wiki configuration and the user's options,
3154 * whether this user must be over HTTPS no matter what.
3158 public function requiresHTTPS() {
3159 global $wgSecureLogin;
3160 if ( !$wgSecureLogin ) {
3163 $https = $this->getBoolOption( 'prefershttps' );
3164 Hooks
::run( 'UserRequiresHTTPS', [ $this, &$https ] );
3166 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
3173 * Get the user preferred stub threshold
3177 public function getStubThreshold() {
3178 global $wgMaxArticleSize; # Maximum article size, in Kb
3179 $threshold = $this->getIntOption( 'stubthreshold' );
3180 if ( $threshold > $wgMaxArticleSize * 1024 ) {
3181 // If they have set an impossible value, disable the preference
3182 // so we can use the parser cache again.
3189 * Get the permissions this user has.
3190 * @return array Array of String permission names
3192 public function getRights() {
3193 if ( is_null( $this->mRights
) ) {
3194 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
3195 Hooks
::run( 'UserGetRights', [ $this, &$this->mRights
] );
3197 // Deny any rights denied by the user's session, unless this
3198 // endpoint has no sessions.
3199 if ( !defined( 'MW_NO_SESSION' ) ) {
3200 $allowedRights = $this->getRequest()->getSession()->getAllowedUserRights();
3201 if ( $allowedRights !== null ) {
3202 $this->mRights
= array_intersect( $this->mRights
, $allowedRights );
3206 // Force reindexation of rights when a hook has unset one of them
3207 $this->mRights
= array_values( array_unique( $this->mRights
) );
3209 // If block disables login, we should also remove any
3210 // extra rights blocked users might have, in case the
3211 // blocked user has a pre-existing session (T129738).
3212 // This is checked here for cases where people only call
3213 // $user->isAllowed(). It is also checked in Title::checkUserBlock()
3214 // to give a better error message in the common case.
3215 $config = RequestContext
::getMain()->getConfig();
3217 $this->isLoggedIn() &&
3218 $config->get( 'BlockDisablesLogin' ) &&
3222 $this->mRights
= array_intersect( $this->mRights
, $anon->getRights() );
3225 return $this->mRights
;
3229 * Get the list of explicit group memberships this user has.
3230 * The implicit * and user groups are not included.
3231 * @return array Array of String internal group names
3233 public function getGroups() {
3235 $this->loadGroups();
3236 return $this->mGroups
;
3240 * Get the list of implicit group memberships this user has.
3241 * This includes all explicit groups, plus 'user' if logged in,
3242 * '*' for all accounts, and autopromoted groups
3243 * @param bool $recache Whether to avoid the cache
3244 * @return array Array of String internal group names
3246 public function getEffectiveGroups( $recache = false ) {
3247 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
3248 $this->mEffectiveGroups
= array_unique( array_merge(
3249 $this->getGroups(), // explicit groups
3250 $this->getAutomaticGroups( $recache ) // implicit groups
3252 // Avoid PHP 7.1 warning of passing $this by reference
3254 // Hook for additional groups
3255 Hooks
::run( 'UserEffectiveGroups', [ &$user, &$this->mEffectiveGroups
] );
3256 // Force reindexation of groups when a hook has unset one of them
3257 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
3259 return $this->mEffectiveGroups
;
3263 * Get the list of implicit group memberships this user has.
3264 * This includes 'user' if logged in, '*' for all accounts,
3265 * and autopromoted groups
3266 * @param bool $recache Whether to avoid the cache
3267 * @return array Array of String internal group names
3269 public function getAutomaticGroups( $recache = false ) {
3270 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
3271 $this->mImplicitGroups
= [ '*' ];
3272 if ( $this->getId() ) {
3273 $this->mImplicitGroups
[] = 'user';
3275 $this->mImplicitGroups
= array_unique( array_merge(
3276 $this->mImplicitGroups
,
3277 Autopromote
::getAutopromoteGroups( $this )
3281 // Assure data consistency with rights/groups,
3282 // as getEffectiveGroups() depends on this function
3283 $this->mEffectiveGroups
= null;
3286 return $this->mImplicitGroups
;
3290 * Returns the groups the user has belonged to.
3292 * The user may still belong to the returned groups. Compare with getGroups().
3294 * The function will not return groups the user had belonged to before MW 1.17
3296 * @return array Names of the groups the user has belonged to.
3298 public function getFormerGroups() {
3301 if ( is_null( $this->mFormerGroups
) ) {
3302 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3303 ?
wfGetDB( DB_MASTER
)
3304 : wfGetDB( DB_REPLICA
);
3305 $res = $db->select( 'user_former_groups',
3307 [ 'ufg_user' => $this->mId
],
3309 $this->mFormerGroups
= [];
3310 foreach ( $res as $row ) {
3311 $this->mFormerGroups
[] = $row->ufg_group
;
3315 return $this->mFormerGroups
;
3319 * Get the user's edit count.
3320 * @return int|null Null for anonymous users
3322 public function getEditCount() {
3323 if ( !$this->getId() ) {
3327 if ( $this->mEditCount
=== null ) {
3328 /* Populate the count, if it has not been populated yet */
3329 $dbr = wfGetDB( DB_REPLICA
);
3330 // check if the user_editcount field has been initialized
3331 $count = $dbr->selectField(
3332 'user', 'user_editcount',
3333 [ 'user_id' => $this->mId
],
3337 if ( $count === null ) {
3338 // it has not been initialized. do so.
3339 $count = $this->initEditCount();
3341 $this->mEditCount
= $count;
3343 return (int)$this->mEditCount
;
3347 * Add the user to the given group.
3348 * This takes immediate effect.
3349 * @param string $group Name of the group to add
3352 public function addGroup( $group ) {
3355 if ( !Hooks
::run( 'UserAddGroup', [ $this, &$group ] ) ) {
3359 $dbw = wfGetDB( DB_MASTER
);
3360 if ( $this->getId() ) {
3361 $dbw->insert( 'user_groups',
3363 'ug_user' => $this->getId(),
3364 'ug_group' => $group,
3370 $this->loadGroups();
3371 $this->mGroups
[] = $group;
3372 // In case loadGroups was not called before, we now have the right twice.
3373 // Get rid of the duplicate.
3374 $this->mGroups
= array_unique( $this->mGroups
);
3376 // Refresh the groups caches, and clear the rights cache so it will be
3377 // refreshed on the next call to $this->getRights().
3378 $this->getEffectiveGroups( true );
3379 $this->mRights
= null;
3381 $this->invalidateCache();
3387 * Remove the user from the given group.
3388 * This takes immediate effect.
3389 * @param string $group Name of the group to remove
3392 public function removeGroup( $group ) {
3394 if ( !Hooks
::run( 'UserRemoveGroup', [ $this, &$group ] ) ) {
3398 $dbw = wfGetDB( DB_MASTER
);
3399 $dbw->delete( 'user_groups',
3401 'ug_user' => $this->getId(),
3402 'ug_group' => $group,
3405 // Remember that the user was in this group
3406 $dbw->insert( 'user_former_groups',
3408 'ufg_user' => $this->getId(),
3409 'ufg_group' => $group,
3415 $this->loadGroups();
3416 $this->mGroups
= array_diff( $this->mGroups
, [ $group ] );
3418 // Refresh the groups caches, and clear the rights cache so it will be
3419 // refreshed on the next call to $this->getRights().
3420 $this->getEffectiveGroups( true );
3421 $this->mRights
= null;
3423 $this->invalidateCache();
3429 * Get whether the user is logged in
3432 public function isLoggedIn() {
3433 return $this->getId() != 0;
3437 * Get whether the user is anonymous
3440 public function isAnon() {
3441 return !$this->isLoggedIn();
3445 * @return bool Whether this user is flagged as being a bot role account
3448 public function isBot() {
3449 if ( in_array( 'bot', $this->getGroups() ) && $this->isAllowed( 'bot' ) ) {
3454 Hooks
::run( "UserIsBot", [ $this, &$isBot ] );
3460 * Check if user is allowed to access a feature / make an action
3462 * @param string ... Permissions to test
3463 * @return bool True if user is allowed to perform *any* of the given actions
3465 public function isAllowedAny() {
3466 $permissions = func_get_args();
3467 foreach ( $permissions as $permission ) {
3468 if ( $this->isAllowed( $permission ) ) {
3477 * @param string ... Permissions to test
3478 * @return bool True if the user is allowed to perform *all* of the given actions
3480 public function isAllowedAll() {
3481 $permissions = func_get_args();
3482 foreach ( $permissions as $permission ) {
3483 if ( !$this->isAllowed( $permission ) ) {
3491 * Internal mechanics of testing a permission
3492 * @param string $action
3495 public function isAllowed( $action = '' ) {
3496 if ( $action === '' ) {
3497 return true; // In the spirit of DWIM
3499 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3500 // by misconfiguration: 0 == 'foo'
3501 return in_array( $action, $this->getRights(), true );
3505 * Check whether to enable recent changes patrol features for this user
3506 * @return bool True or false
3508 public function useRCPatrol() {
3509 global $wgUseRCPatrol;
3510 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3514 * Check whether to enable new pages patrol features for this user
3515 * @return bool True or false
3517 public function useNPPatrol() {
3518 global $wgUseRCPatrol, $wgUseNPPatrol;
3520 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3521 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3526 * Check whether to enable new files patrol features for this user
3527 * @return bool True or false
3529 public function useFilePatrol() {
3530 global $wgUseRCPatrol, $wgUseFilePatrol;
3532 ( $wgUseRCPatrol ||
$wgUseFilePatrol )
3533 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3538 * Get the WebRequest object to use with this object
3540 * @return WebRequest
3542 public function getRequest() {
3543 if ( $this->mRequest
) {
3544 return $this->mRequest
;
3552 * Check the watched status of an article.
3553 * @since 1.22 $checkRights parameter added
3554 * @param Title $title Title of the article to look at
3555 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3556 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3559 public function isWatched( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3560 if ( $title->isWatchable() && ( !$checkRights ||
$this->isAllowed( 'viewmywatchlist' ) ) ) {
3561 return MediaWikiServices
::getInstance()->getWatchedItemStore()->isWatched( $this, $title );
3568 * @since 1.22 $checkRights parameter added
3569 * @param Title $title Title of the article to look at
3570 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3571 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3573 public function addWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3574 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3575 MediaWikiServices
::getInstance()->getWatchedItemStore()->addWatchBatchForUser(
3577 [ $title->getSubjectPage(), $title->getTalkPage() ]
3580 $this->invalidateCache();
3584 * Stop watching an article.
3585 * @since 1.22 $checkRights parameter added
3586 * @param Title $title Title of the article to look at
3587 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3588 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3590 public function removeWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3591 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3592 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
3593 $store->removeWatch( $this, $title->getSubjectPage() );
3594 $store->removeWatch( $this, $title->getTalkPage() );
3596 $this->invalidateCache();
3600 * Clear the user's notification timestamp for the given title.
3601 * If e-notif e-mails are on, they will receive notification mails on
3602 * the next change of the page if it's watched etc.
3603 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3604 * @param Title $title Title of the article to look at
3605 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3607 public function clearNotification( &$title, $oldid = 0 ) {
3608 global $wgUseEnotif, $wgShowUpdatedMarker;
3610 // Do nothing if the database is locked to writes
3611 if ( wfReadOnly() ) {
3615 // Do nothing if not allowed to edit the watchlist
3616 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3620 // If we're working on user's talk page, we should update the talk page message indicator
3621 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3622 // Avoid PHP 7.1 warning of passing $this by reference
3624 if ( !Hooks
::run( 'UserClearNewTalkNotification', [ &$user, $oldid ] ) ) {
3628 // Try to update the DB post-send and only if needed...
3629 DeferredUpdates
::addCallableUpdate( function() use ( $title, $oldid ) {
3630 if ( !$this->getNewtalk() ) {
3631 return; // no notifications to clear
3634 // Delete the last notifications (they stack up)
3635 $this->setNewtalk( false );
3637 // If there is a new, unseen, revision, use its timestamp
3639 ?
$title->getNextRevisionID( $oldid, Title
::GAID_FOR_UPDATE
)
3642 $this->setNewtalk( true, Revision
::newFromId( $nextid ) );
3647 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3651 if ( $this->isAnon() ) {
3652 // Nothing else to do...
3656 // Only update the timestamp if the page is being watched.
3657 // The query to find out if it is watched is cached both in memcached and per-invocation,
3658 // and when it does have to be executed, it can be on a replica DB
3659 // If this is the user's newtalk page, we always update the timestamp
3661 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3665 MediaWikiServices
::getInstance()->getWatchedItemStore()
3666 ->resetNotificationTimestamp( $this, $title, $force, $oldid );
3670 * Resets all of the given user's page-change notification timestamps.
3671 * If e-notif e-mails are on, they will receive notification mails on
3672 * the next change of any watched page.
3673 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3675 public function clearAllNotifications() {
3676 global $wgUseEnotif, $wgShowUpdatedMarker;
3677 // Do nothing if not allowed to edit the watchlist
3678 if ( wfReadOnly() ||
!$this->isAllowed( 'editmywatchlist' ) ) {
3682 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3683 $this->setNewtalk( false );
3687 $id = $this->getId();
3692 $dbw = wfGetDB( DB_MASTER
);
3693 $asOfTimes = array_unique( $dbw->selectFieldValues(
3695 'wl_notificationtimestamp',
3696 [ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ],
3698 [ 'ORDER BY' => 'wl_notificationtimestamp DESC', 'LIMIT' => 500 ]
3700 if ( !$asOfTimes ) {
3703 // Immediately update the most recent touched rows, which hopefully covers what
3704 // the user sees on the watchlist page before pressing "mark all pages visited"....
3707 [ 'wl_notificationtimestamp' => null ],
3708 [ 'wl_user' => $id, 'wl_notificationtimestamp' => $asOfTimes ],
3711 // ...and finish the older ones in a post-send update with lag checks...
3712 DeferredUpdates
::addUpdate( new AutoCommitUpdate(
3715 function () use ( $dbw, $id ) {
3716 global $wgUpdateRowsPerQuery;
3718 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
3719 $ticket = $lbFactory->getEmptyTransactionTicket( __METHOD__
);
3720 $asOfTimes = array_unique( $dbw->selectFieldValues(
3722 'wl_notificationtimestamp',
3723 [ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ],
3726 foreach ( array_chunk( $asOfTimes, $wgUpdateRowsPerQuery ) as $asOfTimeBatch ) {
3729 [ 'wl_notificationtimestamp' => null ],
3730 [ 'wl_user' => $id, 'wl_notificationtimestamp' => $asOfTimeBatch ],
3733 $lbFactory->commitAndWaitForReplication( __METHOD__
, $ticket );
3737 // We also need to clear here the "you have new message" notification for the own
3738 // user_talk page; it's cleared one page view later in WikiPage::doViewUpdates().
3742 * Set a cookie on the user's client. Wrapper for
3743 * WebResponse::setCookie
3744 * @deprecated since 1.27
3745 * @param string $name Name of the cookie to set
3746 * @param string $value Value to set
3747 * @param int $exp Expiration time, as a UNIX time value;
3748 * if 0 or not specified, use the default $wgCookieExpiration
3749 * @param bool $secure
3750 * true: Force setting the secure attribute when setting the cookie
3751 * false: Force NOT setting the secure attribute when setting the cookie
3752 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3753 * @param array $params Array of options sent passed to WebResponse::setcookie()
3754 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3757 protected function setCookie(
3758 $name, $value, $exp = 0, $secure = null, $params = [], $request = null
3760 wfDeprecated( __METHOD__
, '1.27' );
3761 if ( $request === null ) {
3762 $request = $this->getRequest();
3764 $params['secure'] = $secure;
3765 $request->response()->setCookie( $name, $value, $exp, $params );
3769 * Clear a cookie on the user's client
3770 * @deprecated since 1.27
3771 * @param string $name Name of the cookie to clear
3772 * @param bool $secure
3773 * true: Force setting the secure attribute when setting the cookie
3774 * false: Force NOT setting the secure attribute when setting the cookie
3775 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3776 * @param array $params Array of options sent passed to WebResponse::setcookie()
3778 protected function clearCookie( $name, $secure = null, $params = [] ) {
3779 wfDeprecated( __METHOD__
, '1.27' );
3780 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3784 * Set an extended login cookie on the user's client. The expiry of the cookie
3785 * is controlled by the $wgExtendedLoginCookieExpiration configuration
3788 * @see User::setCookie
3790 * @deprecated since 1.27
3791 * @param string $name Name of the cookie to set
3792 * @param string $value Value to set
3793 * @param bool $secure
3794 * true: Force setting the secure attribute when setting the cookie
3795 * false: Force NOT setting the secure attribute when setting the cookie
3796 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3798 protected function setExtendedLoginCookie( $name, $value, $secure ) {
3799 global $wgExtendedLoginCookieExpiration, $wgCookieExpiration;
3801 wfDeprecated( __METHOD__
, '1.27' );
3804 $exp +
= $wgExtendedLoginCookieExpiration !== null
3805 ?
$wgExtendedLoginCookieExpiration
3806 : $wgCookieExpiration;
3808 $this->setCookie( $name, $value, $exp, $secure );
3812 * Persist this user's session (e.g. set cookies)
3814 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3816 * @param bool $secure Whether to force secure/insecure cookies or use default
3817 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3819 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3821 if ( 0 == $this->mId
) {
3825 $session = $this->getRequest()->getSession();
3826 if ( $request && $session->getRequest() !== $request ) {
3827 $session = $session->sessionWithRequest( $request );
3829 $delay = $session->delaySave();
3831 if ( !$session->getUser()->equals( $this ) ) {
3832 if ( !$session->canSetUser() ) {
3833 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3834 ->warning( __METHOD__
.
3835 ": Cannot save user \"$this\" to a user \"{$session->getUser()}\"'s immutable session"
3839 $session->setUser( $this );
3842 $session->setRememberUser( $rememberMe );
3843 if ( $secure !== null ) {
3844 $session->setForceHTTPS( $secure );
3847 $session->persist();
3849 ScopedCallback
::consume( $delay );
3853 * Log this user out.
3855 public function logout() {
3856 // Avoid PHP 7.1 warning of passing $this by reference
3858 if ( Hooks
::run( 'UserLogout', [ &$user ] ) ) {
3864 * Clear the user's session, and reset the instance cache.
3867 public function doLogout() {
3868 $session = $this->getRequest()->getSession();
3869 if ( !$session->canSetUser() ) {
3870 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3871 ->warning( __METHOD__
. ": Cannot log out of an immutable session" );
3872 $error = 'immutable';
3873 } elseif ( !$session->getUser()->equals( $this ) ) {
3874 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3875 ->warning( __METHOD__
.
3876 ": Cannot log user \"$this\" out of a user \"{$session->getUser()}\"'s session"
3878 // But we still may as well make this user object anon
3879 $this->clearInstanceCache( 'defaults' );
3880 $error = 'wronguser';
3882 $this->clearInstanceCache( 'defaults' );
3883 $delay = $session->delaySave();
3884 $session->unpersist(); // Clear cookies (T127436)
3885 $session->setLoggedOutTimestamp( time() );
3886 $session->setUser( new User
);
3887 $session->set( 'wsUserID', 0 ); // Other code expects this
3888 $session->resetAllTokens();
3889 ScopedCallback
::consume( $delay );
3892 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authevents' )->info( 'Logout', [
3893 'event' => 'logout',
3894 'successful' => $error === false,
3895 'status' => $error ?
: 'success',
3900 * Save this user's settings into the database.
3901 * @todo Only rarely do all these fields need to be set!
3903 public function saveSettings() {
3904 if ( wfReadOnly() ) {
3905 // @TODO: caller should deal with this instead!
3906 // This should really just be an exception.
3907 MWExceptionHandler
::logException( new DBExpectedError(
3909 "Could not update user with ID '{$this->mId}'; DB is read-only."
3915 if ( 0 == $this->mId
) {
3919 // Get a new user_touched that is higher than the old one.
3920 // This will be used for a CAS check as a last-resort safety
3921 // check against race conditions and replica DB lag.
3922 $newTouched = $this->newTouchedTimestamp();
3924 $dbw = wfGetDB( DB_MASTER
);
3925 $dbw->update( 'user',
3927 'user_name' => $this->mName
,
3928 'user_real_name' => $this->mRealName
,
3929 'user_email' => $this->mEmail
,
3930 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3931 'user_touched' => $dbw->timestamp( $newTouched ),
3932 'user_token' => strval( $this->mToken
),
3933 'user_email_token' => $this->mEmailToken
,
3934 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
3935 ], $this->makeUpdateConditions( $dbw, [ /* WHERE */
3936 'user_id' => $this->mId
,
3940 if ( !$dbw->affectedRows() ) {
3941 // Maybe the problem was a missed cache update; clear it to be safe
3942 $this->clearSharedCache( 'refresh' );
3943 // User was changed in the meantime or loaded with stale data
3944 $from = ( $this->queryFlagsUsed
& self
::READ_LATEST
) ?
'master' : 'replica';
3945 throw new MWException(
3946 "CAS update failed on user_touched for user ID '{$this->mId}' (read from $from);" .
3947 " the version of the user to be saved is older than the current version."
3951 $this->mTouched
= $newTouched;
3952 $this->saveOptions();
3954 Hooks
::run( 'UserSaveSettings', [ $this ] );
3955 $this->clearSharedCache();
3956 $this->getUserPage()->invalidateCache();
3960 * If only this user's username is known, and it exists, return the user ID.
3962 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
3965 public function idForName( $flags = 0 ) {
3966 $s = trim( $this->getName() );
3971 $db = ( ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
)
3972 ?
wfGetDB( DB_MASTER
)
3973 : wfGetDB( DB_REPLICA
);
3975 $options = ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
)
3976 ?
[ 'LOCK IN SHARE MODE' ]
3979 $id = $db->selectField( 'user',
3980 'user_id', [ 'user_name' => $s ], __METHOD__
, $options );
3986 * Add a user to the database, return the user object
3988 * @param string $name Username to add
3989 * @param array $params Array of Strings Non-default parameters to save to
3990 * the database as user_* fields:
3991 * - email: The user's email address.
3992 * - email_authenticated: The email authentication timestamp.
3993 * - real_name: The user's real name.
3994 * - options: An associative array of non-default options.
3995 * - token: Random authentication token. Do not set.
3996 * - registration: Registration timestamp. Do not set.
3998 * @return User|null User object, or null if the username already exists.
4000 public static function createNew( $name, $params = [] ) {
4001 foreach ( [ 'password', 'newpassword', 'newpass_time', 'password_expires' ] as $field ) {
4002 if ( isset( $params[$field] ) ) {
4003 wfDeprecated( __METHOD__
. " with param '$field'", '1.27' );
4004 unset( $params[$field] );
4010 $user->setToken(); // init token
4011 if ( isset( $params['options'] ) ) {
4012 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
4013 unset( $params['options'] );
4015 $dbw = wfGetDB( DB_MASTER
);
4016 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
4018 $noPass = PasswordFactory
::newInvalidPassword()->toString();
4021 'user_id' => $seqVal,
4022 'user_name' => $name,
4023 'user_password' => $noPass,
4024 'user_newpassword' => $noPass,
4025 'user_email' => $user->mEmail
,
4026 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
4027 'user_real_name' => $user->mRealName
,
4028 'user_token' => strval( $user->mToken
),
4029 'user_registration' => $dbw->timestamp( $user->mRegistration
),
4030 'user_editcount' => 0,
4031 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
4033 foreach ( $params as $name => $value ) {
4034 $fields["user_$name"] = $value;
4036 $dbw->insert( 'user', $fields, __METHOD__
, [ 'IGNORE' ] );
4037 if ( $dbw->affectedRows() ) {
4038 $newUser = User
::newFromId( $dbw->insertId() );
4046 * Add this existing user object to the database. If the user already
4047 * exists, a fatal status object is returned, and the user object is
4048 * initialised with the data from the database.
4050 * Previously, this function generated a DB error due to a key conflict
4051 * if the user already existed. Many extension callers use this function
4052 * in code along the lines of:
4054 * $user = User::newFromName( $name );
4055 * if ( !$user->isLoggedIn() ) {
4056 * $user->addToDatabase();
4058 * // do something with $user...
4060 * However, this was vulnerable to a race condition (bug 16020). By
4061 * initialising the user object if the user exists, we aim to support this
4062 * calling sequence as far as possible.
4064 * Note that if the user exists, this function will acquire a write lock,
4065 * so it is still advisable to make the call conditional on isLoggedIn(),
4066 * and to commit the transaction after calling.
4068 * @throws MWException
4071 public function addToDatabase() {
4073 if ( !$this->mToken
) {
4074 $this->setToken(); // init token
4077 $this->mTouched
= $this->newTouchedTimestamp();
4079 $noPass = PasswordFactory
::newInvalidPassword()->toString();
4081 $dbw = wfGetDB( DB_MASTER
);
4082 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
4083 $dbw->insert( 'user',
4085 'user_id' => $seqVal,
4086 'user_name' => $this->mName
,
4087 'user_password' => $noPass,
4088 'user_newpassword' => $noPass,
4089 'user_email' => $this->mEmail
,
4090 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
4091 'user_real_name' => $this->mRealName
,
4092 'user_token' => strval( $this->mToken
),
4093 'user_registration' => $dbw->timestamp( $this->mRegistration
),
4094 'user_editcount' => 0,
4095 'user_touched' => $dbw->timestamp( $this->mTouched
),
4099 if ( !$dbw->affectedRows() ) {
4100 // Use locking reads to bypass any REPEATABLE-READ snapshot.
4101 $this->mId
= $dbw->selectField(
4104 [ 'user_name' => $this->mName
],
4106 [ 'LOCK IN SHARE MODE' ]
4110 if ( $this->loadFromDatabase( self
::READ_LOCKING
) ) {
4115 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
4116 "to insert user '{$this->mName}' row, but it was not present in select!" );
4118 return Status
::newFatal( 'userexists' );
4120 $this->mId
= $dbw->insertId();
4121 self
::$idCacheByName[$this->mName
] = $this->mId
;
4123 // Clear instance cache other than user table data, which is already accurate
4124 $this->clearInstanceCache();
4126 $this->saveOptions();
4127 return Status
::newGood();
4131 * If this user is logged-in and blocked,
4132 * block any IP address they've successfully logged in from.
4133 * @return bool A block was spread
4135 public function spreadAnyEditBlock() {
4136 if ( $this->isLoggedIn() && $this->isBlocked() ) {
4137 return $this->spreadBlock();
4144 * If this (non-anonymous) user is blocked,
4145 * block the IP address they've successfully logged in from.
4146 * @return bool A block was spread
4148 protected function spreadBlock() {
4149 wfDebug( __METHOD__
. "()\n" );
4151 if ( $this->mId
== 0 ) {
4155 $userblock = Block
::newFromTarget( $this->getName() );
4156 if ( !$userblock ) {
4160 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
4164 * Get whether the user is explicitly blocked from account creation.
4165 * @return bool|Block
4167 public function isBlockedFromCreateAccount() {
4168 $this->getBlockedStatus();
4169 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
4170 return $this->mBlock
;
4173 # bug 13611: if the IP address the user is trying to create an account from is
4174 # blocked with createaccount disabled, prevent new account creation there even
4175 # when the user is logged in
4176 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
4177 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
4179 return $this->mBlockedFromCreateAccount
instanceof Block
4180 && $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
4181 ?
$this->mBlockedFromCreateAccount
4186 * Get whether the user is blocked from using Special:Emailuser.
4189 public function isBlockedFromEmailuser() {
4190 $this->getBlockedStatus();
4191 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
4195 * Get whether the user is allowed to create an account.
4198 public function isAllowedToCreateAccount() {
4199 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
4203 * Get this user's personal page title.
4205 * @return Title User's personal page title
4207 public function getUserPage() {
4208 return Title
::makeTitle( NS_USER
, $this->getName() );
4212 * Get this user's talk page title.
4214 * @return Title User's talk page title
4216 public function getTalkPage() {
4217 $title = $this->getUserPage();
4218 return $title->getTalkPage();
4222 * Determine whether the user is a newbie. Newbies are either
4223 * anonymous IPs, or the most recently created accounts.
4226 public function isNewbie() {
4227 return !$this->isAllowed( 'autoconfirmed' );
4231 * Check to see if the given clear-text password is one of the accepted passwords
4232 * @deprecated since 1.27, use AuthManager instead
4233 * @param string $password User password
4234 * @return bool True if the given password is correct, otherwise False
4236 public function checkPassword( $password ) {
4237 $manager = AuthManager
::singleton();
4238 $reqs = AuthenticationRequest
::loadRequestsFromSubmission(
4239 $manager->getAuthenticationRequests( AuthManager
::ACTION_LOGIN
),
4241 'username' => $this->getName(),
4242 'password' => $password,
4245 $res = AuthManager
::singleton()->beginAuthentication( $reqs, 'null:' );
4246 switch ( $res->status
) {
4247 case AuthenticationResponse
::PASS
:
4249 case AuthenticationResponse
::FAIL
:
4250 // Hope it's not a PreAuthenticationProvider that failed...
4251 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
4252 ->info( __METHOD__
. ': Authentication failed: ' . $res->message
->plain() );
4255 throw new BadMethodCallException(
4256 'AuthManager returned a response unsupported by ' . __METHOD__
4262 * Check if the given clear-text password matches the temporary password
4263 * sent by e-mail for password reset operations.
4265 * @deprecated since 1.27, use AuthManager instead
4266 * @param string $plaintext
4267 * @return bool True if matches, false otherwise
4269 public function checkTemporaryPassword( $plaintext ) {
4270 // Can't check the temporary password individually.
4271 return $this->checkPassword( $plaintext );
4275 * Initialize (if necessary) and return a session token value
4276 * which can be used in edit forms to show that the user's
4277 * login credentials aren't being hijacked with a foreign form
4281 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4282 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4283 * @return MediaWiki\Session\Token The new edit token
4285 public function getEditTokenObject( $salt = '', $request = null ) {
4286 if ( $this->isAnon() ) {
4287 return new LoggedOutEditToken();
4291 $request = $this->getRequest();
4293 return $request->getSession()->getToken( $salt );
4297 * Initialize (if necessary) and return a session token value
4298 * which can be used in edit forms to show that the user's
4299 * login credentials aren't being hijacked with a foreign form
4302 * The $salt for 'edit' and 'csrf' tokens is the default (empty string).
4305 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4306 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4307 * @return string The new edit token
4309 public function getEditToken( $salt = '', $request = null ) {
4310 return $this->getEditTokenObject( $salt, $request )->toString();
4314 * Get the embedded timestamp from a token.
4315 * @deprecated since 1.27, use \MediaWiki\Session\Token::getTimestamp instead.
4316 * @param string $val Input token
4319 public static function getEditTokenTimestamp( $val ) {
4320 wfDeprecated( __METHOD__
, '1.27' );
4321 return MediaWiki\Session\Token
::getTimestamp( $val );
4325 * Check given value against the token value stored in the session.
4326 * A match should confirm that the form was submitted from the
4327 * user's own login session, not a form submission from a third-party
4330 * @param string $val Input value to compare
4331 * @param string $salt Optional function-specific data for hashing
4332 * @param WebRequest|null $request Object to use or null to use $wgRequest
4333 * @param int $maxage Fail tokens older than this, in seconds
4334 * @return bool Whether the token matches
4336 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4337 return $this->getEditTokenObject( $salt, $request )->match( $val, $maxage );
4341 * Check given value against the token value stored in the session,
4342 * ignoring the suffix.
4344 * @param string $val Input value to compare
4345 * @param string $salt Optional function-specific data for hashing
4346 * @param WebRequest|null $request Object to use or null to use $wgRequest
4347 * @param int $maxage Fail tokens older than this, in seconds
4348 * @return bool Whether the token matches
4350 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4351 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . Token
::SUFFIX
;
4352 return $this->matchEditToken( $val, $salt, $request, $maxage );
4356 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4357 * mail to the user's given address.
4359 * @param string $type Message to send, either "created", "changed" or "set"
4362 public function sendConfirmationMail( $type = 'created' ) {
4364 $expiration = null; // gets passed-by-ref and defined in next line.
4365 $token = $this->confirmationToken( $expiration );
4366 $url = $this->confirmationTokenUrl( $token );
4367 $invalidateURL = $this->invalidationTokenUrl( $token );
4368 $this->saveSettings();
4370 if ( $type == 'created' ||
$type === false ) {
4371 $message = 'confirmemail_body';
4372 } elseif ( $type === true ) {
4373 $message = 'confirmemail_body_changed';
4375 // Messages: confirmemail_body_changed, confirmemail_body_set
4376 $message = 'confirmemail_body_' . $type;
4379 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4380 wfMessage( $message,
4381 $this->getRequest()->getIP(),
4384 $wgLang->userTimeAndDate( $expiration, $this ),
4386 $wgLang->userDate( $expiration, $this ),
4387 $wgLang->userTime( $expiration, $this ) )->text() );
4391 * Send an e-mail to this user's account. Does not check for
4392 * confirmed status or validity.
4394 * @param string $subject Message subject
4395 * @param string $body Message body
4396 * @param User|null $from Optional sending user; if unspecified, default
4397 * $wgPasswordSender will be used.
4398 * @param string $replyto Reply-To address
4401 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4402 global $wgPasswordSender;
4404 if ( $from instanceof User
) {
4405 $sender = MailAddress
::newFromUser( $from );
4407 $sender = new MailAddress( $wgPasswordSender,
4408 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4410 $to = MailAddress
::newFromUser( $this );
4412 return UserMailer
::send( $to, $sender, $subject, $body, [
4413 'replyTo' => $replyto,
4418 * Generate, store, and return a new e-mail confirmation code.
4419 * A hash (unsalted, since it's used as a key) is stored.
4421 * @note Call saveSettings() after calling this function to commit
4422 * this change to the database.
4424 * @param string &$expiration Accepts the expiration time
4425 * @return string New token
4427 protected function confirmationToken( &$expiration ) {
4428 global $wgUserEmailConfirmationTokenExpiry;
4430 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4431 $expiration = wfTimestamp( TS_MW
, $expires );
4433 $token = MWCryptRand
::generateHex( 32 );
4434 $hash = md5( $token );
4435 $this->mEmailToken
= $hash;
4436 $this->mEmailTokenExpires
= $expiration;
4441 * Return a URL the user can use to confirm their email address.
4442 * @param string $token Accepts the email confirmation token
4443 * @return string New token URL
4445 protected function confirmationTokenUrl( $token ) {
4446 return $this->getTokenUrl( 'ConfirmEmail', $token );
4450 * Return a URL the user can use to invalidate their email address.
4451 * @param string $token Accepts the email confirmation token
4452 * @return string New token URL
4454 protected function invalidationTokenUrl( $token ) {
4455 return $this->getTokenUrl( 'InvalidateEmail', $token );
4459 * Internal function to format the e-mail validation/invalidation URLs.
4460 * This uses a quickie hack to use the
4461 * hardcoded English names of the Special: pages, for ASCII safety.
4463 * @note Since these URLs get dropped directly into emails, using the
4464 * short English names avoids insanely long URL-encoded links, which
4465 * also sometimes can get corrupted in some browsers/mailers
4466 * (bug 6957 with Gmail and Internet Explorer).
4468 * @param string $page Special page
4469 * @param string $token Token
4470 * @return string Formatted URL
4472 protected function getTokenUrl( $page, $token ) {
4473 // Hack to bypass localization of 'Special:'
4474 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4475 return $title->getCanonicalURL();
4479 * Mark the e-mail address confirmed.
4481 * @note Call saveSettings() after calling this function to commit the change.
4485 public function confirmEmail() {
4486 // Check if it's already confirmed, so we don't touch the database
4487 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4488 if ( !$this->isEmailConfirmed() ) {
4489 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4490 Hooks
::run( 'ConfirmEmailComplete', [ $this ] );
4496 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4497 * address if it was already confirmed.
4499 * @note Call saveSettings() after calling this function to commit the change.
4500 * @return bool Returns true
4502 public function invalidateEmail() {
4504 $this->mEmailToken
= null;
4505 $this->mEmailTokenExpires
= null;
4506 $this->setEmailAuthenticationTimestamp( null );
4508 Hooks
::run( 'InvalidateEmailComplete', [ $this ] );
4513 * Set the e-mail authentication timestamp.
4514 * @param string $timestamp TS_MW timestamp
4516 public function setEmailAuthenticationTimestamp( $timestamp ) {
4518 $this->mEmailAuthenticated
= $timestamp;
4519 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
4523 * Is this user allowed to send e-mails within limits of current
4524 * site configuration?
4527 public function canSendEmail() {
4528 global $wgEnableEmail, $wgEnableUserEmail;
4529 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4532 $canSend = $this->isEmailConfirmed();
4533 // Avoid PHP 7.1 warning of passing $this by reference
4535 Hooks
::run( 'UserCanSendEmail', [ &$user, &$canSend ] );
4540 * Is this user allowed to receive e-mails within limits of current
4541 * site configuration?
4544 public function canReceiveEmail() {
4545 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4549 * Is this user's e-mail address valid-looking and confirmed within
4550 * limits of the current site configuration?
4552 * @note If $wgEmailAuthentication is on, this may require the user to have
4553 * confirmed their address by returning a code or using a password
4554 * sent to the address from the wiki.
4558 public function isEmailConfirmed() {
4559 global $wgEmailAuthentication;
4561 // Avoid PHP 7.1 warning of passing $this by reference
4564 if ( Hooks
::run( 'EmailConfirmed', [ &$user, &$confirmed ] ) ) {
4565 if ( $this->isAnon() ) {
4568 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4571 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4581 * Check whether there is an outstanding request for e-mail confirmation.
4584 public function isEmailConfirmationPending() {
4585 global $wgEmailAuthentication;
4586 return $wgEmailAuthentication &&
4587 !$this->isEmailConfirmed() &&
4588 $this->mEmailToken
&&
4589 $this->mEmailTokenExpires
> wfTimestamp();
4593 * Get the timestamp of account creation.
4595 * @return string|bool|null Timestamp of account creation, false for
4596 * non-existent/anonymous user accounts, or null if existing account
4597 * but information is not in database.
4599 public function getRegistration() {
4600 if ( $this->isAnon() ) {
4604 return $this->mRegistration
;
4608 * Get the timestamp of the first edit
4610 * @return string|bool Timestamp of first edit, or false for
4611 * non-existent/anonymous user accounts.
4613 public function getFirstEditTimestamp() {
4614 if ( $this->getId() == 0 ) {
4615 return false; // anons
4617 $dbr = wfGetDB( DB_REPLICA
);
4618 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4619 [ 'rev_user' => $this->getId() ],
4621 [ 'ORDER BY' => 'rev_timestamp ASC' ]
4624 return false; // no edits
4626 return wfTimestamp( TS_MW
, $time );
4630 * Get the permissions associated with a given list of groups
4632 * @param array $groups Array of Strings List of internal group names
4633 * @return array Array of Strings List of permission key names for given groups combined
4635 public static function getGroupPermissions( $groups ) {
4636 global $wgGroupPermissions, $wgRevokePermissions;
4638 // grant every granted permission first
4639 foreach ( $groups as $group ) {
4640 if ( isset( $wgGroupPermissions[$group] ) ) {
4641 $rights = array_merge( $rights,
4642 // array_filter removes empty items
4643 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4646 // now revoke the revoked permissions
4647 foreach ( $groups as $group ) {
4648 if ( isset( $wgRevokePermissions[$group] ) ) {
4649 $rights = array_diff( $rights,
4650 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4653 return array_unique( $rights );
4657 * Get all the groups who have a given permission
4659 * @param string $role Role to check
4660 * @return array Array of Strings List of internal group names with the given permission
4662 public static function getGroupsWithPermission( $role ) {
4663 global $wgGroupPermissions;
4664 $allowedGroups = [];
4665 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4666 if ( self
::groupHasPermission( $group, $role ) ) {
4667 $allowedGroups[] = $group;
4670 return $allowedGroups;
4674 * Check, if the given group has the given permission
4676 * If you're wanting to check whether all users have a permission, use
4677 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4681 * @param string $group Group to check
4682 * @param string $role Role to check
4685 public static function groupHasPermission( $group, $role ) {
4686 global $wgGroupPermissions, $wgRevokePermissions;
4687 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4688 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4692 * Check if all users may be assumed to have the given permission
4694 * We generally assume so if the right is granted to '*' and isn't revoked
4695 * on any group. It doesn't attempt to take grants or other extension
4696 * limitations on rights into account in the general case, though, as that
4697 * would require it to always return false and defeat the purpose.
4698 * Specifically, session-based rights restrictions (such as OAuth or bot
4699 * passwords) are applied based on the current session.
4702 * @param string $right Right to check
4705 public static function isEveryoneAllowed( $right ) {
4706 global $wgGroupPermissions, $wgRevokePermissions;
4709 // Use the cached results, except in unit tests which rely on
4710 // being able change the permission mid-request
4711 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4712 return $cache[$right];
4715 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4716 $cache[$right] = false;
4720 // If it's revoked anywhere, then everyone doesn't have it
4721 foreach ( $wgRevokePermissions as $rights ) {
4722 if ( isset( $rights[$right] ) && $rights[$right] ) {
4723 $cache[$right] = false;
4728 // Remove any rights that aren't allowed to the global-session user,
4729 // unless there are no sessions for this endpoint.
4730 if ( !defined( 'MW_NO_SESSION' ) ) {
4731 $allowedRights = SessionManager
::getGlobalSession()->getAllowedUserRights();
4732 if ( $allowedRights !== null && !in_array( $right, $allowedRights, true ) ) {
4733 $cache[$right] = false;
4738 // Allow extensions to say false
4739 if ( !Hooks
::run( 'UserIsEveryoneAllowed', [ $right ] ) ) {
4740 $cache[$right] = false;
4744 $cache[$right] = true;
4749 * Get the localized descriptive name for a group, if it exists
4751 * @param string $group Internal group name
4752 * @return string Localized descriptive group name
4754 public static function getGroupName( $group ) {
4755 $msg = wfMessage( "group-$group" );
4756 return $msg->isBlank() ?
$group : $msg->text();
4760 * Get the localized descriptive name for a member of a group, if it exists
4762 * @param string $group Internal group name
4763 * @param string $username Username for gender (since 1.19)
4764 * @return string Localized name for group member
4766 public static function getGroupMember( $group, $username = '#' ) {
4767 $msg = wfMessage( "group-$group-member", $username );
4768 return $msg->isBlank() ?
$group : $msg->text();
4772 * Return the set of defined explicit groups.
4773 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4774 * are not included, as they are defined automatically, not in the database.
4775 * @return array Array of internal group names
4777 public static function getAllGroups() {
4778 global $wgGroupPermissions, $wgRevokePermissions;
4780 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4781 self
::getImplicitGroups()
4786 * Get a list of all available permissions.
4787 * @return string[] Array of permission names
4789 public static function getAllRights() {
4790 if ( self
::$mAllRights === false ) {
4791 global $wgAvailableRights;
4792 if ( count( $wgAvailableRights ) ) {
4793 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
4795 self
::$mAllRights = self
::$mCoreRights;
4797 Hooks
::run( 'UserGetAllRights', [ &self
::$mAllRights ] );
4799 return self
::$mAllRights;
4803 * Get a list of implicit groups
4804 * @return array Array of Strings Array of internal group names
4806 public static function getImplicitGroups() {
4807 global $wgImplicitGroups;
4809 $groups = $wgImplicitGroups;
4810 # Deprecated, use $wgImplicitGroups instead
4811 Hooks
::run( 'UserGetImplicitGroups', [ &$groups ], '1.25' );
4817 * Get the title of a page describing a particular group
4819 * @param string $group Internal group name
4820 * @return Title|bool Title of the page if it exists, false otherwise
4822 public static function getGroupPage( $group ) {
4823 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4824 if ( $msg->exists() ) {
4825 $title = Title
::newFromText( $msg->text() );
4826 if ( is_object( $title ) ) {
4834 * Create a link to the group in HTML, if available;
4835 * else return the group name.
4837 * @param string $group Internal name of the group
4838 * @param string $text The text of the link
4839 * @return string HTML link to the group
4841 public static function makeGroupLinkHTML( $group, $text = '' ) {
4842 if ( $text == '' ) {
4843 $text = self
::getGroupName( $group );
4845 $title = self
::getGroupPage( $group );
4847 return Linker
::link( $title, htmlspecialchars( $text ) );
4849 return htmlspecialchars( $text );
4854 * Create a link to the group in Wikitext, if available;
4855 * else return the group name.
4857 * @param string $group Internal name of the group
4858 * @param string $text The text of the link
4859 * @return string Wikilink to the group
4861 public static function makeGroupLinkWiki( $group, $text = '' ) {
4862 if ( $text == '' ) {
4863 $text = self
::getGroupName( $group );
4865 $title = self
::getGroupPage( $group );
4867 $page = $title->getFullText();
4868 return "[[$page|$text]]";
4875 * Returns an array of the groups that a particular group can add/remove.
4877 * @param string $group The group to check for whether it can add/remove
4878 * @return array Array( 'add' => array( addablegroups ),
4879 * 'remove' => array( removablegroups ),
4880 * 'add-self' => array( addablegroups to self),
4881 * 'remove-self' => array( removable groups from self) )
4883 public static function changeableByGroup( $group ) {
4884 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4893 if ( empty( $wgAddGroups[$group] ) ) {
4894 // Don't add anything to $groups
4895 } elseif ( $wgAddGroups[$group] === true ) {
4896 // You get everything
4897 $groups['add'] = self
::getAllGroups();
4898 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4899 $groups['add'] = $wgAddGroups[$group];
4902 // Same thing for remove
4903 if ( empty( $wgRemoveGroups[$group] ) ) {
4905 } elseif ( $wgRemoveGroups[$group] === true ) {
4906 $groups['remove'] = self
::getAllGroups();
4907 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4908 $groups['remove'] = $wgRemoveGroups[$group];
4911 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4912 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4913 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4914 if ( is_int( $key ) ) {
4915 $wgGroupsAddToSelf['user'][] = $value;
4920 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
4921 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4922 if ( is_int( $key ) ) {
4923 $wgGroupsRemoveFromSelf['user'][] = $value;
4928 // Now figure out what groups the user can add to him/herself
4929 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4931 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4932 // No idea WHY this would be used, but it's there
4933 $groups['add-self'] = User
::getAllGroups();
4934 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4935 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4938 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4940 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4941 $groups['remove-self'] = User
::getAllGroups();
4942 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4943 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4950 * Returns an array of groups that this user can add and remove
4951 * @return array Array( 'add' => array( addablegroups ),
4952 * 'remove' => array( removablegroups ),
4953 * 'add-self' => array( addablegroups to self),
4954 * 'remove-self' => array( removable groups from self) )
4956 public function changeableGroups() {
4957 if ( $this->isAllowed( 'userrights' ) ) {
4958 // This group gives the right to modify everything (reverse-
4959 // compatibility with old "userrights lets you change
4961 // Using array_merge to make the groups reindexed
4962 $all = array_merge( User
::getAllGroups() );
4971 // Okay, it's not so simple, we will have to go through the arrays
4978 $addergroups = $this->getEffectiveGroups();
4980 foreach ( $addergroups as $addergroup ) {
4981 $groups = array_merge_recursive(
4982 $groups, $this->changeableByGroup( $addergroup )
4984 $groups['add'] = array_unique( $groups['add'] );
4985 $groups['remove'] = array_unique( $groups['remove'] );
4986 $groups['add-self'] = array_unique( $groups['add-self'] );
4987 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4993 * Deferred version of incEditCountImmediate()
4995 public function incEditCount() {
4996 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle(
4998 $this->incEditCountImmediate();
5005 * Increment the user's edit-count field.
5006 * Will have no effect for anonymous users.
5009 public function incEditCountImmediate() {
5010 if ( $this->isAnon() ) {
5014 $dbw = wfGetDB( DB_MASTER
);
5015 // No rows will be "affected" if user_editcount is NULL
5018 [ 'user_editcount=user_editcount+1' ],
5019 [ 'user_id' => $this->getId(), 'user_editcount IS NOT NULL' ],
5022 // Lazy initialization check...
5023 if ( $dbw->affectedRows() == 0 ) {
5024 // Now here's a goddamn hack...
5025 $dbr = wfGetDB( DB_REPLICA
);
5026 if ( $dbr !== $dbw ) {
5027 // If we actually have a replica DB server, the count is
5028 // at least one behind because the current transaction
5029 // has not been committed and replicated.
5030 $this->mEditCount
= $this->initEditCount( 1 );
5032 // But if DB_REPLICA is selecting the master, then the
5033 // count we just read includes the revision that was
5034 // just added in the working transaction.
5035 $this->mEditCount
= $this->initEditCount();
5038 if ( $this->mEditCount
=== null ) {
5039 $this->getEditCount();
5040 $dbr = wfGetDB( DB_REPLICA
);
5041 $this->mEditCount +
= ( $dbr !== $dbw ) ?
1 : 0;
5043 $this->mEditCount++
;
5046 // Edit count in user cache too
5047 $this->invalidateCache();
5051 * Initialize user_editcount from data out of the revision table
5053 * @param int $add Edits to add to the count from the revision table
5054 * @return int Number of edits
5056 protected function initEditCount( $add = 0 ) {
5057 // Pull from a replica DB to be less cruel to servers
5058 // Accuracy isn't the point anyway here
5059 $dbr = wfGetDB( DB_REPLICA
);
5060 $count = (int)$dbr->selectField(
5063 [ 'rev_user' => $this->getId() ],
5066 $count = $count +
$add;
5068 $dbw = wfGetDB( DB_MASTER
);
5071 [ 'user_editcount' => $count ],
5072 [ 'user_id' => $this->getId() ],
5080 * Get the description of a given right
5083 * @param string $right Right to query
5084 * @return string Localized description of the right
5086 public static function getRightDescription( $right ) {
5087 $key = "right-$right";
5088 $msg = wfMessage( $key );
5089 return $msg->isDisabled() ?
$right : $msg->text();
5093 * Get the name of a given grant
5096 * @param string $grant Grant to query
5097 * @return string Localized name of the grant
5099 public static function getGrantName( $grant ) {
5100 $key = "grant-$grant";
5101 $msg = wfMessage( $key );
5102 return $msg->isDisabled() ?
$grant : $msg->text();
5106 * Make a new-style password hash
5108 * @param string $password Plain-text password
5109 * @param bool|string $salt Optional salt, may be random or the user ID.
5110 * If unspecified or false, will generate one automatically
5111 * @return string Password hash
5112 * @deprecated since 1.24, use Password class
5114 public static function crypt( $password, $salt = false ) {
5115 wfDeprecated( __METHOD__
, '1.24' );
5116 $passwordFactory = new PasswordFactory();
5117 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
5118 $hash = $passwordFactory->newFromPlaintext( $password );
5119 return $hash->toString();
5123 * Compare a password hash with a plain-text password. Requires the user
5124 * ID if there's a chance that the hash is an old-style hash.
5126 * @param string $hash Password hash
5127 * @param string $password Plain-text password to compare
5128 * @param string|bool $userId User ID for old-style password salt
5131 * @deprecated since 1.24, use Password class
5133 public static function comparePasswords( $hash, $password, $userId = false ) {
5134 wfDeprecated( __METHOD__
, '1.24' );
5136 // Check for *really* old password hashes that don't even have a type
5137 // The old hash format was just an md5 hex hash, with no type information
5138 if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) {
5139 global $wgPasswordSalt;
5140 if ( $wgPasswordSalt ) {
5141 $password = ":B:{$userId}:{$hash}";
5143 $password = ":A:{$hash}";
5147 $passwordFactory = new PasswordFactory();
5148 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
5149 $hash = $passwordFactory->newFromCiphertext( $hash );
5150 return $hash->equals( $password );
5154 * Add a newuser log entry for this user.
5155 * Before 1.19 the return value was always true.
5157 * @deprecated since 1.27, AuthManager handles logging
5158 * @param string|bool $action Account creation type.
5159 * - String, one of the following values:
5160 * - 'create' for an anonymous user creating an account for himself.
5161 * This will force the action's performer to be the created user itself,
5162 * no matter the value of $wgUser
5163 * - 'create2' for a logged in user creating an account for someone else
5164 * - 'byemail' when the created user will receive its password by e-mail
5165 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
5166 * - Boolean means whether the account was created by e-mail (deprecated):
5167 * - true will be converted to 'byemail'
5168 * - false will be converted to 'create' if this object is the same as
5169 * $wgUser and to 'create2' otherwise
5170 * @param string $reason User supplied reason
5173 public function addNewUserLogEntry( $action = false, $reason = '' ) {
5174 return true; // disabled
5178 * Add an autocreate newuser log entry for this user
5179 * Used by things like CentralAuth and perhaps other authplugins.
5180 * Consider calling addNewUserLogEntry() directly instead.
5182 * @deprecated since 1.27, AuthManager handles logging
5185 public function addNewUserLogEntryAutoCreate() {
5186 $this->addNewUserLogEntry( 'autocreate' );
5192 * Load the user options either from cache, the database or an array
5194 * @param array $data Rows for the current user out of the user_properties table
5196 protected function loadOptions( $data = null ) {
5201 if ( $this->mOptionsLoaded
) {
5205 $this->mOptions
= self
::getDefaultOptions();
5207 if ( !$this->getId() ) {
5208 // For unlogged-in users, load language/variant options from request.
5209 // There's no need to do it for logged-in users: they can set preferences,
5210 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5211 // so don't override user's choice (especially when the user chooses site default).
5212 $variant = $wgContLang->getDefaultVariant();
5213 $this->mOptions
['variant'] = $variant;
5214 $this->mOptions
['language'] = $variant;
5215 $this->mOptionsLoaded
= true;
5219 // Maybe load from the object
5220 if ( !is_null( $this->mOptionOverrides
) ) {
5221 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5222 foreach ( $this->mOptionOverrides
as $key => $value ) {
5223 $this->mOptions
[$key] = $value;
5226 if ( !is_array( $data ) ) {
5227 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5228 // Load from database
5229 $dbr = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
5230 ?
wfGetDB( DB_MASTER
)
5231 : wfGetDB( DB_REPLICA
);
5233 $res = $dbr->select(
5235 [ 'up_property', 'up_value' ],
5236 [ 'up_user' => $this->getId() ],
5240 $this->mOptionOverrides
= [];
5242 foreach ( $res as $row ) {
5243 $data[$row->up_property
] = $row->up_value
;
5246 foreach ( $data as $property => $value ) {
5247 $this->mOptionOverrides
[$property] = $value;
5248 $this->mOptions
[$property] = $value;
5252 $this->mOptionsLoaded
= true;
5254 Hooks
::run( 'UserLoadOptions', [ $this, &$this->mOptions
] );
5258 * Saves the non-default options for this user, as previously set e.g. via
5259 * setOption(), in the database's "user_properties" (preferences) table.
5260 * Usually used via saveSettings().
5262 protected function saveOptions() {
5263 $this->loadOptions();
5265 // Not using getOptions(), to keep hidden preferences in database
5266 $saveOptions = $this->mOptions
;
5268 // Allow hooks to abort, for instance to save to a global profile.
5269 // Reset options to default state before saving.
5270 if ( !Hooks
::run( 'UserSaveOptions', [ $this, &$saveOptions ] ) ) {
5274 $userId = $this->getId();
5276 $insert_rows = []; // all the new preference rows
5277 foreach ( $saveOptions as $key => $value ) {
5278 // Don't bother storing default values
5279 $defaultOption = self
::getDefaultOption( $key );
5280 if ( ( $defaultOption === null && $value !== false && $value !== null )
5281 ||
$value != $defaultOption
5284 'up_user' => $userId,
5285 'up_property' => $key,
5286 'up_value' => $value,
5291 $dbw = wfGetDB( DB_MASTER
);
5293 $res = $dbw->select( 'user_properties',
5294 [ 'up_property', 'up_value' ], [ 'up_user' => $userId ], __METHOD__
);
5296 // Find prior rows that need to be removed or updated. These rows will
5297 // all be deleted (the latter so that INSERT IGNORE applies the new values).
5299 foreach ( $res as $row ) {
5300 if ( !isset( $saveOptions[$row->up_property
] )
5301 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
5303 $keysDelete[] = $row->up_property
;
5307 if ( count( $keysDelete ) ) {
5308 // Do the DELETE by PRIMARY KEY for prior rows.
5309 // In the past a very large portion of calls to this function are for setting
5310 // 'rememberpassword' for new accounts (a preference that has since been removed).
5311 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5312 // caused gap locks on [max user ID,+infinity) which caused high contention since
5313 // updates would pile up on each other as they are for higher (newer) user IDs.
5314 // It might not be necessary these days, but it shouldn't hurt either.
5315 $dbw->delete( 'user_properties',
5316 [ 'up_user' => $userId, 'up_property' => $keysDelete ], __METHOD__
);
5318 // Insert the new preference rows
5319 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, [ 'IGNORE' ] );
5323 * Lazily instantiate and return a factory object for making passwords
5325 * @deprecated since 1.27, create a PasswordFactory directly instead
5326 * @return PasswordFactory
5328 public static function getPasswordFactory() {
5329 wfDeprecated( __METHOD__
, '1.27' );
5330 $ret = new PasswordFactory();
5331 $ret->init( RequestContext
::getMain()->getConfig() );
5336 * Provide an array of HTML5 attributes to put on an input element
5337 * intended for the user to enter a new password. This may include
5338 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
5340 * Do *not* use this when asking the user to enter his current password!
5341 * Regardless of configuration, users may have invalid passwords for whatever
5342 * reason (e.g., they were set before requirements were tightened up).
5343 * Only use it when asking for a new password, like on account creation or
5346 * Obviously, you still need to do server-side checking.
5348 * NOTE: A combination of bugs in various browsers means that this function
5349 * actually just returns array() unconditionally at the moment. May as
5350 * well keep it around for when the browser bugs get fixed, though.
5352 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
5354 * @deprecated since 1.27
5355 * @return array Array of HTML attributes suitable for feeding to
5356 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
5357 * That will get confused by the boolean attribute syntax used.)
5359 public static function passwordChangeInputAttribs() {
5360 global $wgMinimalPasswordLength;
5362 if ( $wgMinimalPasswordLength == 0 ) {
5366 # Note that the pattern requirement will always be satisfied if the
5367 # input is empty, so we need required in all cases.
5369 # @todo FIXME: Bug 23769: This needs to not claim the password is required
5370 # if e-mail confirmation is being used. Since HTML5 input validation
5371 # is b0rked anyway in some browsers, just return nothing. When it's
5372 # re-enabled, fix this code to not output required for e-mail
5374 # $ret = array( 'required' );
5377 # We can't actually do this right now, because Opera 9.6 will print out
5378 # the entered password visibly in its error message! When other
5379 # browsers add support for this attribute, or Opera fixes its support,
5380 # we can add support with a version check to avoid doing this on Opera
5381 # versions where it will be a problem. Reported to Opera as
5382 # DSK-262266, but they don't have a public bug tracker for us to follow.
5384 if ( $wgMinimalPasswordLength > 1 ) {
5385 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
5386 $ret['title'] = wfMessage( 'passwordtooshort' )
5387 ->numParams( $wgMinimalPasswordLength )->text();
5395 * Return the list of user fields that should be selected to create
5396 * a new user object.
5399 public static function selectFields() {
5407 'user_email_authenticated',
5409 'user_email_token_expires',
5410 'user_registration',
5416 * Factory function for fatal permission-denied errors
5419 * @param string $permission User right required
5422 static function newFatalPermissionDeniedStatus( $permission ) {
5425 $groups = array_map(
5426 [ 'User', 'makeGroupLinkWiki' ],
5427 User
::getGroupsWithPermission( $permission )
5431 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5433 return Status
::newFatal( 'badaccess-group0' );
5438 * Get a new instance of this user that was loaded from the master via a locking read
5440 * Use this instead of the main context User when updating that user. This avoids races
5441 * where that user was loaded from a replica DB or even the master but without proper locks.
5443 * @return User|null Returns null if the user was not found in the DB
5446 public function getInstanceForUpdate() {
5447 if ( !$this->getId() ) {
5448 return null; // anon
5451 $user = self
::newFromId( $this->getId() );
5452 if ( !$user->loadFromId( self
::READ_EXCLUSIVE
) ) {
5460 * Checks if two user objects point to the same user.
5466 public function equals( User
$user ) {
5467 return $this->getName() === $user->getName();