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',
190 'userrights-interwiki',
198 * String Cached results of getAllRights()
200 protected static $mAllRights = false;
202 /** Cache variables */
213 /** @var string TS_MW timestamp from the DB */
215 /** @var string TS_MW timestamp from cache */
216 protected $mQuickTouched;
220 public $mEmailAuthenticated;
222 protected $mEmailToken;
224 protected $mEmailTokenExpires;
226 protected $mRegistration;
228 protected $mEditCount;
232 protected $mOptionOverrides;
236 * Bool Whether the cache variables have been loaded.
239 public $mOptionsLoaded;
242 * Array with already loaded items or true if all items have been loaded.
244 protected $mLoadedItems = [];
248 * String Initialization data source if mLoadedItems!==true. May be one of:
249 * - 'defaults' anonymous user initialised from class defaults
250 * - 'name' initialise from mName
251 * - 'id' initialise from mId
252 * - 'session' log in from session if possible
254 * Use the User::newFrom*() family of functions to set this.
259 * Lazy-initialized variables, invalidated with clearInstanceCache
263 protected $mDatePreference;
271 protected $mBlockreason;
273 protected $mEffectiveGroups;
275 protected $mImplicitGroups;
277 protected $mFormerGroups;
279 protected $mGlobalBlock;
296 protected $mAllowUsertalk;
299 private $mBlockedFromCreateAccount = false;
301 /** @var integer User::READ_* constant bitfield used to load data */
302 protected $queryFlagsUsed = self
::READ_NORMAL
;
304 /** @var string Indicates type of block (used for eventlogging)
305 * 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 * Load user data from shared cache, given mId has already been set.
477 protected function loadFromCache() {
478 $cache = ObjectCache
::getMainWANInstance();
479 $data = $cache->getWithSetCallback(
480 $this->getCacheKey( $cache ),
482 function ( $oldValue, &$ttl, array &$setOpts ) use ( $cache ) {
483 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
484 wfDebug( "User: cache miss for user {$this->mId}\n" );
486 $this->loadFromDatabase( self
::READ_NORMAL
);
488 $this->loadOptions();
491 foreach ( self
::$mCacheVars as $name ) {
492 $data[$name] = $this->$name;
495 $ttl = $cache->adaptiveTTL( wfTimestamp( TS_UNIX
, $this->mTouched
), $ttl );
500 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'version' => self
::VERSION
]
503 // Restore from cache
504 foreach ( self
::$mCacheVars as $name ) {
505 $this->$name = $data[$name];
511 /** @name newFrom*() static factory methods */
515 * Static factory method for creation from username.
517 * This is slightly less efficient than newFromId(), so use newFromId() if
518 * you have both an ID and a name handy.
520 * @param string $name Username, validated by Title::newFromText()
521 * @param string|bool $validate Validate username. Takes the same parameters as
522 * User::getCanonicalName(), except that true is accepted as an alias
523 * for 'valid', for BC.
525 * @return User|bool User object, or false if the username is invalid
526 * (e.g. if it contains illegal characters or is an IP address). If the
527 * username is not present in the database, the result will be a user object
528 * with a name, zero user ID and default settings.
530 public static function newFromName( $name, $validate = 'valid' ) {
531 if ( $validate === true ) {
534 $name = self
::getCanonicalName( $name, $validate );
535 if ( $name === false ) {
538 // Create unloaded user object
542 $u->setItemLoaded( 'name' );
548 * Static factory method for creation from a given user ID.
550 * @param int $id Valid user ID
551 * @return User The corresponding User object
553 public static function newFromId( $id ) {
557 $u->setItemLoaded( 'id' );
562 * Factory method to fetch whichever user has a given email confirmation code.
563 * This code is generated when an account is created or its e-mail address
566 * If the code is invalid or has expired, returns NULL.
568 * @param string $code Confirmation code
569 * @param int $flags User::READ_* bitfield
572 public static function newFromConfirmationCode( $code, $flags = 0 ) {
573 $db = ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
574 ?
wfGetDB( DB_MASTER
)
575 : wfGetDB( DB_REPLICA
);
577 $id = $db->selectField(
581 'user_email_token' => md5( $code ),
582 'user_email_token_expires > ' . $db->addQuotes( $db->timestamp() ),
586 return $id ? User
::newFromId( $id ) : null;
590 * Create a new user object using data from session. If the login
591 * credentials are invalid, the result is an anonymous user.
593 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
596 public static function newFromSession( WebRequest
$request = null ) {
598 $user->mFrom
= 'session';
599 $user->mRequest
= $request;
604 * Create a new user object from a user row.
605 * The row should have the following fields from the user table in it:
606 * - either user_name or user_id to load further data if needed (or both)
608 * - all other fields (email, etc.)
609 * It is useless to provide the remaining fields if either user_id,
610 * user_name and user_real_name are not provided because the whole row
611 * will be loaded once more from the database when accessing them.
613 * @param stdClass $row A row from the user table
614 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
617 public static function newFromRow( $row, $data = null ) {
619 $user->loadFromRow( $row, $data );
624 * Static factory method for creation of a "system" user from username.
626 * A "system" user is an account that's used to attribute logged actions
627 * taken by MediaWiki itself, as opposed to a bot or human user. Examples
628 * might include the 'Maintenance script' or 'Conversion script' accounts
629 * used by various scripts in the maintenance/ directory or accounts such
630 * as 'MediaWiki message delivery' used by the MassMessage extension.
632 * This can optionally create the user if it doesn't exist, and "steal" the
633 * account if it does exist.
635 * "Stealing" an existing user is intended to make it impossible for normal
636 * authentication processes to use the account, effectively disabling the
637 * account for normal use:
638 * - Email is invalidated, to prevent account recovery by emailing a
639 * temporary password and to disassociate the account from the existing
641 * - The token is set to a magic invalid value, to kill existing sessions
642 * and to prevent $this->setToken() calls from resetting the token to a
644 * - SessionManager is instructed to prevent new sessions for the user, to
645 * do things like deauthorizing OAuth consumers.
646 * - AuthManager is instructed to revoke access, to invalidate or remove
647 * passwords and other credentials.
649 * @param string $name Username
650 * @param array $options Options are:
651 * - validate: As for User::getCanonicalName(), default 'valid'
652 * - create: Whether to create the user if it doesn't already exist, default true
653 * - steal: Whether to "disable" the account for normal use if it already
654 * exists, default false
658 public static function newSystemUser( $name, $options = [] ) {
660 'validate' => 'valid',
665 $name = self
::getCanonicalName( $name, $options['validate'] );
666 if ( $name === false ) {
670 $fields = self
::selectFields();
672 $dbw = wfGetDB( DB_MASTER
);
673 $row = $dbw->selectRow(
676 [ 'user_name' => $name ],
680 // No user. Create it?
681 return $options['create'] ? self
::createNew( $name ) : null;
683 $user = self
::newFromRow( $row );
685 // A user is considered to exist as a non-system user if it can
686 // authenticate, or has an email set, or has a non-invalid token.
687 if ( $user->mEmail ||
$user->mToken
!== self
::INVALID_TOKEN ||
688 AuthManager
::singleton()->userCanAuthenticate( $name )
690 // User exists. Steal it?
691 if ( !$options['steal'] ) {
695 AuthManager
::singleton()->revokeAccessForUser( $name );
697 $user->invalidateEmail();
698 $user->mToken
= self
::INVALID_TOKEN
;
699 $user->saveSettings();
700 SessionManager
::singleton()->preventSessionsForUser( $user->getName() );
709 * Get the username corresponding to a given user ID
710 * @param int $id User ID
711 * @return string|bool The corresponding username
713 public static function whoIs( $id ) {
714 return UserCache
::singleton()->getProp( $id, 'name' );
718 * Get the real name of a user given their user ID
720 * @param int $id User ID
721 * @return string|bool The corresponding user's real name
723 public static function whoIsReal( $id ) {
724 return UserCache
::singleton()->getProp( $id, 'real_name' );
728 * Get database id given a user name
729 * @param string $name Username
730 * @param integer $flags User::READ_* constant bitfield
731 * @return int|null The corresponding user's ID, or null if user is nonexistent
733 public static function idFromName( $name, $flags = self
::READ_NORMAL
) {
734 $nt = Title
::makeTitleSafe( NS_USER
, $name );
735 if ( is_null( $nt ) ) {
740 if ( !( $flags & self
::READ_LATEST
) && isset( self
::$idCacheByName[$name] ) ) {
741 return self
::$idCacheByName[$name];
744 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
745 $db = wfGetDB( $index );
750 [ 'user_name' => $nt->getText() ],
755 if ( $s === false ) {
758 $result = $s->user_id
;
761 self
::$idCacheByName[$name] = $result;
763 if ( count( self
::$idCacheByName ) > 1000 ) {
764 self
::$idCacheByName = [];
771 * Reset the cache used in idFromName(). For use in tests.
773 public static function resetIdByNameCache() {
774 self
::$idCacheByName = [];
778 * Does the string match an anonymous IP address?
780 * This function exists for username validation, in order to reject
781 * usernames which are similar in form to IP addresses. Strings such
782 * as 300.300.300.300 will return true because it looks like an IP
783 * address, despite not being strictly valid.
785 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
786 * address because the usemod software would "cloak" anonymous IP
787 * addresses like this, if we allowed accounts like this to be created
788 * new users could get the old edits of these anonymous users.
790 * @param string $name Name to match
793 public static function isIP( $name ) {
794 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
795 || IP
::isIPv6( $name );
799 * Is the input a valid username?
801 * Checks if the input is a valid username, we don't want an empty string,
802 * an IP address, anything that contains slashes (would mess up subpages),
803 * is longer than the maximum allowed username size or doesn't begin with
806 * @param string $name Name to match
809 public static function isValidUserName( $name ) {
810 global $wgContLang, $wgMaxNameChars;
813 || User
::isIP( $name )
814 ||
strpos( $name, '/' ) !== false
815 ||
strlen( $name ) > $wgMaxNameChars
816 ||
$name != $wgContLang->ucfirst( $name )
821 // Ensure that the name can't be misresolved as a different title,
822 // such as with extra namespace keys at the start.
823 $parsed = Title
::newFromText( $name );
824 if ( is_null( $parsed )
825 ||
$parsed->getNamespace()
826 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
830 // Check an additional blacklist of troublemaker characters.
831 // Should these be merged into the title char list?
832 $unicodeBlacklist = '/[' .
833 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
834 '\x{00a0}' . # non-breaking space
835 '\x{2000}-\x{200f}' . # various whitespace
836 '\x{2028}-\x{202f}' . # breaks and control chars
837 '\x{3000}' . # ideographic space
838 '\x{e000}-\x{f8ff}' . # private use
840 if ( preg_match( $unicodeBlacklist, $name ) ) {
848 * Usernames which fail to pass this function will be blocked
849 * from user login and new account registrations, but may be used
850 * internally by batch processes.
852 * If an account already exists in this form, login will be blocked
853 * by a failure to pass this function.
855 * @param string $name Name to match
858 public static function isUsableName( $name ) {
859 global $wgReservedUsernames;
860 // Must be a valid username, obviously ;)
861 if ( !self
::isValidUserName( $name ) ) {
865 static $reservedUsernames = false;
866 if ( !$reservedUsernames ) {
867 $reservedUsernames = $wgReservedUsernames;
868 Hooks
::run( 'UserGetReservedNames', [ &$reservedUsernames ] );
871 // Certain names may be reserved for batch processes.
872 foreach ( $reservedUsernames as $reserved ) {
873 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
874 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
876 if ( $reserved == $name ) {
884 * Return the users who are members of the given group(s). In case of multiple groups,
885 * users who are members of at least one of them are returned.
887 * @param string|array $groups A single group name or an array of group names
888 * @param int $limit Max number of users to return. The actual limit will never exceed 5000
889 * records; larger values are ignored.
890 * @param int $after ID the user to start after
891 * @return UserArrayFromResult
893 public static function findUsersByGroup( $groups, $limit = 5000, $after = null ) {
894 if ( $groups === [] ) {
895 return UserArrayFromResult
::newFromIDs( [] );
898 $groups = array_unique( (array)$groups );
899 $limit = min( 5000, $limit );
901 $conds = [ 'ug_group' => $groups ];
902 if ( $after !== null ) {
903 $conds[] = 'ug_user > ' . (int)$after;
906 $dbr = wfGetDB( DB_REPLICA
);
907 $ids = $dbr->selectFieldValues(
914 'ORDER BY' => 'ug_user',
918 return UserArray
::newFromIDs( $ids );
922 * Usernames which fail to pass this function will be blocked
923 * from new account registrations, but may be used internally
924 * either by batch processes or by user accounts which have
925 * already been created.
927 * Additional blacklisting may be added here rather than in
928 * isValidUserName() to avoid disrupting existing accounts.
930 * @param string $name String to match
933 public static function isCreatableName( $name ) {
934 global $wgInvalidUsernameCharacters;
936 // Ensure that the username isn't longer than 235 bytes, so that
937 // (at least for the builtin skins) user javascript and css files
938 // will work. (bug 23080)
939 if ( strlen( $name ) > 235 ) {
940 wfDebugLog( 'username', __METHOD__
.
941 ": '$name' invalid due to length" );
945 // Preg yells if you try to give it an empty string
946 if ( $wgInvalidUsernameCharacters !== '' ) {
947 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
948 wfDebugLog( 'username', __METHOD__
.
949 ": '$name' invalid due to wgInvalidUsernameCharacters" );
954 return self
::isUsableName( $name );
958 * Is the input a valid password for this user?
960 * @param string $password Desired password
963 public function isValidPassword( $password ) {
964 // simple boolean wrapper for getPasswordValidity
965 return $this->getPasswordValidity( $password ) === true;
969 * Given unvalidated password input, return error message on failure.
971 * @param string $password Desired password
972 * @return bool|string|array True on success, string or array of error message on failure
974 public function getPasswordValidity( $password ) {
975 $result = $this->checkPasswordValidity( $password );
976 if ( $result->isGood() ) {
980 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
981 $messages[] = $error['message'];
983 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
984 $messages[] = $warning['message'];
986 if ( count( $messages ) === 1 ) {
994 * Check if this is a valid password for this user
996 * Create a Status object based on the password's validity.
997 * The Status should be set to fatal if the user should not
998 * be allowed to log in, and should have any errors that
999 * would block changing the password.
1001 * If the return value of this is not OK, the password
1002 * should not be checked. If the return value is not Good,
1003 * the password can be checked, but the user should not be
1004 * able to set their password to this.
1006 * @param string $password Desired password
1007 * @param string $purpose one of 'login', 'create', 'reset'
1011 public function checkPasswordValidity( $password, $purpose = 'login' ) {
1012 global $wgPasswordPolicy;
1014 $upp = new UserPasswordPolicy(
1015 $wgPasswordPolicy['policies'],
1016 $wgPasswordPolicy['checks']
1019 $status = Status
::newGood();
1020 $result = false; // init $result to false for the internal checks
1022 if ( !Hooks
::run( 'isValidPassword', [ $password, &$result, $this ] ) ) {
1023 $status->error( $result );
1027 if ( $result === false ) {
1028 $status->merge( $upp->checkUserPassword( $this, $password, $purpose ) );
1030 } elseif ( $result === true ) {
1033 $status->error( $result );
1034 return $status; // the isValidPassword hook set a string $result and returned true
1039 * Given unvalidated user input, return a canonical username, or false if
1040 * the username is invalid.
1041 * @param string $name User input
1042 * @param string|bool $validate Type of validation to use:
1043 * - false No validation
1044 * - 'valid' Valid for batch processes
1045 * - 'usable' Valid for batch processes and login
1046 * - 'creatable' Valid for batch processes, login and account creation
1048 * @throws InvalidArgumentException
1049 * @return bool|string
1051 public static function getCanonicalName( $name, $validate = 'valid' ) {
1052 // Force usernames to capital
1054 $name = $wgContLang->ucfirst( $name );
1056 # Reject names containing '#'; these will be cleaned up
1057 # with title normalisation, but then it's too late to
1059 if ( strpos( $name, '#' ) !== false ) {
1063 // Clean up name according to title rules,
1064 // but only when validation is requested (bug 12654)
1065 $t = ( $validate !== false ) ?
1066 Title
::newFromText( $name, NS_USER
) : Title
::makeTitle( NS_USER
, $name );
1067 // Check for invalid titles
1068 if ( is_null( $t ) ||
$t->getNamespace() !== NS_USER ||
$t->isExternal() ) {
1072 // Reject various classes of invalid names
1073 $name = AuthManager
::callLegacyAuthPlugin(
1074 'getCanonicalName', [ $t->getText() ], $t->getText()
1077 switch ( $validate ) {
1081 if ( !User
::isValidUserName( $name ) ) {
1086 if ( !User
::isUsableName( $name ) ) {
1091 if ( !User
::isCreatableName( $name ) ) {
1096 throw new InvalidArgumentException(
1097 'Invalid parameter value for $validate in ' . __METHOD__
);
1103 * Count the number of edits of a user
1105 * @param int $uid User ID to check
1106 * @return int The user's edit count
1108 * @deprecated since 1.21 in favour of User::getEditCount
1110 public static function edits( $uid ) {
1111 wfDeprecated( __METHOD__
, '1.21' );
1112 $user = self
::newFromId( $uid );
1113 return $user->getEditCount();
1117 * Return a random password.
1119 * @deprecated since 1.27, use PasswordFactory::generateRandomPasswordString()
1120 * @return string New random password
1122 public static function randomPassword() {
1123 global $wgMinimalPasswordLength;
1124 return PasswordFactory
::generateRandomPasswordString( $wgMinimalPasswordLength );
1128 * Set cached properties to default.
1130 * @note This no longer clears uncached lazy-initialised properties;
1131 * the constructor does that instead.
1133 * @param string|bool $name
1135 public function loadDefaults( $name = false ) {
1137 $this->mName
= $name;
1138 $this->mRealName
= '';
1140 $this->mOptionOverrides
= null;
1141 $this->mOptionsLoaded
= false;
1143 $loggedOut = $this->mRequest
&& !defined( 'MW_NO_SESSION' )
1144 ?
$this->mRequest
->getSession()->getLoggedOutTimestamp() : 0;
1145 if ( $loggedOut !== 0 ) {
1146 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1148 $this->mTouched
= '1'; # Allow any pages to be cached
1151 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1152 $this->mEmailAuthenticated
= null;
1153 $this->mEmailToken
= '';
1154 $this->mEmailTokenExpires
= null;
1155 $this->mRegistration
= wfTimestamp( TS_MW
);
1156 $this->mGroups
= [];
1158 Hooks
::run( 'UserLoadDefaults', [ $this, $name ] );
1162 * Return whether an item has been loaded.
1164 * @param string $item Item to check. Current possibilities:
1168 * @param string $all 'all' to check if the whole object has been loaded
1169 * or any other string to check if only the item is available (e.g.
1173 public function isItemLoaded( $item, $all = 'all' ) {
1174 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1175 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1179 * Set that an item has been loaded
1181 * @param string $item
1183 protected function setItemLoaded( $item ) {
1184 if ( is_array( $this->mLoadedItems
) ) {
1185 $this->mLoadedItems
[$item] = true;
1190 * Load user data from the session.
1192 * @return bool True if the user is logged in, false otherwise.
1194 private function loadFromSession() {
1197 Hooks
::run( 'UserLoadFromSession', [ $this, &$result ], '1.27' );
1198 if ( $result !== null ) {
1202 // MediaWiki\Session\Session already did the necessary authentication of the user
1203 // returned here, so just use it if applicable.
1204 $session = $this->getRequest()->getSession();
1205 $user = $session->getUser();
1206 if ( $user->isLoggedIn() ) {
1207 $this->loadFromUserObject( $user );
1209 // If this user is autoblocked, set a cookie to track the Block. This has to be done on
1210 // every session load, because an autoblocked editor might not edit again from the same
1211 // IP address after being blocked.
1212 $config = RequestContext
::getMain()->getConfig();
1213 if ( $config->get( 'CookieSetOnAutoblock' ) === true ) {
1214 $block = $this->getBlock();
1215 $shouldSetCookie = $this->getRequest()->getCookie( 'BlockID' ) === null
1217 && $block->getType() === Block
::TYPE_USER
1218 && $block->isAutoblocking();
1219 if ( $shouldSetCookie ) {
1220 wfDebug( __METHOD__
. ': User is autoblocked, setting cookie to track' );
1221 $block->setCookie( $this->getRequest()->response() );
1225 // Other code expects these to be set in the session, so set them.
1226 $session->set( 'wsUserID', $this->getId() );
1227 $session->set( 'wsUserName', $this->getName() );
1228 $session->set( 'wsToken', $this->getToken() );
1235 * Load user and user_group data from the database.
1236 * $this->mId must be set, this is how the user is identified.
1238 * @param integer $flags User::READ_* constant bitfield
1239 * @return bool True if the user exists, false if the user is anonymous
1241 public function loadFromDatabase( $flags = self
::READ_LATEST
) {
1243 $this->mId
= intval( $this->mId
);
1245 if ( !$this->mId
) {
1246 // Anonymous users are not in the database
1247 $this->loadDefaults();
1251 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
1252 $db = wfGetDB( $index );
1254 $s = $db->selectRow(
1256 self
::selectFields(),
1257 [ 'user_id' => $this->mId
],
1262 $this->queryFlagsUsed
= $flags;
1263 Hooks
::run( 'UserLoadFromDatabase', [ $this, &$s ] );
1265 if ( $s !== false ) {
1266 // Initialise user table data
1267 $this->loadFromRow( $s );
1268 $this->mGroups
= null; // deferred
1269 $this->getEditCount(); // revalidation for nulls
1274 $this->loadDefaults();
1280 * Initialize this object from a row from the user table.
1282 * @param stdClass $row Row from the user table to load.
1283 * @param array $data Further user data to load into the object
1285 * user_groups Array with groups out of the user_groups table
1286 * user_properties Array with properties out of the user_properties table
1288 protected function loadFromRow( $row, $data = null ) {
1291 $this->mGroups
= null; // deferred
1293 if ( isset( $row->user_name
) ) {
1294 $this->mName
= $row->user_name
;
1295 $this->mFrom
= 'name';
1296 $this->setItemLoaded( 'name' );
1301 if ( isset( $row->user_real_name
) ) {
1302 $this->mRealName
= $row->user_real_name
;
1303 $this->setItemLoaded( 'realname' );
1308 if ( isset( $row->user_id
) ) {
1309 $this->mId
= intval( $row->user_id
);
1310 $this->mFrom
= 'id';
1311 $this->setItemLoaded( 'id' );
1316 if ( isset( $row->user_id
) && isset( $row->user_name
) ) {
1317 self
::$idCacheByName[$row->user_name
] = $row->user_id
;
1320 if ( isset( $row->user_editcount
) ) {
1321 $this->mEditCount
= $row->user_editcount
;
1326 if ( isset( $row->user_touched
) ) {
1327 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1332 if ( isset( $row->user_token
) ) {
1333 // The definition for the column is binary(32), so trim the NULs
1334 // that appends. The previous definition was char(32), so trim
1336 $this->mToken
= rtrim( $row->user_token
, " \0" );
1337 if ( $this->mToken
=== '' ) {
1338 $this->mToken
= null;
1344 if ( isset( $row->user_email
) ) {
1345 $this->mEmail
= $row->user_email
;
1346 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1347 $this->mEmailToken
= $row->user_email_token
;
1348 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1349 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1355 $this->mLoadedItems
= true;
1358 if ( is_array( $data ) ) {
1359 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1360 $this->mGroups
= $data['user_groups'];
1362 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1363 $this->loadOptions( $data['user_properties'] );
1369 * Load the data for this user object from another user object.
1373 protected function loadFromUserObject( $user ) {
1375 foreach ( self
::$mCacheVars as $var ) {
1376 $this->$var = $user->$var;
1381 * Load the groups from the database if they aren't already loaded.
1383 private function loadGroups() {
1384 if ( is_null( $this->mGroups
) ) {
1385 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
1386 ?
wfGetDB( DB_MASTER
)
1387 : wfGetDB( DB_REPLICA
);
1388 $res = $db->select( 'user_groups',
1390 [ 'ug_user' => $this->mId
],
1392 $this->mGroups
= [];
1393 foreach ( $res as $row ) {
1394 $this->mGroups
[] = $row->ug_group
;
1400 * Add the user to the group if he/she meets given criteria.
1402 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1403 * possible to remove manually via Special:UserRights. In such case it
1404 * will not be re-added automatically. The user will also not lose the
1405 * group if they no longer meet the criteria.
1407 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1409 * @return array Array of groups the user has been promoted to.
1411 * @see $wgAutopromoteOnce
1413 public function addAutopromoteOnceGroups( $event ) {
1414 global $wgAutopromoteOnceLogInRC;
1416 if ( wfReadOnly() ||
!$this->getId() ) {
1420 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1421 if ( !count( $toPromote ) ) {
1425 if ( !$this->checkAndSetTouched() ) {
1426 return []; // raced out (bug T48834)
1429 $oldGroups = $this->getGroups(); // previous groups
1430 foreach ( $toPromote as $group ) {
1431 $this->addGroup( $group );
1433 // update groups in external authentication database
1434 Hooks
::run( 'UserGroupsChanged', [ $this, $toPromote, [], false, false ] );
1435 AuthManager
::callLegacyAuthPlugin( 'updateExternalDBGroups', [ $this, $toPromote ] );
1437 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1439 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1440 $logEntry->setPerformer( $this );
1441 $logEntry->setTarget( $this->getUserPage() );
1442 $logEntry->setParameters( [
1443 '4::oldgroups' => $oldGroups,
1444 '5::newgroups' => $newGroups,
1446 $logid = $logEntry->insert();
1447 if ( $wgAutopromoteOnceLogInRC ) {
1448 $logEntry->publish( $logid );
1455 * Builds update conditions. Additional conditions may be added to $conditions to
1456 * protected against race conditions using a compare-and-set (CAS) mechanism
1457 * based on comparing $this->mTouched with the user_touched field.
1459 * @param Database $db
1460 * @param array $conditions WHERE conditions for use with Database::update
1461 * @return array WHERE conditions for use with Database::update
1463 protected function makeUpdateConditions( Database
$db, array $conditions ) {
1464 if ( $this->mTouched
) {
1465 // CAS check: only update if the row wasn't changed sicne it was loaded.
1466 $conditions['user_touched'] = $db->timestamp( $this->mTouched
);
1473 * Bump user_touched if it didn't change since this object was loaded
1475 * On success, the mTouched field is updated.
1476 * The user serialization cache is always cleared.
1478 * @return bool Whether user_touched was actually updated
1481 protected function checkAndSetTouched() {
1484 if ( !$this->mId
) {
1485 return false; // anon
1488 // Get a new user_touched that is higher than the old one
1489 $newTouched = $this->newTouchedTimestamp();
1491 $dbw = wfGetDB( DB_MASTER
);
1492 $dbw->update( 'user',
1493 [ 'user_touched' => $dbw->timestamp( $newTouched ) ],
1494 $this->makeUpdateConditions( $dbw, [
1495 'user_id' => $this->mId
,
1499 $success = ( $dbw->affectedRows() > 0 );
1502 $this->mTouched
= $newTouched;
1503 $this->clearSharedCache();
1505 // Clears on failure too since that is desired if the cache is stale
1506 $this->clearSharedCache( 'refresh' );
1513 * Clear various cached data stored in this object. The cache of the user table
1514 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1516 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1517 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1519 public function clearInstanceCache( $reloadFrom = false ) {
1520 $this->mNewtalk
= -1;
1521 $this->mDatePreference
= null;
1522 $this->mBlockedby
= -1; # Unset
1523 $this->mHash
= false;
1524 $this->mRights
= null;
1525 $this->mEffectiveGroups
= null;
1526 $this->mImplicitGroups
= null;
1527 $this->mGroups
= null;
1528 $this->mOptions
= null;
1529 $this->mOptionsLoaded
= false;
1530 $this->mEditCount
= null;
1532 if ( $reloadFrom ) {
1533 $this->mLoadedItems
= [];
1534 $this->mFrom
= $reloadFrom;
1539 * Combine the language default options with any site-specific options
1540 * and add the default language variants.
1542 * @return array Array of String options
1544 public static function getDefaultOptions() {
1545 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1547 static $defOpt = null;
1548 static $defOptLang = null;
1550 if ( $defOpt !== null && $defOptLang === $wgContLang->getCode() ) {
1551 // $wgContLang does not change (and should not change) mid-request,
1552 // but the unit tests change it anyway, and expect this method to
1553 // return values relevant to the current $wgContLang.
1557 $defOpt = $wgDefaultUserOptions;
1558 // Default language setting
1559 $defOptLang = $wgContLang->getCode();
1560 $defOpt['language'] = $defOptLang;
1561 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1562 $defOpt[$langCode == $wgContLang->getCode() ?
'variant' : "variant-$langCode"] = $langCode;
1565 // NOTE: don't use SearchEngineConfig::getSearchableNamespaces here,
1566 // since extensions may change the set of searchable namespaces depending
1567 // on user groups/permissions.
1568 foreach ( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
1569 $defOpt['searchNs' . $nsnum] = (boolean
)$val;
1571 $defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1573 Hooks
::run( 'UserGetDefaultOptions', [ &$defOpt ] );
1579 * Get a given default option value.
1581 * @param string $opt Name of option to retrieve
1582 * @return string Default option value
1584 public static function getDefaultOption( $opt ) {
1585 $defOpts = self
::getDefaultOptions();
1586 if ( isset( $defOpts[$opt] ) ) {
1587 return $defOpts[$opt];
1594 * Get blocking information
1595 * @param bool $bFromSlave Whether to check the replica DB first.
1596 * To improve performance, non-critical checks are done against replica DBs.
1597 * Check when actually saving should be done against master.
1599 private function getBlockedStatus( $bFromSlave = true ) {
1600 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1602 if ( -1 != $this->mBlockedby
) {
1606 wfDebug( __METHOD__
. ": checking...\n" );
1608 // Initialize data...
1609 // Otherwise something ends up stomping on $this->mBlockedby when
1610 // things get lazy-loaded later, causing false positive block hits
1611 // due to -1 !== 0. Probably session-related... Nothing should be
1612 // overwriting mBlockedby, surely?
1615 # We only need to worry about passing the IP address to the Block generator if the
1616 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1617 # know which IP address they're actually coming from
1619 if ( !$this->isAllowed( 'ipblock-exempt' ) ) {
1620 // $wgUser->getName() only works after the end of Setup.php. Until
1621 // then, assume it's a logged-out user.
1622 $globalUserName = $wgUser->isSafeToLoad()
1623 ?
$wgUser->getName()
1624 : IP
::sanitizeIP( $wgUser->getRequest()->getIP() );
1625 if ( $this->getName() === $globalUserName ) {
1626 $ip = $this->getRequest()->getIP();
1631 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1633 // If no block has been found, check for a cookie indicating that the user is blocked.
1634 $blockCookieVal = (int)$this->getRequest()->getCookie( 'BlockID' );
1635 if ( !$block instanceof Block
&& $blockCookieVal > 0 ) {
1636 // Load the Block from the ID in the cookie.
1637 $tmpBlock = Block
::newFromID( $blockCookieVal );
1638 if ( $tmpBlock instanceof Block
) {
1639 // Check the validity of the block.
1640 $blockIsValid = $tmpBlock->getType() == Block
::TYPE_USER
1641 && !$tmpBlock->isExpired()
1642 && $tmpBlock->isAutoblocking();
1643 $config = RequestContext
::getMain()->getConfig();
1644 $useBlockCookie = ( $config->get( 'CookieSetOnAutoblock' ) === true );
1645 if ( $blockIsValid && $useBlockCookie ) {
1648 $this->blockTrigger
= 'cookie-block';
1650 // If the block is not valid, clear the block cookie (but don't delete it,
1651 // because it needs to be cleared from LocalStorage as well and an empty string
1652 // value is checked for in the mediawiki.user.blockcookie module).
1653 $block->setCookie( $this->getRequest()->response(), true );
1659 if ( !$block instanceof Block
&& $ip !== null && !in_array( $ip, $wgProxyWhitelist ) ) {
1661 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1663 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1664 $block->mReason
= wfMessage( 'proxyblockreason' )->text();
1665 $block->setTarget( $ip );
1666 $this->blockTrigger
= 'proxy-block';
1667 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1669 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1670 $block->mReason
= wfMessage( 'sorbsreason' )->text();
1671 $block->setTarget( $ip );
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
) {
1696 wfDebug( __METHOD__
. ": Found block.\n" );
1697 $this->mBlock
= $block;
1698 $this->mBlockedby
= $block->getByName();
1699 $this->mBlockreason
= $block->mReason
;
1700 $this->mHideName
= $block->mHideName
;
1701 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1703 $this->mBlockedby
= '';
1704 $this->mHideName
= 0;
1705 $this->mAllowUsertalk
= false;
1706 $this->blockTrigger
= false;
1710 Hooks
::run( 'GetBlockedStatus', [ &$this ] );
1714 * Whether the given IP is in a DNS blacklist.
1716 * @param string $ip IP to check
1717 * @param bool $checkWhitelist Whether to check the whitelist first
1718 * @return bool True if blacklisted.
1720 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1721 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1723 if ( !$wgEnableDnsBlacklist ) {
1727 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1731 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1735 * Whether the given IP is in a given DNS blacklist.
1737 * @param string $ip IP to check
1738 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1739 * @return bool True if blacklisted.
1741 public function inDnsBlacklist( $ip, $bases ) {
1743 // @todo FIXME: IPv6 ??? (https://bugs.php.net/bug.php?id=33170)
1744 if ( IP
::isIPv4( $ip ) ) {
1745 // Reverse IP, bug 21255
1746 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1748 foreach ( (array)$bases as $base ) {
1750 // If we have an access key, use that too (ProjectHoneypot, etc.)
1752 if ( is_array( $base ) ) {
1753 if ( count( $base ) >= 2 ) {
1754 // Access key is 1, base URL is 0
1755 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1757 $host = "$ipReversed.{$base[0]}";
1759 $basename = $base[0];
1761 $host = "$ipReversed.$base";
1765 $ipList = gethostbynamel( $host );
1768 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
1772 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
1781 * Check if an IP address is in the local proxy list
1787 public static function isLocallyBlockedProxy( $ip ) {
1788 global $wgProxyList;
1790 if ( !$wgProxyList ) {
1794 if ( !is_array( $wgProxyList ) ) {
1795 // Load from the specified file
1796 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1799 if ( !is_array( $wgProxyList ) ) {
1801 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1803 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1804 // Old-style flipped proxy list
1813 * Is this user subject to rate limiting?
1815 * @return bool True if rate limited
1817 public function isPingLimitable() {
1818 global $wgRateLimitsExcludedIPs;
1819 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1820 // No other good way currently to disable rate limits
1821 // for specific IPs. :P
1822 // But this is a crappy hack and should die.
1825 return !$this->isAllowed( 'noratelimit' );
1829 * Primitive rate limits: enforce maximum actions per time period
1830 * to put a brake on flooding.
1832 * The method generates both a generic profiling point and a per action one
1833 * (suffix being "-$action".
1835 * @note When using a shared cache like memcached, IP-address
1836 * last-hit counters will be shared across wikis.
1838 * @param string $action Action to enforce; 'edit' if unspecified
1839 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1840 * @return bool True if a rate limiter was tripped
1842 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1843 // Call the 'PingLimiter' hook
1845 if ( !Hooks
::run( 'PingLimiter', [ &$this, $action, &$result, $incrBy ] ) ) {
1849 global $wgRateLimits;
1850 if ( !isset( $wgRateLimits[$action] ) ) {
1854 $limits = array_merge(
1855 [ '&can-bypass' => true ],
1856 $wgRateLimits[$action]
1859 // Some groups shouldn't trigger the ping limiter, ever
1860 if ( $limits['&can-bypass'] && !$this->isPingLimitable() ) {
1865 $id = $this->getId();
1867 $isNewbie = $this->isNewbie();
1871 if ( isset( $limits['anon'] ) ) {
1872 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1875 // limits for logged-in users
1876 if ( isset( $limits['user'] ) ) {
1877 $userLimit = $limits['user'];
1879 // limits for newbie logged-in users
1880 if ( $isNewbie && isset( $limits['newbie'] ) ) {
1881 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1885 // limits for anons and for newbie logged-in users
1888 if ( isset( $limits['ip'] ) ) {
1889 $ip = $this->getRequest()->getIP();
1890 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1892 // subnet-based limits
1893 if ( isset( $limits['subnet'] ) ) {
1894 $ip = $this->getRequest()->getIP();
1895 $subnet = IP
::getSubnet( $ip );
1896 if ( $subnet !== false ) {
1897 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1902 // Check for group-specific permissions
1903 // If more than one group applies, use the group with the highest limit ratio (max/period)
1904 foreach ( $this->getGroups() as $group ) {
1905 if ( isset( $limits[$group] ) ) {
1906 if ( $userLimit === false
1907 ||
$limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1909 $userLimit = $limits[$group];
1914 // Set the user limit key
1915 if ( $userLimit !== false ) {
1916 list( $max, $period ) = $userLimit;
1917 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
1918 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1921 // ip-based limits for all ping-limitable users
1922 if ( isset( $limits['ip-all'] ) ) {
1923 $ip = $this->getRequest()->getIP();
1924 // ignore if user limit is more permissive
1925 if ( $isNewbie ||
$userLimit === false
1926 ||
$limits['ip-all'][0] / $limits['ip-all'][1] > $userLimit[0] / $userLimit[1] ) {
1927 $keys["mediawiki:limiter:$action:ip-all:$ip"] = $limits['ip-all'];
1931 // subnet-based limits for all ping-limitable users
1932 if ( isset( $limits['subnet-all'] ) ) {
1933 $ip = $this->getRequest()->getIP();
1934 $subnet = IP
::getSubnet( $ip );
1935 if ( $subnet !== false ) {
1936 // ignore if user limit is more permissive
1937 if ( $isNewbie ||
$userLimit === false
1938 ||
$limits['ip-all'][0] / $limits['ip-all'][1]
1939 > $userLimit[0] / $userLimit[1] ) {
1940 $keys["mediawiki:limiter:$action:subnet-all:$subnet"] = $limits['subnet-all'];
1945 $cache = ObjectCache
::getLocalClusterInstance();
1948 foreach ( $keys as $key => $limit ) {
1949 list( $max, $period ) = $limit;
1950 $summary = "(limit $max in {$period}s)";
1951 $count = $cache->get( $key );
1954 if ( $count >= $max ) {
1955 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1956 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1959 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1962 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1963 if ( $incrBy > 0 ) {
1964 $cache->add( $key, 0, intval( $period ) ); // first ping
1967 if ( $incrBy > 0 ) {
1968 $cache->incr( $key, $incrBy );
1976 * Check if user is blocked
1978 * @param bool $bFromSlave Whether to check the replica DB instead of
1979 * the master. Hacked from false due to horrible probs on site.
1980 * @return bool True if blocked, false otherwise
1982 public function isBlocked( $bFromSlave = true ) {
1983 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
1987 * Get the block affecting the user, or null if the user is not blocked
1989 * @param bool $bFromSlave Whether to check the replica DB instead of the master
1990 * @return Block|null
1992 public function getBlock( $bFromSlave = true ) {
1993 $this->getBlockedStatus( $bFromSlave );
1994 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
1998 * Check if user is blocked from editing a particular article
2000 * @param Title $title Title to check
2001 * @param bool $bFromSlave Whether to check the replica DB instead of the master
2004 public function isBlockedFrom( $title, $bFromSlave = false ) {
2005 global $wgBlockAllowsUTEdit;
2007 $blocked = $this->isBlocked( $bFromSlave );
2008 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
2009 // If a user's name is suppressed, they cannot make edits anywhere
2010 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName()
2011 && $title->getNamespace() == NS_USER_TALK
) {
2013 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
2016 Hooks
::run( 'UserIsBlockedFrom', [ $this, $title, &$blocked, &$allowUsertalk ] );
2022 * If user is blocked, return the name of the user who placed the block
2023 * @return string Name of blocker
2025 public function blockedBy() {
2026 $this->getBlockedStatus();
2027 return $this->mBlockedby
;
2031 * If user is blocked, return the specified reason for the block
2032 * @return string Blocking reason
2034 public function blockedFor() {
2035 $this->getBlockedStatus();
2036 return $this->mBlockreason
;
2040 * If user is blocked, return the ID for the block
2041 * @return int Block ID
2043 public function getBlockId() {
2044 $this->getBlockedStatus();
2045 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
2049 * Check if user is blocked on all wikis.
2050 * Do not use for actual edit permission checks!
2051 * This is intended for quick UI checks.
2053 * @param string $ip IP address, uses current client if none given
2054 * @return bool True if blocked, false otherwise
2056 public function isBlockedGlobally( $ip = '' ) {
2057 return $this->getGlobalBlock( $ip ) instanceof Block
;
2061 * Check if user is blocked on all wikis.
2062 * Do not use for actual edit permission checks!
2063 * This is intended for quick UI checks.
2065 * @param string $ip IP address, uses current client if none given
2066 * @return Block|null Block object if blocked, null otherwise
2067 * @throws FatalError
2068 * @throws MWException
2070 public function getGlobalBlock( $ip = '' ) {
2071 if ( $this->mGlobalBlock
!== null ) {
2072 return $this->mGlobalBlock ?
: null;
2074 // User is already an IP?
2075 if ( IP
::isIPAddress( $this->getName() ) ) {
2076 $ip = $this->getName();
2078 $ip = $this->getRequest()->getIP();
2082 Hooks
::run( 'UserIsBlockedGlobally', [ &$this, $ip, &$blocked, &$block ] );
2084 if ( $blocked && $block === null ) {
2085 // back-compat: UserIsBlockedGlobally didn't have $block param first
2087 $block->setTarget( $ip );
2090 $this->mGlobalBlock
= $blocked ?
$block : false;
2091 return $this->mGlobalBlock ?
: null;
2095 * Check if user account is locked
2097 * @return bool True if locked, false otherwise
2099 public function isLocked() {
2100 if ( $this->mLocked
!== null ) {
2101 return $this->mLocked
;
2103 $authUser = AuthManager
::callLegacyAuthPlugin( 'getUserInstance', [ &$this ], null );
2104 $this->mLocked
= $authUser && $authUser->isLocked();
2105 Hooks
::run( 'UserIsLocked', [ $this, &$this->mLocked
] );
2106 return $this->mLocked
;
2110 * Check if user account is hidden
2112 * @return bool True if hidden, false otherwise
2114 public function isHidden() {
2115 if ( $this->mHideName
!== null ) {
2116 return $this->mHideName
;
2118 $this->getBlockedStatus();
2119 if ( !$this->mHideName
) {
2120 $authUser = AuthManager
::callLegacyAuthPlugin( 'getUserInstance', [ &$this ], null );
2121 $this->mHideName
= $authUser && $authUser->isHidden();
2122 Hooks
::run( 'UserIsHidden', [ $this, &$this->mHideName
] );
2124 return $this->mHideName
;
2128 * Get the user's ID.
2129 * @return int The user's ID; 0 if the user is anonymous or nonexistent
2131 public function getId() {
2132 if ( $this->mId
=== null && $this->mName
!== null && User
::isIP( $this->mName
) ) {
2133 // Special case, we know the user is anonymous
2135 } elseif ( !$this->isItemLoaded( 'id' ) ) {
2136 // Don't load if this was initialized from an ID
2140 return (int)$this->mId
;
2144 * Set the user and reload all fields according to a given ID
2145 * @param int $v User ID to reload
2147 public function setId( $v ) {
2149 $this->clearInstanceCache( 'id' );
2153 * Get the user name, or the IP of an anonymous user
2154 * @return string User's name or IP address
2156 public function getName() {
2157 if ( $this->isItemLoaded( 'name', 'only' ) ) {
2158 // Special case optimisation
2159 return $this->mName
;
2162 if ( $this->mName
=== false ) {
2164 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
2166 return $this->mName
;
2171 * Set the user name.
2173 * This does not reload fields from the database according to the given
2174 * name. Rather, it is used to create a temporary "nonexistent user" for
2175 * later addition to the database. It can also be used to set the IP
2176 * address for an anonymous user to something other than the current
2179 * @note User::newFromName() has roughly the same function, when the named user
2181 * @param string $str New user name to set
2183 public function setName( $str ) {
2185 $this->mName
= $str;
2189 * Get the user's name escaped by underscores.
2190 * @return string Username escaped by underscores.
2192 public function getTitleKey() {
2193 return str_replace( ' ', '_', $this->getName() );
2197 * Check if the user has new messages.
2198 * @return bool True if the user has new messages
2200 public function getNewtalk() {
2203 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2204 if ( $this->mNewtalk
=== -1 ) {
2205 $this->mNewtalk
= false; # reset talk page status
2207 // Check memcached separately for anons, who have no
2208 // entire User object stored in there.
2209 if ( !$this->mId
) {
2210 global $wgDisableAnonTalk;
2211 if ( $wgDisableAnonTalk ) {
2212 // Anon newtalk disabled by configuration.
2213 $this->mNewtalk
= false;
2215 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
2218 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2222 return (bool)$this->mNewtalk
;
2226 * Return the data needed to construct links for new talk page message
2227 * alerts. If there are new messages, this will return an associative array
2228 * with the following data:
2229 * wiki: The database name of the wiki
2230 * link: Root-relative link to the user's talk page
2231 * rev: The last talk page revision that the user has seen or null. This
2232 * is useful for building diff links.
2233 * If there are no new messages, it returns an empty array.
2234 * @note This function was designed to accomodate multiple talk pages, but
2235 * currently only returns a single link and revision.
2238 public function getNewMessageLinks() {
2240 if ( !Hooks
::run( 'UserRetrieveNewTalks', [ &$this, &$talks ] ) ) {
2242 } elseif ( !$this->getNewtalk() ) {
2245 $utp = $this->getTalkPage();
2246 $dbr = wfGetDB( DB_REPLICA
);
2247 // Get the "last viewed rev" timestamp from the oldest message notification
2248 $timestamp = $dbr->selectField( 'user_newtalk',
2249 'MIN(user_last_timestamp)',
2250 $this->isAnon() ?
[ 'user_ip' => $this->getName() ] : [ 'user_id' => $this->getId() ],
2252 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2253 return [ [ 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ] ];
2257 * Get the revision ID for the last talk page revision viewed by the talk
2259 * @return int|null Revision ID or null
2261 public function getNewMessageRevisionId() {
2262 $newMessageRevisionId = null;
2263 $newMessageLinks = $this->getNewMessageLinks();
2264 if ( $newMessageLinks ) {
2265 // Note: getNewMessageLinks() never returns more than a single link
2266 // and it is always for the same wiki, but we double-check here in
2267 // case that changes some time in the future.
2268 if ( count( $newMessageLinks ) === 1
2269 && $newMessageLinks[0]['wiki'] === wfWikiID()
2270 && $newMessageLinks[0]['rev']
2272 /** @var Revision $newMessageRevision */
2273 $newMessageRevision = $newMessageLinks[0]['rev'];
2274 $newMessageRevisionId = $newMessageRevision->getId();
2277 return $newMessageRevisionId;
2281 * Internal uncached check for new messages
2284 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2285 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2286 * @return bool True if the user has new messages
2288 protected function checkNewtalk( $field, $id ) {
2289 $dbr = wfGetDB( DB_REPLICA
);
2291 $ok = $dbr->selectField( 'user_newtalk', $field, [ $field => $id ], __METHOD__
);
2293 return $ok !== false;
2297 * Add or update the new messages flag
2298 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2299 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2300 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2301 * @return bool True if successful, false otherwise
2303 protected function updateNewtalk( $field, $id, $curRev = null ) {
2304 // Get timestamp of the talk page revision prior to the current one
2305 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2306 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2307 // Mark the user as having new messages since this revision
2308 $dbw = wfGetDB( DB_MASTER
);
2309 $dbw->insert( 'user_newtalk',
2310 [ $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ],
2313 if ( $dbw->affectedRows() ) {
2314 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2317 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2323 * Clear the new messages flag for the given user
2324 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2325 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2326 * @return bool True if successful, false otherwise
2328 protected function deleteNewtalk( $field, $id ) {
2329 $dbw = wfGetDB( DB_MASTER
);
2330 $dbw->delete( 'user_newtalk',
2333 if ( $dbw->affectedRows() ) {
2334 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2337 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2343 * Update the 'You have new messages!' status.
2344 * @param bool $val Whether the user has new messages
2345 * @param Revision $curRev New, as yet unseen revision of the user talk
2346 * page. Ignored if null or !$val.
2348 public function setNewtalk( $val, $curRev = null ) {
2349 if ( wfReadOnly() ) {
2354 $this->mNewtalk
= $val;
2356 if ( $this->isAnon() ) {
2358 $id = $this->getName();
2361 $id = $this->getId();
2365 $changed = $this->updateNewtalk( $field, $id, $curRev );
2367 $changed = $this->deleteNewtalk( $field, $id );
2371 $this->invalidateCache();
2376 * Generate a current or new-future timestamp to be stored in the
2377 * user_touched field when we update things.
2378 * @return string Timestamp in TS_MW format
2380 private function newTouchedTimestamp() {
2381 global $wgClockSkewFudge;
2383 $time = wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2384 if ( $this->mTouched
&& $time <= $this->mTouched
) {
2385 $time = wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $this->mTouched
) +
1 );
2392 * Clear user data from memcached
2394 * Use after applying updates to the database; caller's
2395 * responsibility to update user_touched if appropriate.
2397 * Called implicitly from invalidateCache() and saveSettings().
2399 * @param string $mode Use 'refresh' to clear now; otherwise before DB commit
2401 public function clearSharedCache( $mode = 'changed' ) {
2402 if ( !$this->getId() ) {
2406 $cache = ObjectCache
::getMainWANInstance();
2407 $key = $this->getCacheKey( $cache );
2408 if ( $mode === 'refresh' ) {
2409 $cache->delete( $key, 1 );
2411 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle(
2412 function() use ( $cache, $key ) {
2413 $cache->delete( $key );
2421 * Immediately touch the user data cache for this account
2423 * Calls touch() and removes account data from memcached
2425 public function invalidateCache() {
2427 $this->clearSharedCache();
2431 * Update the "touched" timestamp for the user
2433 * This is useful on various login/logout events when making sure that
2434 * a browser or proxy that has multiple tenants does not suffer cache
2435 * pollution where the new user sees the old users content. The value
2436 * of getTouched() is checked when determining 304 vs 200 responses.
2437 * Unlike invalidateCache(), this preserves the User object cache and
2438 * avoids database writes.
2442 public function touch() {
2443 $id = $this->getId();
2445 $key = wfMemcKey( 'user-quicktouched', 'id', $id );
2446 ObjectCache
::getMainWANInstance()->touchCheckKey( $key );
2447 $this->mQuickTouched
= null;
2452 * Validate the cache for this account.
2453 * @param string $timestamp A timestamp in TS_MW format
2456 public function validateCache( $timestamp ) {
2457 return ( $timestamp >= $this->getTouched() );
2461 * Get the user touched timestamp
2463 * Use this value only to validate caches via inequalities
2464 * such as in the case of HTTP If-Modified-Since response logic
2466 * @return string TS_MW Timestamp
2468 public function getTouched() {
2472 if ( $this->mQuickTouched
=== null ) {
2473 $key = wfMemcKey( 'user-quicktouched', 'id', $this->mId
);
2474 $cache = ObjectCache
::getMainWANInstance();
2476 $this->mQuickTouched
= wfTimestamp( TS_MW
, $cache->getCheckKeyTime( $key ) );
2479 return max( $this->mTouched
, $this->mQuickTouched
);
2482 return $this->mTouched
;
2486 * Get the user_touched timestamp field (time of last DB updates)
2487 * @return string TS_MW Timestamp
2490 public function getDBTouched() {
2493 return $this->mTouched
;
2497 * @deprecated Removed in 1.27.
2501 public function getPassword() {
2502 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2506 * @deprecated Removed in 1.27.
2510 public function getTemporaryPassword() {
2511 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2515 * Set the password and reset the random token.
2516 * Calls through to authentication plugin if necessary;
2517 * will have no effect if the auth plugin refuses to
2518 * pass the change through or if the legal password
2521 * As a special case, setting the password to null
2522 * wipes it, so the account cannot be logged in until
2523 * a new password is set, for instance via e-mail.
2525 * @deprecated since 1.27, use AuthManager instead
2526 * @param string $str New password to set
2527 * @throws PasswordError On failure
2530 public function setPassword( $str ) {
2531 return $this->setPasswordInternal( $str );
2535 * Set the password and reset the random token unconditionally.
2537 * @deprecated since 1.27, use AuthManager instead
2538 * @param string|null $str New password to set or null to set an invalid
2539 * password hash meaning that the user will not be able to log in
2540 * through the web interface.
2542 public function setInternalPassword( $str ) {
2543 $this->setPasswordInternal( $str );
2547 * Actually set the password and such
2548 * @since 1.27 cannot set a password for a user not in the database
2549 * @param string|null $str New password to set or null to set an invalid
2550 * password hash meaning that the user will not be able to log in
2551 * through the web interface.
2552 * @return bool Success
2554 private function setPasswordInternal( $str ) {
2555 $manager = AuthManager
::singleton();
2557 // If the user doesn't exist yet, fail
2558 if ( !$manager->userExists( $this->getName() ) ) {
2559 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2562 $status = $this->changeAuthenticationData( [
2563 'username' => $this->getName(),
2567 if ( !$status->isGood() ) {
2568 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
2569 ->info( __METHOD__
. ': Password change rejected: '
2570 . $status->getWikiText( null, null, 'en' ) );
2574 $this->setOption( 'watchlisttoken', false );
2575 SessionManager
::singleton()->invalidateSessionsForUser( $this );
2581 * Changes credentials of the user.
2583 * This is a convenience wrapper around AuthManager::changeAuthenticationData.
2584 * Note that this can return a status that isOK() but not isGood() on certain types of failures,
2585 * e.g. when no provider handled the change.
2587 * @param array $data A set of authentication data in fieldname => value format. This is the
2588 * same data you would pass the changeauthenticationdata API - 'username', 'password' etc.
2592 public function changeAuthenticationData( array $data ) {
2593 $manager = AuthManager
::singleton();
2594 $reqs = $manager->getAuthenticationRequests( AuthManager
::ACTION_CHANGE
, $this );
2595 $reqs = AuthenticationRequest
::loadRequestsFromSubmission( $reqs, $data );
2597 $status = Status
::newGood( 'ignored' );
2598 foreach ( $reqs as $req ) {
2599 $status->merge( $manager->allowsAuthenticationDataChange( $req ), true );
2601 if ( $status->getValue() === 'ignored' ) {
2602 $status->warning( 'authenticationdatachange-ignored' );
2605 if ( $status->isGood() ) {
2606 foreach ( $reqs as $req ) {
2607 $manager->changeAuthenticationData( $req );
2614 * Get the user's current token.
2615 * @param bool $forceCreation Force the generation of a new token if the
2616 * user doesn't have one (default=true for backwards compatibility).
2617 * @return string|null Token
2619 public function getToken( $forceCreation = true ) {
2620 global $wgAuthenticationTokenVersion;
2623 if ( !$this->mToken
&& $forceCreation ) {
2627 if ( !$this->mToken
) {
2628 // The user doesn't have a token, return null to indicate that.
2630 } elseif ( $this->mToken
=== self
::INVALID_TOKEN
) {
2631 // We return a random value here so existing token checks are very
2633 return MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2634 } elseif ( $wgAuthenticationTokenVersion === null ) {
2635 // $wgAuthenticationTokenVersion not in use, so return the raw secret
2636 return $this->mToken
;
2638 // $wgAuthenticationTokenVersion in use, so hmac it.
2639 $ret = MWCryptHash
::hmac( $wgAuthenticationTokenVersion, $this->mToken
, false );
2641 // The raw hash can be overly long. Shorten it up.
2642 $len = max( 32, self
::TOKEN_LENGTH
);
2643 if ( strlen( $ret ) < $len ) {
2644 // Should never happen, even md5 is 128 bits
2645 throw new \
UnexpectedValueException( 'Hmac returned less than 128 bits' );
2647 return substr( $ret, -$len );
2652 * Set the random token (used for persistent authentication)
2653 * Called from loadDefaults() among other places.
2655 * @param string|bool $token If specified, set the token to this value
2657 public function setToken( $token = false ) {
2659 if ( $this->mToken
=== self
::INVALID_TOKEN
) {
2660 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
2661 ->debug( __METHOD__
. ": Ignoring attempt to set token for system user \"$this\"" );
2662 } elseif ( !$token ) {
2663 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2665 $this->mToken
= $token;
2670 * Set the password for a password reminder or new account email
2672 * @deprecated Removed in 1.27. Use PasswordReset instead.
2673 * @param string $str New password to set or null to set an invalid
2674 * password hash meaning that the user will not be able to use it
2675 * @param bool $throttle If true, reset the throttle timestamp to the present
2677 public function setNewpassword( $str, $throttle = true ) {
2678 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2682 * Has password reminder email been sent within the last
2683 * $wgPasswordReminderResendTime hours?
2684 * @deprecated Removed in 1.27. See above.
2687 public function isPasswordReminderThrottled() {
2688 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2692 * Get the user's e-mail address
2693 * @return string User's email address
2695 public function getEmail() {
2697 Hooks
::run( 'UserGetEmail', [ $this, &$this->mEmail
] );
2698 return $this->mEmail
;
2702 * Get the timestamp of the user's e-mail authentication
2703 * @return string TS_MW timestamp
2705 public function getEmailAuthenticationTimestamp() {
2707 Hooks
::run( 'UserGetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
2708 return $this->mEmailAuthenticated
;
2712 * Set the user's e-mail address
2713 * @param string $str New e-mail address
2715 public function setEmail( $str ) {
2717 if ( $str == $this->mEmail
) {
2720 $this->invalidateEmail();
2721 $this->mEmail
= $str;
2722 Hooks
::run( 'UserSetEmail', [ $this, &$this->mEmail
] );
2726 * Set the user's e-mail address and a confirmation mail if needed.
2729 * @param string $str New e-mail address
2732 public function setEmailWithConfirmation( $str ) {
2733 global $wgEnableEmail, $wgEmailAuthentication;
2735 if ( !$wgEnableEmail ) {
2736 return Status
::newFatal( 'emaildisabled' );
2739 $oldaddr = $this->getEmail();
2740 if ( $str === $oldaddr ) {
2741 return Status
::newGood( true );
2744 $type = $oldaddr != '' ?
'changed' : 'set';
2745 $notificationResult = null;
2747 if ( $wgEmailAuthentication ) {
2748 // Send the user an email notifying the user of the change in registered
2749 // email address on their previous email address
2750 if ( $type == 'changed' ) {
2751 $change = $str != '' ?
'changed' : 'removed';
2752 $notificationResult = $this->sendMail(
2753 wfMessage( 'notificationemail_subject_' . $change )->text(),
2754 wfMessage( 'notificationemail_body_' . $change,
2755 $this->getRequest()->getIP(),
2762 $this->setEmail( $str );
2764 if ( $str !== '' && $wgEmailAuthentication ) {
2765 // Send a confirmation request to the new address if needed
2766 $result = $this->sendConfirmationMail( $type );
2768 if ( $notificationResult !== null ) {
2769 $result->merge( $notificationResult );
2772 if ( $result->isGood() ) {
2773 // Say to the caller that a confirmation and notification mail has been sent
2774 $result->value
= 'eauth';
2777 $result = Status
::newGood( true );
2784 * Get the user's real name
2785 * @return string User's real name
2787 public function getRealName() {
2788 if ( !$this->isItemLoaded( 'realname' ) ) {
2792 return $this->mRealName
;
2796 * Set the user's real name
2797 * @param string $str New real name
2799 public function setRealName( $str ) {
2801 $this->mRealName
= $str;
2805 * Get the user's current setting for a given option.
2807 * @param string $oname The option to check
2808 * @param string $defaultOverride A default value returned if the option does not exist
2809 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2810 * @return string User's current value for the option
2811 * @see getBoolOption()
2812 * @see getIntOption()
2814 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2815 global $wgHiddenPrefs;
2816 $this->loadOptions();
2818 # We want 'disabled' preferences to always behave as the default value for
2819 # users, even if they have set the option explicitly in their settings (ie they
2820 # set it, and then it was disabled removing their ability to change it). But
2821 # we don't want to erase the preferences in the database in case the preference
2822 # is re-enabled again. So don't touch $mOptions, just override the returned value
2823 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2824 return self
::getDefaultOption( $oname );
2827 if ( array_key_exists( $oname, $this->mOptions
) ) {
2828 return $this->mOptions
[$oname];
2830 return $defaultOverride;
2835 * Get all user's options
2837 * @param int $flags Bitwise combination of:
2838 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2839 * to the default value. (Since 1.25)
2842 public function getOptions( $flags = 0 ) {
2843 global $wgHiddenPrefs;
2844 $this->loadOptions();
2845 $options = $this->mOptions
;
2847 # We want 'disabled' preferences to always behave as the default value for
2848 # users, even if they have set the option explicitly in their settings (ie they
2849 # set it, and then it was disabled removing their ability to change it). But
2850 # we don't want to erase the preferences in the database in case the preference
2851 # is re-enabled again. So don't touch $mOptions, just override the returned value
2852 foreach ( $wgHiddenPrefs as $pref ) {
2853 $default = self
::getDefaultOption( $pref );
2854 if ( $default !== null ) {
2855 $options[$pref] = $default;
2859 if ( $flags & self
::GETOPTIONS_EXCLUDE_DEFAULTS
) {
2860 $options = array_diff_assoc( $options, self
::getDefaultOptions() );
2867 * Get the user's current setting for a given option, as a boolean value.
2869 * @param string $oname The option to check
2870 * @return bool User's current value for the option
2873 public function getBoolOption( $oname ) {
2874 return (bool)$this->getOption( $oname );
2878 * Get the user's current setting for a given option, as an integer value.
2880 * @param string $oname The option to check
2881 * @param int $defaultOverride A default value returned if the option does not exist
2882 * @return int User's current value for the option
2885 public function getIntOption( $oname, $defaultOverride = 0 ) {
2886 $val = $this->getOption( $oname );
2888 $val = $defaultOverride;
2890 return intval( $val );
2894 * Set the given option for a user.
2896 * You need to call saveSettings() to actually write to the database.
2898 * @param string $oname The option to set
2899 * @param mixed $val New value to set
2901 public function setOption( $oname, $val ) {
2902 $this->loadOptions();
2904 // Explicitly NULL values should refer to defaults
2905 if ( is_null( $val ) ) {
2906 $val = self
::getDefaultOption( $oname );
2909 $this->mOptions
[$oname] = $val;
2913 * Get a token stored in the preferences (like the watchlist one),
2914 * resetting it if it's empty (and saving changes).
2916 * @param string $oname The option name to retrieve the token from
2917 * @return string|bool User's current value for the option, or false if this option is disabled.
2918 * @see resetTokenFromOption()
2920 * @deprecated since 1.26 Applications should use the OAuth extension
2922 public function getTokenFromOption( $oname ) {
2923 global $wgHiddenPrefs;
2925 $id = $this->getId();
2926 if ( !$id ||
in_array( $oname, $wgHiddenPrefs ) ) {
2930 $token = $this->getOption( $oname );
2932 // Default to a value based on the user token to avoid space
2933 // wasted on storing tokens for all users. When this option
2934 // is set manually by the user, only then is it stored.
2935 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
2942 * Reset a token stored in the preferences (like the watchlist one).
2943 * *Does not* save user's preferences (similarly to setOption()).
2945 * @param string $oname The option name to reset the token in
2946 * @return string|bool New token value, or false if this option is disabled.
2947 * @see getTokenFromOption()
2950 public function resetTokenFromOption( $oname ) {
2951 global $wgHiddenPrefs;
2952 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2956 $token = MWCryptRand
::generateHex( 40 );
2957 $this->setOption( $oname, $token );
2962 * Return a list of the types of user options currently returned by
2963 * User::getOptionKinds().
2965 * Currently, the option kinds are:
2966 * - 'registered' - preferences which are registered in core MediaWiki or
2967 * by extensions using the UserGetDefaultOptions hook.
2968 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2969 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2970 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2971 * be used by user scripts.
2972 * - 'special' - "preferences" that are not accessible via User::getOptions
2973 * or User::setOptions.
2974 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2975 * These are usually legacy options, removed in newer versions.
2977 * The API (and possibly others) use this function to determine the possible
2978 * option types for validation purposes, so make sure to update this when a
2979 * new option kind is added.
2981 * @see User::getOptionKinds
2982 * @return array Option kinds
2984 public static function listOptionKinds() {
2987 'registered-multiselect',
2988 'registered-checkmatrix',
2996 * Return an associative array mapping preferences keys to the kind of a preference they're
2997 * used for. Different kinds are handled differently when setting or reading preferences.
2999 * See User::listOptionKinds for the list of valid option types that can be provided.
3001 * @see User::listOptionKinds
3002 * @param IContextSource $context
3003 * @param array $options Assoc. array with options keys to check as keys.
3004 * Defaults to $this->mOptions.
3005 * @return array The key => kind mapping data
3007 public function getOptionKinds( IContextSource
$context, $options = null ) {
3008 $this->loadOptions();
3009 if ( $options === null ) {
3010 $options = $this->mOptions
;
3013 $prefs = Preferences
::getPreferences( $this, $context );
3016 // Pull out the "special" options, so they don't get converted as
3017 // multiselect or checkmatrix.
3018 $specialOptions = array_fill_keys( Preferences
::getSaveBlacklist(), true );
3019 foreach ( $specialOptions as $name => $value ) {
3020 unset( $prefs[$name] );
3023 // Multiselect and checkmatrix options are stored in the database with
3024 // one key per option, each having a boolean value. Extract those keys.
3025 $multiselectOptions = [];
3026 foreach ( $prefs as $name => $info ) {
3027 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
3028 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
3029 $opts = HTMLFormField
::flattenOptions( $info['options'] );
3030 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
3032 foreach ( $opts as $value ) {
3033 $multiselectOptions["$prefix$value"] = true;
3036 unset( $prefs[$name] );
3039 $checkmatrixOptions = [];
3040 foreach ( $prefs as $name => $info ) {
3041 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
3042 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
3043 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
3044 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
3045 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
3047 foreach ( $columns as $column ) {
3048 foreach ( $rows as $row ) {
3049 $checkmatrixOptions["$prefix$column-$row"] = true;
3053 unset( $prefs[$name] );
3057 // $value is ignored
3058 foreach ( $options as $key => $value ) {
3059 if ( isset( $prefs[$key] ) ) {
3060 $mapping[$key] = 'registered';
3061 } elseif ( isset( $multiselectOptions[$key] ) ) {
3062 $mapping[$key] = 'registered-multiselect';
3063 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
3064 $mapping[$key] = 'registered-checkmatrix';
3065 } elseif ( isset( $specialOptions[$key] ) ) {
3066 $mapping[$key] = 'special';
3067 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
3068 $mapping[$key] = 'userjs';
3070 $mapping[$key] = 'unused';
3078 * Reset certain (or all) options to the site defaults
3080 * The optional parameter determines which kinds of preferences will be reset.
3081 * Supported values are everything that can be reported by getOptionKinds()
3082 * and 'all', which forces a reset of *all* preferences and overrides everything else.
3084 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
3085 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
3086 * for backwards-compatibility.
3087 * @param IContextSource|null $context Context source used when $resetKinds
3088 * does not contain 'all', passed to getOptionKinds().
3089 * Defaults to RequestContext::getMain() when null.
3091 public function resetOptions(
3092 $resetKinds = [ 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ],
3093 IContextSource
$context = null
3096 $defaultOptions = self
::getDefaultOptions();
3098 if ( !is_array( $resetKinds ) ) {
3099 $resetKinds = [ $resetKinds ];
3102 if ( in_array( 'all', $resetKinds ) ) {
3103 $newOptions = $defaultOptions;
3105 if ( $context === null ) {
3106 $context = RequestContext
::getMain();
3109 $optionKinds = $this->getOptionKinds( $context );
3110 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
3113 // Use default values for the options that should be deleted, and
3114 // copy old values for the ones that shouldn't.
3115 foreach ( $this->mOptions
as $key => $value ) {
3116 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
3117 if ( array_key_exists( $key, $defaultOptions ) ) {
3118 $newOptions[$key] = $defaultOptions[$key];
3121 $newOptions[$key] = $value;
3126 Hooks
::run( 'UserResetAllOptions', [ $this, &$newOptions, $this->mOptions
, $resetKinds ] );
3128 $this->mOptions
= $newOptions;
3129 $this->mOptionsLoaded
= true;
3133 * Get the user's preferred date format.
3134 * @return string User's preferred date format
3136 public function getDatePreference() {
3137 // Important migration for old data rows
3138 if ( is_null( $this->mDatePreference
) ) {
3140 $value = $this->getOption( 'date' );
3141 $map = $wgLang->getDatePreferenceMigrationMap();
3142 if ( isset( $map[$value] ) ) {
3143 $value = $map[$value];
3145 $this->mDatePreference
= $value;
3147 return $this->mDatePreference
;
3151 * Determine based on the wiki configuration and the user's options,
3152 * whether this user must be over HTTPS no matter what.
3156 public function requiresHTTPS() {
3157 global $wgSecureLogin;
3158 if ( !$wgSecureLogin ) {
3161 $https = $this->getBoolOption( 'prefershttps' );
3162 Hooks
::run( 'UserRequiresHTTPS', [ $this, &$https ] );
3164 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
3171 * Get the user preferred stub threshold
3175 public function getStubThreshold() {
3176 global $wgMaxArticleSize; # Maximum article size, in Kb
3177 $threshold = $this->getIntOption( 'stubthreshold' );
3178 if ( $threshold > $wgMaxArticleSize * 1024 ) {
3179 // If they have set an impossible value, disable the preference
3180 // so we can use the parser cache again.
3187 * Get the permissions this user has.
3188 * @return array Array of String permission names
3190 public function getRights() {
3191 if ( is_null( $this->mRights
) ) {
3192 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
3193 Hooks
::run( 'UserGetRights', [ $this, &$this->mRights
] );
3195 // Deny any rights denied by the user's session, unless this
3196 // endpoint has no sessions.
3197 if ( !defined( 'MW_NO_SESSION' ) ) {
3198 $allowedRights = $this->getRequest()->getSession()->getAllowedUserRights();
3199 if ( $allowedRights !== null ) {
3200 $this->mRights
= array_intersect( $this->mRights
, $allowedRights );
3204 // Force reindexation of rights when a hook has unset one of them
3205 $this->mRights
= array_values( array_unique( $this->mRights
) );
3207 // If block disables login, we should also remove any
3208 // extra rights blocked users might have, in case the
3209 // blocked user has a pre-existing session (T129738).
3210 // This is checked here for cases where people only call
3211 // $user->isAllowed(). It is also checked in Title::checkUserBlock()
3212 // to give a better error message in the common case.
3213 $config = RequestContext
::getMain()->getConfig();
3215 $this->isLoggedIn() &&
3216 $config->get( 'BlockDisablesLogin' ) &&
3220 $this->mRights
= array_intersect( $this->mRights
, $anon->getRights() );
3223 return $this->mRights
;
3227 * Get the list of explicit group memberships this user has.
3228 * The implicit * and user groups are not included.
3229 * @return array Array of String internal group names
3231 public function getGroups() {
3233 $this->loadGroups();
3234 return $this->mGroups
;
3238 * Get the list of implicit group memberships this user has.
3239 * This includes all explicit groups, plus 'user' if logged in,
3240 * '*' for all accounts, and autopromoted groups
3241 * @param bool $recache Whether to avoid the cache
3242 * @return array Array of String internal group names
3244 public function getEffectiveGroups( $recache = false ) {
3245 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
3246 $this->mEffectiveGroups
= array_unique( array_merge(
3247 $this->getGroups(), // explicit groups
3248 $this->getAutomaticGroups( $recache ) // implicit groups
3250 // Hook for additional groups
3251 Hooks
::run( 'UserEffectiveGroups', [ &$this, &$this->mEffectiveGroups
] );
3252 // Force reindexation of groups when a hook has unset one of them
3253 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
3255 return $this->mEffectiveGroups
;
3259 * Get the list of implicit group memberships this user has.
3260 * This includes 'user' if logged in, '*' for all accounts,
3261 * and autopromoted groups
3262 * @param bool $recache Whether to avoid the cache
3263 * @return array Array of String internal group names
3265 public function getAutomaticGroups( $recache = false ) {
3266 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
3267 $this->mImplicitGroups
= [ '*' ];
3268 if ( $this->getId() ) {
3269 $this->mImplicitGroups
[] = 'user';
3271 $this->mImplicitGroups
= array_unique( array_merge(
3272 $this->mImplicitGroups
,
3273 Autopromote
::getAutopromoteGroups( $this )
3277 // Assure data consistency with rights/groups,
3278 // as getEffectiveGroups() depends on this function
3279 $this->mEffectiveGroups
= null;
3282 return $this->mImplicitGroups
;
3286 * Returns the groups the user has belonged to.
3288 * The user may still belong to the returned groups. Compare with getGroups().
3290 * The function will not return groups the user had belonged to before MW 1.17
3292 * @return array Names of the groups the user has belonged to.
3294 public function getFormerGroups() {
3297 if ( is_null( $this->mFormerGroups
) ) {
3298 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3299 ?
wfGetDB( DB_MASTER
)
3300 : wfGetDB( DB_REPLICA
);
3301 $res = $db->select( 'user_former_groups',
3303 [ 'ufg_user' => $this->mId
],
3305 $this->mFormerGroups
= [];
3306 foreach ( $res as $row ) {
3307 $this->mFormerGroups
[] = $row->ufg_group
;
3311 return $this->mFormerGroups
;
3315 * Get the user's edit count.
3316 * @return int|null Null for anonymous users
3318 public function getEditCount() {
3319 if ( !$this->getId() ) {
3323 if ( $this->mEditCount
=== null ) {
3324 /* Populate the count, if it has not been populated yet */
3325 $dbr = wfGetDB( DB_REPLICA
);
3326 // check if the user_editcount field has been initialized
3327 $count = $dbr->selectField(
3328 'user', 'user_editcount',
3329 [ 'user_id' => $this->mId
],
3333 if ( $count === null ) {
3334 // it has not been initialized. do so.
3335 $count = $this->initEditCount();
3337 $this->mEditCount
= $count;
3339 return (int)$this->mEditCount
;
3343 * Add the user to the given group.
3344 * This takes immediate effect.
3345 * @param string $group Name of the group to add
3348 public function addGroup( $group ) {
3351 if ( !Hooks
::run( 'UserAddGroup', [ $this, &$group ] ) ) {
3355 $dbw = wfGetDB( DB_MASTER
);
3356 if ( $this->getId() ) {
3357 $dbw->insert( 'user_groups',
3359 'ug_user' => $this->getId(),
3360 'ug_group' => $group,
3366 $this->loadGroups();
3367 $this->mGroups
[] = $group;
3368 // In case loadGroups was not called before, we now have the right twice.
3369 // Get rid of the duplicate.
3370 $this->mGroups
= array_unique( $this->mGroups
);
3372 // Refresh the groups caches, and clear the rights cache so it will be
3373 // refreshed on the next call to $this->getRights().
3374 $this->getEffectiveGroups( true );
3375 $this->mRights
= null;
3377 $this->invalidateCache();
3383 * Remove the user from the given group.
3384 * This takes immediate effect.
3385 * @param string $group Name of the group to remove
3388 public function removeGroup( $group ) {
3390 if ( !Hooks
::run( 'UserRemoveGroup', [ $this, &$group ] ) ) {
3394 $dbw = wfGetDB( DB_MASTER
);
3395 $dbw->delete( 'user_groups',
3397 'ug_user' => $this->getId(),
3398 'ug_group' => $group,
3401 // Remember that the user was in this group
3402 $dbw->insert( 'user_former_groups',
3404 'ufg_user' => $this->getId(),
3405 'ufg_group' => $group,
3411 $this->loadGroups();
3412 $this->mGroups
= array_diff( $this->mGroups
, [ $group ] );
3414 // Refresh the groups caches, and clear the rights cache so it will be
3415 // refreshed on the next call to $this->getRights().
3416 $this->getEffectiveGroups( true );
3417 $this->mRights
= null;
3419 $this->invalidateCache();
3425 * Get whether the user is logged in
3428 public function isLoggedIn() {
3429 return $this->getId() != 0;
3433 * Get whether the user is anonymous
3436 public function isAnon() {
3437 return !$this->isLoggedIn();
3441 * @return bool Whether this user is flagged as being a bot role account
3444 public function isBot() {
3445 if ( in_array( 'bot', $this->getGroups() ) && $this->isAllowed( 'bot' ) ) {
3450 Hooks
::run( "UserIsBot", [ $this, &$isBot ] );
3456 * Check if user is allowed to access a feature / make an action
3458 * @param string ... Permissions to test
3459 * @return bool True if user is allowed to perform *any* of the given actions
3461 public function isAllowedAny() {
3462 $permissions = func_get_args();
3463 foreach ( $permissions as $permission ) {
3464 if ( $this->isAllowed( $permission ) ) {
3473 * @param string ... Permissions to test
3474 * @return bool True if the user is allowed to perform *all* of the given actions
3476 public function isAllowedAll() {
3477 $permissions = func_get_args();
3478 foreach ( $permissions as $permission ) {
3479 if ( !$this->isAllowed( $permission ) ) {
3487 * Internal mechanics of testing a permission
3488 * @param string $action
3491 public function isAllowed( $action = '' ) {
3492 if ( $action === '' ) {
3493 return true; // In the spirit of DWIM
3495 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3496 // by misconfiguration: 0 == 'foo'
3497 return in_array( $action, $this->getRights(), true );
3501 * Check whether to enable recent changes patrol features for this user
3502 * @return bool True or false
3504 public function useRCPatrol() {
3505 global $wgUseRCPatrol;
3506 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3510 * Check whether to enable new pages patrol features for this user
3511 * @return bool True or false
3513 public function useNPPatrol() {
3514 global $wgUseRCPatrol, $wgUseNPPatrol;
3516 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3517 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3522 * Check whether to enable new files patrol features for this user
3523 * @return bool True or false
3525 public function useFilePatrol() {
3526 global $wgUseRCPatrol, $wgUseFilePatrol;
3528 ( $wgUseRCPatrol ||
$wgUseFilePatrol )
3529 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3534 * Get the WebRequest object to use with this object
3536 * @return WebRequest
3538 public function getRequest() {
3539 if ( $this->mRequest
) {
3540 return $this->mRequest
;
3548 * Check the watched status of an article.
3549 * @since 1.22 $checkRights parameter added
3550 * @param Title $title Title of the article to look at
3551 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3552 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3555 public function isWatched( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3556 if ( $title->isWatchable() && ( !$checkRights ||
$this->isAllowed( 'viewmywatchlist' ) ) ) {
3557 return MediaWikiServices
::getInstance()->getWatchedItemStore()->isWatched( $this, $title );
3564 * @since 1.22 $checkRights parameter added
3565 * @param Title $title Title of the article to look at
3566 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3567 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3569 public function addWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3570 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3571 MediaWikiServices
::getInstance()->getWatchedItemStore()->addWatchBatchForUser(
3573 [ $title->getSubjectPage(), $title->getTalkPage() ]
3576 $this->invalidateCache();
3580 * Stop watching an article.
3581 * @since 1.22 $checkRights parameter added
3582 * @param Title $title Title of the article to look at
3583 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3584 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3586 public function removeWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3587 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3588 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
3589 $store->removeWatch( $this, $title->getSubjectPage() );
3590 $store->removeWatch( $this, $title->getTalkPage() );
3592 $this->invalidateCache();
3596 * Clear the user's notification timestamp for the given title.
3597 * If e-notif e-mails are on, they will receive notification mails on
3598 * the next change of the page if it's watched etc.
3599 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3600 * @param Title $title Title of the article to look at
3601 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3603 public function clearNotification( &$title, $oldid = 0 ) {
3604 global $wgUseEnotif, $wgShowUpdatedMarker;
3606 // Do nothing if the database is locked to writes
3607 if ( wfReadOnly() ) {
3611 // Do nothing if not allowed to edit the watchlist
3612 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3616 // If we're working on user's talk page, we should update the talk page message indicator
3617 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3618 if ( !Hooks
::run( 'UserClearNewTalkNotification', [ &$this, $oldid ] ) ) {
3622 // Try to update the DB post-send and only if needed...
3623 DeferredUpdates
::addCallableUpdate( function() use ( $title, $oldid ) {
3624 if ( !$this->getNewtalk() ) {
3625 return; // no notifications to clear
3628 // Delete the last notifications (they stack up)
3629 $this->setNewtalk( false );
3631 // If there is a new, unseen, revision, use its timestamp
3633 ?
$title->getNextRevisionID( $oldid, Title
::GAID_FOR_UPDATE
)
3636 $this->setNewtalk( true, Revision
::newFromId( $nextid ) );
3641 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3645 if ( $this->isAnon() ) {
3646 // Nothing else to do...
3650 // Only update the timestamp if the page is being watched.
3651 // The query to find out if it is watched is cached both in memcached and per-invocation,
3652 // and when it does have to be executed, it can be on a replica DB
3653 // If this is the user's newtalk page, we always update the timestamp
3655 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3659 MediaWikiServices
::getInstance()->getWatchedItemStore()
3660 ->resetNotificationTimestamp( $this, $title, $force, $oldid );
3664 * Resets all of the given user's page-change notification timestamps.
3665 * If e-notif e-mails are on, they will receive notification mails on
3666 * the next change of any watched page.
3667 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3669 public function clearAllNotifications() {
3670 global $wgUseEnotif, $wgShowUpdatedMarker;
3671 // Do nothing if not allowed to edit the watchlist
3672 if ( wfReadOnly() ||
!$this->isAllowed( 'editmywatchlist' ) ) {
3676 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3677 $this->setNewtalk( false );
3681 $id = $this->getId();
3686 $dbw = wfGetDB( DB_MASTER
);
3687 $asOfTimes = array_unique( $dbw->selectFieldValues(
3689 'wl_notificationtimestamp',
3690 [ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ],
3692 [ 'ORDER BY' => 'wl_notificationtimestamp DESC', 'LIMIT' => 500 ]
3694 if ( !$asOfTimes ) {
3697 // Immediately update the most recent touched rows, which hopefully covers what
3698 // the user sees on the watchlist page before pressing "mark all pages visited"....
3701 [ 'wl_notificationtimestamp' => null ],
3702 [ 'wl_user' => $id, 'wl_notificationtimestamp' => $asOfTimes ],
3705 // ...and finish the older ones in a post-send update with lag checks...
3706 DeferredUpdates
::addUpdate( new AutoCommitUpdate(
3709 function () use ( $dbw, $id ) {
3710 global $wgUpdateRowsPerQuery;
3712 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
3713 $ticket = $lbFactory->getEmptyTransactionTicket( __METHOD__
);
3714 $asOfTimes = array_unique( $dbw->selectFieldValues(
3716 'wl_notificationtimestamp',
3717 [ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ],
3720 foreach ( array_chunk( $asOfTimes, $wgUpdateRowsPerQuery ) as $asOfTimeBatch ) {
3723 [ 'wl_notificationtimestamp' => null ],
3724 [ 'wl_user' => $id, 'wl_notificationtimestamp' => $asOfTimeBatch ],
3727 $lbFactory->commitAndWaitForReplication( __METHOD__
, $ticket );
3731 // We also need to clear here the "you have new message" notification for the own
3732 // user_talk page; it's cleared one page view later in WikiPage::doViewUpdates().
3736 * Set a cookie on the user's client. Wrapper for
3737 * WebResponse::setCookie
3738 * @deprecated since 1.27
3739 * @param string $name Name of the cookie to set
3740 * @param string $value Value to set
3741 * @param int $exp Expiration time, as a UNIX time value;
3742 * if 0 or not specified, use the default $wgCookieExpiration
3743 * @param bool $secure
3744 * true: Force setting the secure attribute when setting the cookie
3745 * false: Force NOT setting the secure attribute when setting the cookie
3746 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3747 * @param array $params Array of options sent passed to WebResponse::setcookie()
3748 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3751 protected function setCookie(
3752 $name, $value, $exp = 0, $secure = null, $params = [], $request = null
3754 wfDeprecated( __METHOD__
, '1.27' );
3755 if ( $request === null ) {
3756 $request = $this->getRequest();
3758 $params['secure'] = $secure;
3759 $request->response()->setCookie( $name, $value, $exp, $params );
3763 * Clear a cookie on the user's client
3764 * @deprecated since 1.27
3765 * @param string $name Name of the cookie to clear
3766 * @param bool $secure
3767 * true: Force setting the secure attribute when setting the cookie
3768 * false: Force NOT setting the secure attribute when setting the cookie
3769 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3770 * @param array $params Array of options sent passed to WebResponse::setcookie()
3772 protected function clearCookie( $name, $secure = null, $params = [] ) {
3773 wfDeprecated( __METHOD__
, '1.27' );
3774 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3778 * Set an extended login cookie on the user's client. The expiry of the cookie
3779 * is controlled by the $wgExtendedLoginCookieExpiration configuration
3782 * @see User::setCookie
3784 * @deprecated since 1.27
3785 * @param string $name Name of the cookie to set
3786 * @param string $value Value to set
3787 * @param bool $secure
3788 * true: Force setting the secure attribute when setting the cookie
3789 * false: Force NOT setting the secure attribute when setting the cookie
3790 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3792 protected function setExtendedLoginCookie( $name, $value, $secure ) {
3793 global $wgExtendedLoginCookieExpiration, $wgCookieExpiration;
3795 wfDeprecated( __METHOD__
, '1.27' );
3798 $exp +
= $wgExtendedLoginCookieExpiration !== null
3799 ?
$wgExtendedLoginCookieExpiration
3800 : $wgCookieExpiration;
3802 $this->setCookie( $name, $value, $exp, $secure );
3806 * Persist this user's session (e.g. set cookies)
3808 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3810 * @param bool $secure Whether to force secure/insecure cookies or use default
3811 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3813 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3815 if ( 0 == $this->mId
) {
3819 $session = $this->getRequest()->getSession();
3820 if ( $request && $session->getRequest() !== $request ) {
3821 $session = $session->sessionWithRequest( $request );
3823 $delay = $session->delaySave();
3825 if ( !$session->getUser()->equals( $this ) ) {
3826 if ( !$session->canSetUser() ) {
3827 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3828 ->warning( __METHOD__
.
3829 ": Cannot save user \"$this\" to a user \"{$session->getUser()}\"'s immutable session"
3833 $session->setUser( $this );
3836 $session->setRememberUser( $rememberMe );
3837 if ( $secure !== null ) {
3838 $session->setForceHTTPS( $secure );
3841 $session->persist();
3843 ScopedCallback
::consume( $delay );
3847 * Log this user out.
3849 public function logout() {
3850 if ( Hooks
::run( 'UserLogout', [ &$this ] ) ) {
3856 * Clear the user's session, and reset the instance cache.
3859 public function doLogout() {
3860 $session = $this->getRequest()->getSession();
3861 if ( !$session->canSetUser() ) {
3862 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3863 ->warning( __METHOD__
. ": Cannot log out of an immutable session" );
3864 $error = 'immutable';
3865 } elseif ( !$session->getUser()->equals( $this ) ) {
3866 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3867 ->warning( __METHOD__
.
3868 ": Cannot log user \"$this\" out of a user \"{$session->getUser()}\"'s session"
3870 // But we still may as well make this user object anon
3871 $this->clearInstanceCache( 'defaults' );
3872 $error = 'wronguser';
3874 $this->clearInstanceCache( 'defaults' );
3875 $delay = $session->delaySave();
3876 $session->unpersist(); // Clear cookies (T127436)
3877 $session->setLoggedOutTimestamp( time() );
3878 $session->setUser( new User
);
3879 $session->set( 'wsUserID', 0 ); // Other code expects this
3880 $session->resetAllTokens();
3881 ScopedCallback
::consume( $delay );
3884 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authevents' )->info( 'Logout', [
3885 'event' => 'logout',
3886 'successful' => $error === false,
3887 'status' => $error ?
: 'success',
3892 * Save this user's settings into the database.
3893 * @todo Only rarely do all these fields need to be set!
3895 public function saveSettings() {
3896 if ( wfReadOnly() ) {
3897 // @TODO: caller should deal with this instead!
3898 // This should really just be an exception.
3899 MWExceptionHandler
::logException( new DBExpectedError(
3901 "Could not update user with ID '{$this->mId}'; DB is read-only."
3907 if ( 0 == $this->mId
) {
3911 // Get a new user_touched that is higher than the old one.
3912 // This will be used for a CAS check as a last-resort safety
3913 // check against race conditions and replica DB lag.
3914 $newTouched = $this->newTouchedTimestamp();
3916 $dbw = wfGetDB( DB_MASTER
);
3917 $dbw->update( 'user',
3919 'user_name' => $this->mName
,
3920 'user_real_name' => $this->mRealName
,
3921 'user_email' => $this->mEmail
,
3922 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3923 'user_touched' => $dbw->timestamp( $newTouched ),
3924 'user_token' => strval( $this->mToken
),
3925 'user_email_token' => $this->mEmailToken
,
3926 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
3927 ], $this->makeUpdateConditions( $dbw, [ /* WHERE */
3928 'user_id' => $this->mId
,
3932 if ( !$dbw->affectedRows() ) {
3933 // Maybe the problem was a missed cache update; clear it to be safe
3934 $this->clearSharedCache( 'refresh' );
3935 // User was changed in the meantime or loaded with stale data
3936 $from = ( $this->queryFlagsUsed
& self
::READ_LATEST
) ?
'master' : 'replica';
3937 throw new MWException(
3938 "CAS update failed on user_touched for user ID '{$this->mId}' (read from $from);" .
3939 " the version of the user to be saved is older than the current version."
3943 $this->mTouched
= $newTouched;
3944 $this->saveOptions();
3946 Hooks
::run( 'UserSaveSettings', [ $this ] );
3947 $this->clearSharedCache();
3948 $this->getUserPage()->invalidateCache();
3952 * If only this user's username is known, and it exists, return the user ID.
3954 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
3957 public function idForName( $flags = 0 ) {
3958 $s = trim( $this->getName() );
3963 $db = ( ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
)
3964 ?
wfGetDB( DB_MASTER
)
3965 : wfGetDB( DB_REPLICA
);
3967 $options = ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
)
3968 ?
[ 'LOCK IN SHARE MODE' ]
3971 $id = $db->selectField( 'user',
3972 'user_id', [ 'user_name' => $s ], __METHOD__
, $options );
3978 * Add a user to the database, return the user object
3980 * @param string $name Username to add
3981 * @param array $params Array of Strings Non-default parameters to save to
3982 * the database as user_* fields:
3983 * - email: The user's email address.
3984 * - email_authenticated: The email authentication timestamp.
3985 * - real_name: The user's real name.
3986 * - options: An associative array of non-default options.
3987 * - token: Random authentication token. Do not set.
3988 * - registration: Registration timestamp. Do not set.
3990 * @return User|null User object, or null if the username already exists.
3992 public static function createNew( $name, $params = [] ) {
3993 foreach ( [ 'password', 'newpassword', 'newpass_time', 'password_expires' ] as $field ) {
3994 if ( isset( $params[$field] ) ) {
3995 wfDeprecated( __METHOD__
. " with param '$field'", '1.27' );
3996 unset( $params[$field] );
4002 $user->setToken(); // init token
4003 if ( isset( $params['options'] ) ) {
4004 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
4005 unset( $params['options'] );
4007 $dbw = wfGetDB( DB_MASTER
);
4008 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
4010 $noPass = PasswordFactory
::newInvalidPassword()->toString();
4013 'user_id' => $seqVal,
4014 'user_name' => $name,
4015 'user_password' => $noPass,
4016 'user_newpassword' => $noPass,
4017 'user_email' => $user->mEmail
,
4018 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
4019 'user_real_name' => $user->mRealName
,
4020 'user_token' => strval( $user->mToken
),
4021 'user_registration' => $dbw->timestamp( $user->mRegistration
),
4022 'user_editcount' => 0,
4023 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
4025 foreach ( $params as $name => $value ) {
4026 $fields["user_$name"] = $value;
4028 $dbw->insert( 'user', $fields, __METHOD__
, [ 'IGNORE' ] );
4029 if ( $dbw->affectedRows() ) {
4030 $newUser = User
::newFromId( $dbw->insertId() );
4038 * Add this existing user object to the database. If the user already
4039 * exists, a fatal status object is returned, and the user object is
4040 * initialised with the data from the database.
4042 * Previously, this function generated a DB error due to a key conflict
4043 * if the user already existed. Many extension callers use this function
4044 * in code along the lines of:
4046 * $user = User::newFromName( $name );
4047 * if ( !$user->isLoggedIn() ) {
4048 * $user->addToDatabase();
4050 * // do something with $user...
4052 * However, this was vulnerable to a race condition (bug 16020). By
4053 * initialising the user object if the user exists, we aim to support this
4054 * calling sequence as far as possible.
4056 * Note that if the user exists, this function will acquire a write lock,
4057 * so it is still advisable to make the call conditional on isLoggedIn(),
4058 * and to commit the transaction after calling.
4060 * @throws MWException
4063 public function addToDatabase() {
4065 if ( !$this->mToken
) {
4066 $this->setToken(); // init token
4069 $this->mTouched
= $this->newTouchedTimestamp();
4071 $noPass = PasswordFactory
::newInvalidPassword()->toString();
4073 $dbw = wfGetDB( DB_MASTER
);
4074 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
4075 $dbw->insert( 'user',
4077 'user_id' => $seqVal,
4078 'user_name' => $this->mName
,
4079 'user_password' => $noPass,
4080 'user_newpassword' => $noPass,
4081 'user_email' => $this->mEmail
,
4082 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
4083 'user_real_name' => $this->mRealName
,
4084 'user_token' => strval( $this->mToken
),
4085 'user_registration' => $dbw->timestamp( $this->mRegistration
),
4086 'user_editcount' => 0,
4087 'user_touched' => $dbw->timestamp( $this->mTouched
),
4091 if ( !$dbw->affectedRows() ) {
4092 // Use locking reads to bypass any REPEATABLE-READ snapshot.
4093 $this->mId
= $dbw->selectField(
4096 [ 'user_name' => $this->mName
],
4098 [ 'LOCK IN SHARE MODE' ]
4102 if ( $this->loadFromDatabase( self
::READ_LOCKING
) ) {
4107 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
4108 "to insert user '{$this->mName}' row, but it was not present in select!" );
4110 return Status
::newFatal( 'userexists' );
4112 $this->mId
= $dbw->insertId();
4113 self
::$idCacheByName[$this->mName
] = $this->mId
;
4115 // Clear instance cache other than user table data, which is already accurate
4116 $this->clearInstanceCache();
4118 $this->saveOptions();
4119 return Status
::newGood();
4123 * If this user is logged-in and blocked,
4124 * block any IP address they've successfully logged in from.
4125 * @return bool A block was spread
4127 public function spreadAnyEditBlock() {
4128 if ( $this->isLoggedIn() && $this->isBlocked() ) {
4129 return $this->spreadBlock();
4136 * If this (non-anonymous) user is blocked,
4137 * block the IP address they've successfully logged in from.
4138 * @return bool A block was spread
4140 protected function spreadBlock() {
4141 wfDebug( __METHOD__
. "()\n" );
4143 if ( $this->mId
== 0 ) {
4147 $userblock = Block
::newFromTarget( $this->getName() );
4148 if ( !$userblock ) {
4152 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
4156 * Get whether the user is explicitly blocked from account creation.
4157 * @return bool|Block
4159 public function isBlockedFromCreateAccount() {
4160 $this->getBlockedStatus();
4161 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
4162 return $this->mBlock
;
4165 # bug 13611: if the IP address the user is trying to create an account from is
4166 # blocked with createaccount disabled, prevent new account creation there even
4167 # when the user is logged in
4168 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
4169 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
4171 return $this->mBlockedFromCreateAccount
instanceof Block
4172 && $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
4173 ?
$this->mBlockedFromCreateAccount
4178 * Get whether the user is blocked from using Special:Emailuser.
4181 public function isBlockedFromEmailuser() {
4182 $this->getBlockedStatus();
4183 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
4187 * Get whether the user is allowed to create an account.
4190 public function isAllowedToCreateAccount() {
4191 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
4195 * Get this user's personal page title.
4197 * @return Title User's personal page title
4199 public function getUserPage() {
4200 return Title
::makeTitle( NS_USER
, $this->getName() );
4204 * Get this user's talk page title.
4206 * @return Title User's talk page title
4208 public function getTalkPage() {
4209 $title = $this->getUserPage();
4210 return $title->getTalkPage();
4214 * Determine whether the user is a newbie. Newbies are either
4215 * anonymous IPs, or the most recently created accounts.
4218 public function isNewbie() {
4219 return !$this->isAllowed( 'autoconfirmed' );
4223 * Check to see if the given clear-text password is one of the accepted passwords
4224 * @deprecated since 1.27, use AuthManager instead
4225 * @param string $password User password
4226 * @return bool True if the given password is correct, otherwise False
4228 public function checkPassword( $password ) {
4229 $manager = AuthManager
::singleton();
4230 $reqs = AuthenticationRequest
::loadRequestsFromSubmission(
4231 $manager->getAuthenticationRequests( AuthManager
::ACTION_LOGIN
),
4233 'username' => $this->getName(),
4234 'password' => $password,
4237 $res = AuthManager
::singleton()->beginAuthentication( $reqs, 'null:' );
4238 switch ( $res->status
) {
4239 case AuthenticationResponse
::PASS
:
4241 case AuthenticationResponse
::FAIL
:
4242 // Hope it's not a PreAuthenticationProvider that failed...
4243 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
4244 ->info( __METHOD__
. ': Authentication failed: ' . $res->message
->plain() );
4247 throw new BadMethodCallException(
4248 'AuthManager returned a response unsupported by ' . __METHOD__
4254 * Check if the given clear-text password matches the temporary password
4255 * sent by e-mail for password reset operations.
4257 * @deprecated since 1.27, use AuthManager instead
4258 * @param string $plaintext
4259 * @return bool True if matches, false otherwise
4261 public function checkTemporaryPassword( $plaintext ) {
4262 // Can't check the temporary password individually.
4263 return $this->checkPassword( $plaintext );
4267 * Initialize (if necessary) and return a session token value
4268 * which can be used in edit forms to show that the user's
4269 * login credentials aren't being hijacked with a foreign form
4273 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4274 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4275 * @return MediaWiki\Session\Token The new edit token
4277 public function getEditTokenObject( $salt = '', $request = null ) {
4278 if ( $this->isAnon() ) {
4279 return new LoggedOutEditToken();
4283 $request = $this->getRequest();
4285 return $request->getSession()->getToken( $salt );
4289 * Initialize (if necessary) and return a session token value
4290 * which can be used in edit forms to show that the user's
4291 * login credentials aren't being hijacked with a foreign form
4294 * The $salt for 'edit' and 'csrf' tokens is the default (empty string).
4297 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4298 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4299 * @return string The new edit token
4301 public function getEditToken( $salt = '', $request = null ) {
4302 return $this->getEditTokenObject( $salt, $request )->toString();
4306 * Get the embedded timestamp from a token.
4307 * @deprecated since 1.27, use \MediaWiki\Session\Token::getTimestamp instead.
4308 * @param string $val Input token
4311 public static function getEditTokenTimestamp( $val ) {
4312 wfDeprecated( __METHOD__
, '1.27' );
4313 return MediaWiki\Session\Token
::getTimestamp( $val );
4317 * Check given value against the token value stored in the session.
4318 * A match should confirm that the form was submitted from the
4319 * user's own login session, not a form submission from a third-party
4322 * @param string $val Input value to compare
4323 * @param string $salt Optional function-specific data for hashing
4324 * @param WebRequest|null $request Object to use or null to use $wgRequest
4325 * @param int $maxage Fail tokens older than this, in seconds
4326 * @return bool Whether the token matches
4328 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4329 return $this->getEditTokenObject( $salt, $request )->match( $val, $maxage );
4333 * Check given value against the token value stored in the session,
4334 * ignoring the suffix.
4336 * @param string $val Input value to compare
4337 * @param string $salt Optional function-specific data for hashing
4338 * @param WebRequest|null $request Object to use or null to use $wgRequest
4339 * @param int $maxage Fail tokens older than this, in seconds
4340 * @return bool Whether the token matches
4342 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4343 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . Token
::SUFFIX
;
4344 return $this->matchEditToken( $val, $salt, $request, $maxage );
4348 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4349 * mail to the user's given address.
4351 * @param string $type Message to send, either "created", "changed" or "set"
4354 public function sendConfirmationMail( $type = 'created' ) {
4356 $expiration = null; // gets passed-by-ref and defined in next line.
4357 $token = $this->confirmationToken( $expiration );
4358 $url = $this->confirmationTokenUrl( $token );
4359 $invalidateURL = $this->invalidationTokenUrl( $token );
4360 $this->saveSettings();
4362 if ( $type == 'created' ||
$type === false ) {
4363 $message = 'confirmemail_body';
4364 } elseif ( $type === true ) {
4365 $message = 'confirmemail_body_changed';
4367 // Messages: confirmemail_body_changed, confirmemail_body_set
4368 $message = 'confirmemail_body_' . $type;
4371 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4372 wfMessage( $message,
4373 $this->getRequest()->getIP(),
4376 $wgLang->userTimeAndDate( $expiration, $this ),
4378 $wgLang->userDate( $expiration, $this ),
4379 $wgLang->userTime( $expiration, $this ) )->text() );
4383 * Send an e-mail to this user's account. Does not check for
4384 * confirmed status or validity.
4386 * @param string $subject Message subject
4387 * @param string $body Message body
4388 * @param User|null $from Optional sending user; if unspecified, default
4389 * $wgPasswordSender will be used.
4390 * @param string $replyto Reply-To address
4393 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4394 global $wgPasswordSender;
4396 if ( $from instanceof User
) {
4397 $sender = MailAddress
::newFromUser( $from );
4399 $sender = new MailAddress( $wgPasswordSender,
4400 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4402 $to = MailAddress
::newFromUser( $this );
4404 return UserMailer
::send( $to, $sender, $subject, $body, [
4405 'replyTo' => $replyto,
4410 * Generate, store, and return a new e-mail confirmation code.
4411 * A hash (unsalted, since it's used as a key) is stored.
4413 * @note Call saveSettings() after calling this function to commit
4414 * this change to the database.
4416 * @param string &$expiration Accepts the expiration time
4417 * @return string New token
4419 protected function confirmationToken( &$expiration ) {
4420 global $wgUserEmailConfirmationTokenExpiry;
4422 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4423 $expiration = wfTimestamp( TS_MW
, $expires );
4425 $token = MWCryptRand
::generateHex( 32 );
4426 $hash = md5( $token );
4427 $this->mEmailToken
= $hash;
4428 $this->mEmailTokenExpires
= $expiration;
4433 * Return a URL the user can use to confirm their email address.
4434 * @param string $token Accepts the email confirmation token
4435 * @return string New token URL
4437 protected function confirmationTokenUrl( $token ) {
4438 return $this->getTokenUrl( 'ConfirmEmail', $token );
4442 * Return a URL the user can use to invalidate their email address.
4443 * @param string $token Accepts the email confirmation token
4444 * @return string New token URL
4446 protected function invalidationTokenUrl( $token ) {
4447 return $this->getTokenUrl( 'InvalidateEmail', $token );
4451 * Internal function to format the e-mail validation/invalidation URLs.
4452 * This uses a quickie hack to use the
4453 * hardcoded English names of the Special: pages, for ASCII safety.
4455 * @note Since these URLs get dropped directly into emails, using the
4456 * short English names avoids insanely long URL-encoded links, which
4457 * also sometimes can get corrupted in some browsers/mailers
4458 * (bug 6957 with Gmail and Internet Explorer).
4460 * @param string $page Special page
4461 * @param string $token Token
4462 * @return string Formatted URL
4464 protected function getTokenUrl( $page, $token ) {
4465 // Hack to bypass localization of 'Special:'
4466 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4467 return $title->getCanonicalURL();
4471 * Mark the e-mail address confirmed.
4473 * @note Call saveSettings() after calling this function to commit the change.
4477 public function confirmEmail() {
4478 // Check if it's already confirmed, so we don't touch the database
4479 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4480 if ( !$this->isEmailConfirmed() ) {
4481 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4482 Hooks
::run( 'ConfirmEmailComplete', [ $this ] );
4488 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4489 * address if it was already confirmed.
4491 * @note Call saveSettings() after calling this function to commit the change.
4492 * @return bool Returns true
4494 public function invalidateEmail() {
4496 $this->mEmailToken
= null;
4497 $this->mEmailTokenExpires
= null;
4498 $this->setEmailAuthenticationTimestamp( null );
4500 Hooks
::run( 'InvalidateEmailComplete', [ $this ] );
4505 * Set the e-mail authentication timestamp.
4506 * @param string $timestamp TS_MW timestamp
4508 public function setEmailAuthenticationTimestamp( $timestamp ) {
4510 $this->mEmailAuthenticated
= $timestamp;
4511 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
4515 * Is this user allowed to send e-mails within limits of current
4516 * site configuration?
4519 public function canSendEmail() {
4520 global $wgEnableEmail, $wgEnableUserEmail;
4521 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4524 $canSend = $this->isEmailConfirmed();
4525 Hooks
::run( 'UserCanSendEmail', [ &$this, &$canSend ] );
4530 * Is this user allowed to receive e-mails within limits of current
4531 * site configuration?
4534 public function canReceiveEmail() {
4535 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4539 * Is this user's e-mail address valid-looking and confirmed within
4540 * limits of the current site configuration?
4542 * @note If $wgEmailAuthentication is on, this may require the user to have
4543 * confirmed their address by returning a code or using a password
4544 * sent to the address from the wiki.
4548 public function isEmailConfirmed() {
4549 global $wgEmailAuthentication;
4552 if ( Hooks
::run( 'EmailConfirmed', [ &$this, &$confirmed ] ) ) {
4553 if ( $this->isAnon() ) {
4556 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4559 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4569 * Check whether there is an outstanding request for e-mail confirmation.
4572 public function isEmailConfirmationPending() {
4573 global $wgEmailAuthentication;
4574 return $wgEmailAuthentication &&
4575 !$this->isEmailConfirmed() &&
4576 $this->mEmailToken
&&
4577 $this->mEmailTokenExpires
> wfTimestamp();
4581 * Get the timestamp of account creation.
4583 * @return string|bool|null Timestamp of account creation, false for
4584 * non-existent/anonymous user accounts, or null if existing account
4585 * but information is not in database.
4587 public function getRegistration() {
4588 if ( $this->isAnon() ) {
4592 return $this->mRegistration
;
4596 * Get the timestamp of the first edit
4598 * @return string|bool Timestamp of first edit, or false for
4599 * non-existent/anonymous user accounts.
4601 public function getFirstEditTimestamp() {
4602 if ( $this->getId() == 0 ) {
4603 return false; // anons
4605 $dbr = wfGetDB( DB_REPLICA
);
4606 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4607 [ 'rev_user' => $this->getId() ],
4609 [ 'ORDER BY' => 'rev_timestamp ASC' ]
4612 return false; // no edits
4614 return wfTimestamp( TS_MW
, $time );
4618 * Get the permissions associated with a given list of groups
4620 * @param array $groups Array of Strings List of internal group names
4621 * @return array Array of Strings List of permission key names for given groups combined
4623 public static function getGroupPermissions( $groups ) {
4624 global $wgGroupPermissions, $wgRevokePermissions;
4626 // grant every granted permission first
4627 foreach ( $groups as $group ) {
4628 if ( isset( $wgGroupPermissions[$group] ) ) {
4629 $rights = array_merge( $rights,
4630 // array_filter removes empty items
4631 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4634 // now revoke the revoked permissions
4635 foreach ( $groups as $group ) {
4636 if ( isset( $wgRevokePermissions[$group] ) ) {
4637 $rights = array_diff( $rights,
4638 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4641 return array_unique( $rights );
4645 * Get all the groups who have a given permission
4647 * @param string $role Role to check
4648 * @return array Array of Strings List of internal group names with the given permission
4650 public static function getGroupsWithPermission( $role ) {
4651 global $wgGroupPermissions;
4652 $allowedGroups = [];
4653 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4654 if ( self
::groupHasPermission( $group, $role ) ) {
4655 $allowedGroups[] = $group;
4658 return $allowedGroups;
4662 * Check, if the given group has the given permission
4664 * If you're wanting to check whether all users have a permission, use
4665 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4669 * @param string $group Group to check
4670 * @param string $role Role to check
4673 public static function groupHasPermission( $group, $role ) {
4674 global $wgGroupPermissions, $wgRevokePermissions;
4675 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4676 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4680 * Check if all users may be assumed to have the given permission
4682 * We generally assume so if the right is granted to '*' and isn't revoked
4683 * on any group. It doesn't attempt to take grants or other extension
4684 * limitations on rights into account in the general case, though, as that
4685 * would require it to always return false and defeat the purpose.
4686 * Specifically, session-based rights restrictions (such as OAuth or bot
4687 * passwords) are applied based on the current session.
4690 * @param string $right Right to check
4693 public static function isEveryoneAllowed( $right ) {
4694 global $wgGroupPermissions, $wgRevokePermissions;
4697 // Use the cached results, except in unit tests which rely on
4698 // being able change the permission mid-request
4699 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4700 return $cache[$right];
4703 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4704 $cache[$right] = false;
4708 // If it's revoked anywhere, then everyone doesn't have it
4709 foreach ( $wgRevokePermissions as $rights ) {
4710 if ( isset( $rights[$right] ) && $rights[$right] ) {
4711 $cache[$right] = false;
4716 // Remove any rights that aren't allowed to the global-session user,
4717 // unless there are no sessions for this endpoint.
4718 if ( !defined( 'MW_NO_SESSION' ) ) {
4719 $allowedRights = SessionManager
::getGlobalSession()->getAllowedUserRights();
4720 if ( $allowedRights !== null && !in_array( $right, $allowedRights, true ) ) {
4721 $cache[$right] = false;
4726 // Allow extensions to say false
4727 if ( !Hooks
::run( 'UserIsEveryoneAllowed', [ $right ] ) ) {
4728 $cache[$right] = false;
4732 $cache[$right] = true;
4737 * Get the localized descriptive name for a group, if it exists
4739 * @param string $group Internal group name
4740 * @return string Localized descriptive group name
4742 public static function getGroupName( $group ) {
4743 $msg = wfMessage( "group-$group" );
4744 return $msg->isBlank() ?
$group : $msg->text();
4748 * Get the localized descriptive name for a member of a group, if it exists
4750 * @param string $group Internal group name
4751 * @param string $username Username for gender (since 1.19)
4752 * @return string Localized name for group member
4754 public static function getGroupMember( $group, $username = '#' ) {
4755 $msg = wfMessage( "group-$group-member", $username );
4756 return $msg->isBlank() ?
$group : $msg->text();
4760 * Return the set of defined explicit groups.
4761 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4762 * are not included, as they are defined automatically, not in the database.
4763 * @return array Array of internal group names
4765 public static function getAllGroups() {
4766 global $wgGroupPermissions, $wgRevokePermissions;
4768 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4769 self
::getImplicitGroups()
4774 * Get a list of all available permissions.
4775 * @return string[] Array of permission names
4777 public static function getAllRights() {
4778 if ( self
::$mAllRights === false ) {
4779 global $wgAvailableRights;
4780 if ( count( $wgAvailableRights ) ) {
4781 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
4783 self
::$mAllRights = self
::$mCoreRights;
4785 Hooks
::run( 'UserGetAllRights', [ &self
::$mAllRights ] );
4787 return self
::$mAllRights;
4791 * Get a list of implicit groups
4792 * @return array Array of Strings Array of internal group names
4794 public static function getImplicitGroups() {
4795 global $wgImplicitGroups;
4797 $groups = $wgImplicitGroups;
4798 # Deprecated, use $wgImplicitGroups instead
4799 Hooks
::run( 'UserGetImplicitGroups', [ &$groups ], '1.25' );
4805 * Get the title of a page describing a particular group
4807 * @param string $group Internal group name
4808 * @return Title|bool Title of the page if it exists, false otherwise
4810 public static function getGroupPage( $group ) {
4811 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4812 if ( $msg->exists() ) {
4813 $title = Title
::newFromText( $msg->text() );
4814 if ( is_object( $title ) ) {
4822 * Create a link to the group in HTML, if available;
4823 * else return the group name.
4825 * @param string $group Internal name of the group
4826 * @param string $text The text of the link
4827 * @return string HTML link to the group
4829 public static function makeGroupLinkHTML( $group, $text = '' ) {
4830 if ( $text == '' ) {
4831 $text = self
::getGroupName( $group );
4833 $title = self
::getGroupPage( $group );
4835 return Linker
::link( $title, htmlspecialchars( $text ) );
4837 return htmlspecialchars( $text );
4842 * Create a link to the group in Wikitext, if available;
4843 * else return the group name.
4845 * @param string $group Internal name of the group
4846 * @param string $text The text of the link
4847 * @return string Wikilink to the group
4849 public static function makeGroupLinkWiki( $group, $text = '' ) {
4850 if ( $text == '' ) {
4851 $text = self
::getGroupName( $group );
4853 $title = self
::getGroupPage( $group );
4855 $page = $title->getFullText();
4856 return "[[$page|$text]]";
4863 * Returns an array of the groups that a particular group can add/remove.
4865 * @param string $group The group to check for whether it can add/remove
4866 * @return array Array( 'add' => array( addablegroups ),
4867 * 'remove' => array( removablegroups ),
4868 * 'add-self' => array( addablegroups to self),
4869 * 'remove-self' => array( removable groups from self) )
4871 public static function changeableByGroup( $group ) {
4872 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4881 if ( empty( $wgAddGroups[$group] ) ) {
4882 // Don't add anything to $groups
4883 } elseif ( $wgAddGroups[$group] === true ) {
4884 // You get everything
4885 $groups['add'] = self
::getAllGroups();
4886 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4887 $groups['add'] = $wgAddGroups[$group];
4890 // Same thing for remove
4891 if ( empty( $wgRemoveGroups[$group] ) ) {
4893 } elseif ( $wgRemoveGroups[$group] === true ) {
4894 $groups['remove'] = self
::getAllGroups();
4895 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4896 $groups['remove'] = $wgRemoveGroups[$group];
4899 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4900 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4901 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4902 if ( is_int( $key ) ) {
4903 $wgGroupsAddToSelf['user'][] = $value;
4908 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
4909 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4910 if ( is_int( $key ) ) {
4911 $wgGroupsRemoveFromSelf['user'][] = $value;
4916 // Now figure out what groups the user can add to him/herself
4917 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4919 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4920 // No idea WHY this would be used, but it's there
4921 $groups['add-self'] = User
::getAllGroups();
4922 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4923 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4926 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4928 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4929 $groups['remove-self'] = User
::getAllGroups();
4930 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4931 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4938 * Returns an array of groups that this user can add and remove
4939 * @return array Array( 'add' => array( addablegroups ),
4940 * 'remove' => array( removablegroups ),
4941 * 'add-self' => array( addablegroups to self),
4942 * 'remove-self' => array( removable groups from self) )
4944 public function changeableGroups() {
4945 if ( $this->isAllowed( 'userrights' ) ) {
4946 // This group gives the right to modify everything (reverse-
4947 // compatibility with old "userrights lets you change
4949 // Using array_merge to make the groups reindexed
4950 $all = array_merge( User
::getAllGroups() );
4959 // Okay, it's not so simple, we will have to go through the arrays
4966 $addergroups = $this->getEffectiveGroups();
4968 foreach ( $addergroups as $addergroup ) {
4969 $groups = array_merge_recursive(
4970 $groups, $this->changeableByGroup( $addergroup )
4972 $groups['add'] = array_unique( $groups['add'] );
4973 $groups['remove'] = array_unique( $groups['remove'] );
4974 $groups['add-self'] = array_unique( $groups['add-self'] );
4975 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4981 * Deferred version of incEditCountImmediate()
4983 public function incEditCount() {
4984 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle(
4986 $this->incEditCountImmediate();
4993 * Increment the user's edit-count field.
4994 * Will have no effect for anonymous users.
4997 public function incEditCountImmediate() {
4998 if ( $this->isAnon() ) {
5002 $dbw = wfGetDB( DB_MASTER
);
5003 // No rows will be "affected" if user_editcount is NULL
5006 [ 'user_editcount=user_editcount+1' ],
5007 [ 'user_id' => $this->getId(), 'user_editcount IS NOT NULL' ],
5010 // Lazy initialization check...
5011 if ( $dbw->affectedRows() == 0 ) {
5012 // Now here's a goddamn hack...
5013 $dbr = wfGetDB( DB_REPLICA
);
5014 if ( $dbr !== $dbw ) {
5015 // If we actually have a replica DB server, the count is
5016 // at least one behind because the current transaction
5017 // has not been committed and replicated.
5018 $this->mEditCount
= $this->initEditCount( 1 );
5020 // But if DB_REPLICA is selecting the master, then the
5021 // count we just read includes the revision that was
5022 // just added in the working transaction.
5023 $this->mEditCount
= $this->initEditCount();
5026 if ( $this->mEditCount
=== null ) {
5027 $this->getEditCount();
5028 $dbr = wfGetDB( DB_REPLICA
);
5029 $this->mEditCount +
= ( $dbr !== $dbw ) ?
1 : 0;
5031 $this->mEditCount++
;
5034 // Edit count in user cache too
5035 $this->invalidateCache();
5039 * Initialize user_editcount from data out of the revision table
5041 * @param int $add Edits to add to the count from the revision table
5042 * @return int Number of edits
5044 protected function initEditCount( $add = 0 ) {
5045 // Pull from a replica DB to be less cruel to servers
5046 // Accuracy isn't the point anyway here
5047 $dbr = wfGetDB( DB_REPLICA
);
5048 $count = (int)$dbr->selectField(
5051 [ 'rev_user' => $this->getId() ],
5054 $count = $count +
$add;
5056 $dbw = wfGetDB( DB_MASTER
);
5059 [ 'user_editcount' => $count ],
5060 [ 'user_id' => $this->getId() ],
5068 * Get the description of a given right
5070 * @param string $right Right to query
5071 * @return string Localized description of the right
5073 public static function getRightDescription( $right ) {
5074 $key = "right-$right";
5075 $msg = wfMessage( $key );
5076 return $msg->isBlank() ?
$right : $msg->text();
5080 * Make a new-style password hash
5082 * @param string $password Plain-text password
5083 * @param bool|string $salt Optional salt, may be random or the user ID.
5084 * If unspecified or false, will generate one automatically
5085 * @return string Password hash
5086 * @deprecated since 1.24, use Password class
5088 public static function crypt( $password, $salt = false ) {
5089 wfDeprecated( __METHOD__
, '1.24' );
5090 $passwordFactory = new PasswordFactory();
5091 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
5092 $hash = $passwordFactory->newFromPlaintext( $password );
5093 return $hash->toString();
5097 * Compare a password hash with a plain-text password. Requires the user
5098 * ID if there's a chance that the hash is an old-style hash.
5100 * @param string $hash Password hash
5101 * @param string $password Plain-text password to compare
5102 * @param string|bool $userId User ID for old-style password salt
5105 * @deprecated since 1.24, use Password class
5107 public static function comparePasswords( $hash, $password, $userId = false ) {
5108 wfDeprecated( __METHOD__
, '1.24' );
5110 // Check for *really* old password hashes that don't even have a type
5111 // The old hash format was just an md5 hex hash, with no type information
5112 if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) {
5113 global $wgPasswordSalt;
5114 if ( $wgPasswordSalt ) {
5115 $password = ":B:{$userId}:{$hash}";
5117 $password = ":A:{$hash}";
5121 $passwordFactory = new PasswordFactory();
5122 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
5123 $hash = $passwordFactory->newFromCiphertext( $hash );
5124 return $hash->equals( $password );
5128 * Add a newuser log entry for this user.
5129 * Before 1.19 the return value was always true.
5131 * @deprecated since 1.27, AuthManager handles logging
5132 * @param string|bool $action Account creation type.
5133 * - String, one of the following values:
5134 * - 'create' for an anonymous user creating an account for himself.
5135 * This will force the action's performer to be the created user itself,
5136 * no matter the value of $wgUser
5137 * - 'create2' for a logged in user creating an account for someone else
5138 * - 'byemail' when the created user will receive its password by e-mail
5139 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
5140 * - Boolean means whether the account was created by e-mail (deprecated):
5141 * - true will be converted to 'byemail'
5142 * - false will be converted to 'create' if this object is the same as
5143 * $wgUser and to 'create2' otherwise
5144 * @param string $reason User supplied reason
5147 public function addNewUserLogEntry( $action = false, $reason = '' ) {
5148 return true; // disabled
5152 * Add an autocreate newuser log entry for this user
5153 * Used by things like CentralAuth and perhaps other authplugins.
5154 * Consider calling addNewUserLogEntry() directly instead.
5156 * @deprecated since 1.27, AuthManager handles logging
5159 public function addNewUserLogEntryAutoCreate() {
5160 $this->addNewUserLogEntry( 'autocreate' );
5166 * Load the user options either from cache, the database or an array
5168 * @param array $data Rows for the current user out of the user_properties table
5170 protected function loadOptions( $data = null ) {
5175 if ( $this->mOptionsLoaded
) {
5179 $this->mOptions
= self
::getDefaultOptions();
5181 if ( !$this->getId() ) {
5182 // For unlogged-in users, load language/variant options from request.
5183 // There's no need to do it for logged-in users: they can set preferences,
5184 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5185 // so don't override user's choice (especially when the user chooses site default).
5186 $variant = $wgContLang->getDefaultVariant();
5187 $this->mOptions
['variant'] = $variant;
5188 $this->mOptions
['language'] = $variant;
5189 $this->mOptionsLoaded
= true;
5193 // Maybe load from the object
5194 if ( !is_null( $this->mOptionOverrides
) ) {
5195 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5196 foreach ( $this->mOptionOverrides
as $key => $value ) {
5197 $this->mOptions
[$key] = $value;
5200 if ( !is_array( $data ) ) {
5201 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5202 // Load from database
5203 $dbr = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
5204 ?
wfGetDB( DB_MASTER
)
5205 : wfGetDB( DB_REPLICA
);
5207 $res = $dbr->select(
5209 [ 'up_property', 'up_value' ],
5210 [ 'up_user' => $this->getId() ],
5214 $this->mOptionOverrides
= [];
5216 foreach ( $res as $row ) {
5217 $data[$row->up_property
] = $row->up_value
;
5220 foreach ( $data as $property => $value ) {
5221 $this->mOptionOverrides
[$property] = $value;
5222 $this->mOptions
[$property] = $value;
5226 $this->mOptionsLoaded
= true;
5228 Hooks
::run( 'UserLoadOptions', [ $this, &$this->mOptions
] );
5232 * Saves the non-default options for this user, as previously set e.g. via
5233 * setOption(), in the database's "user_properties" (preferences) table.
5234 * Usually used via saveSettings().
5236 protected function saveOptions() {
5237 $this->loadOptions();
5239 // Not using getOptions(), to keep hidden preferences in database
5240 $saveOptions = $this->mOptions
;
5242 // Allow hooks to abort, for instance to save to a global profile.
5243 // Reset options to default state before saving.
5244 if ( !Hooks
::run( 'UserSaveOptions', [ $this, &$saveOptions ] ) ) {
5248 $userId = $this->getId();
5250 $insert_rows = []; // all the new preference rows
5251 foreach ( $saveOptions as $key => $value ) {
5252 // Don't bother storing default values
5253 $defaultOption = self
::getDefaultOption( $key );
5254 if ( ( $defaultOption === null && $value !== false && $value !== null )
5255 ||
$value != $defaultOption
5258 'up_user' => $userId,
5259 'up_property' => $key,
5260 'up_value' => $value,
5265 $dbw = wfGetDB( DB_MASTER
);
5267 $res = $dbw->select( 'user_properties',
5268 [ 'up_property', 'up_value' ], [ 'up_user' => $userId ], __METHOD__
);
5270 // Find prior rows that need to be removed or updated. These rows will
5271 // all be deleted (the latter so that INSERT IGNORE applies the new values).
5273 foreach ( $res as $row ) {
5274 if ( !isset( $saveOptions[$row->up_property
] )
5275 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
5277 $keysDelete[] = $row->up_property
;
5281 if ( count( $keysDelete ) ) {
5282 // Do the DELETE by PRIMARY KEY for prior rows.
5283 // In the past a very large portion of calls to this function are for setting
5284 // 'rememberpassword' for new accounts (a preference that has since been removed).
5285 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5286 // caused gap locks on [max user ID,+infinity) which caused high contention since
5287 // updates would pile up on each other as they are for higher (newer) user IDs.
5288 // It might not be necessary these days, but it shouldn't hurt either.
5289 $dbw->delete( 'user_properties',
5290 [ 'up_user' => $userId, 'up_property' => $keysDelete ], __METHOD__
);
5292 // Insert the new preference rows
5293 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, [ 'IGNORE' ] );
5297 * Lazily instantiate and return a factory object for making passwords
5299 * @deprecated since 1.27, create a PasswordFactory directly instead
5300 * @return PasswordFactory
5302 public static function getPasswordFactory() {
5303 wfDeprecated( __METHOD__
, '1.27' );
5304 $ret = new PasswordFactory();
5305 $ret->init( RequestContext
::getMain()->getConfig() );
5310 * Provide an array of HTML5 attributes to put on an input element
5311 * intended for the user to enter a new password. This may include
5312 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
5314 * Do *not* use this when asking the user to enter his current password!
5315 * Regardless of configuration, users may have invalid passwords for whatever
5316 * reason (e.g., they were set before requirements were tightened up).
5317 * Only use it when asking for a new password, like on account creation or
5320 * Obviously, you still need to do server-side checking.
5322 * NOTE: A combination of bugs in various browsers means that this function
5323 * actually just returns array() unconditionally at the moment. May as
5324 * well keep it around for when the browser bugs get fixed, though.
5326 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
5328 * @deprecated since 1.27
5329 * @return array Array of HTML attributes suitable for feeding to
5330 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
5331 * That will get confused by the boolean attribute syntax used.)
5333 public static function passwordChangeInputAttribs() {
5334 global $wgMinimalPasswordLength;
5336 if ( $wgMinimalPasswordLength == 0 ) {
5340 # Note that the pattern requirement will always be satisfied if the
5341 # input is empty, so we need required in all cases.
5343 # @todo FIXME: Bug 23769: This needs to not claim the password is required
5344 # if e-mail confirmation is being used. Since HTML5 input validation
5345 # is b0rked anyway in some browsers, just return nothing. When it's
5346 # re-enabled, fix this code to not output required for e-mail
5348 # $ret = array( 'required' );
5351 # We can't actually do this right now, because Opera 9.6 will print out
5352 # the entered password visibly in its error message! When other
5353 # browsers add support for this attribute, or Opera fixes its support,
5354 # we can add support with a version check to avoid doing this on Opera
5355 # versions where it will be a problem. Reported to Opera as
5356 # DSK-262266, but they don't have a public bug tracker for us to follow.
5358 if ( $wgMinimalPasswordLength > 1 ) {
5359 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
5360 $ret['title'] = wfMessage( 'passwordtooshort' )
5361 ->numParams( $wgMinimalPasswordLength )->text();
5369 * Return the list of user fields that should be selected to create
5370 * a new user object.
5373 public static function selectFields() {
5381 'user_email_authenticated',
5383 'user_email_token_expires',
5384 'user_registration',
5390 * Factory function for fatal permission-denied errors
5393 * @param string $permission User right required
5396 static function newFatalPermissionDeniedStatus( $permission ) {
5399 $groups = array_map(
5400 [ 'User', 'makeGroupLinkWiki' ],
5401 User
::getGroupsWithPermission( $permission )
5405 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5407 return Status
::newFatal( 'badaccess-group0' );
5412 * Get a new instance of this user that was loaded from the master via a locking read
5414 * Use this instead of the main context User when updating that user. This avoids races
5415 * where that user was loaded from a replica DB or even the master but without proper locks.
5417 * @return User|null Returns null if the user was not found in the DB
5420 public function getInstanceForUpdate() {
5421 if ( !$this->getId() ) {
5422 return null; // anon
5425 $user = self
::newFromId( $this->getId() );
5426 if ( !$user->loadFromId( self
::READ_EXCLUSIVE
) ) {
5434 * Checks if two user objects point to the same user.
5440 public function equals( User
$user ) {
5441 return $this->getName() === $user->getName();