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
;
31 * String Some punctuation to prevent editing from broken text-mangling proxies.
32 * @deprecated since 1.27, use \MediaWiki\Session\Token::SUFFIX
35 define( 'EDIT_TOKEN_SUFFIX', Token
::SUFFIX
);
38 * The User object encapsulates all of the user-specific settings (user_id,
39 * name, rights, email address, options, last login time). Client
40 * classes use the getXXX() functions to access these fields. These functions
41 * do all the work of determining whether the user is logged in,
42 * whether the requested option can be satisfied from cookies or
43 * whether a database query is needed. Most of the settings needed
44 * for rendering normal pages are set in the cookie to minimize use
47 class User
implements IDBAccessObject
{
49 * @const int Number of characters in user_token field.
51 const TOKEN_LENGTH
= 32;
54 * @const string An invalid value for user_token
56 const INVALID_TOKEN
= '*** INVALID ***';
59 * Global constant made accessible as class constants so that autoloader
61 * @deprecated since 1.27, use \MediaWiki\Session\Token::SUFFIX
63 const EDIT_TOKEN_SUFFIX
= EDIT_TOKEN_SUFFIX
;
66 * @const int Serialized record version.
71 * Exclude user options that are set to their default value.
74 const GETOPTIONS_EXCLUDE_DEFAULTS
= 1;
79 const CHECK_USER_RIGHTS
= true;
84 const IGNORE_USER_RIGHTS
= false;
87 * Array of Strings List of member variables which are saved to the
88 * shared cache (memcached). Any operation which changes the
89 * corresponding database fields must call a cache-clearing function.
92 protected static $mCacheVars = [
100 'mEmailAuthenticated',
102 'mEmailTokenExpires',
107 // user_properties table
112 * Array of Strings Core rights.
113 * Each of these should have a corresponding message of the form
117 protected static $mCoreRights = [
148 'editusercssjs', # deprecated
161 'move-categorypages',
162 'move-rootuserpages',
166 'override-export-depth',
189 'userrights-interwiki',
197 * String Cached results of getAllRights()
199 protected static $mAllRights = false;
201 /** Cache variables */
212 /** @var string TS_MW timestamp from the DB */
214 /** @var string TS_MW timestamp from cache */
215 protected $mQuickTouched;
219 public $mEmailAuthenticated;
221 protected $mEmailToken;
223 protected $mEmailTokenExpires;
225 protected $mRegistration;
227 protected $mEditCount;
231 protected $mOptionOverrides;
235 * Bool Whether the cache variables have been loaded.
238 public $mOptionsLoaded;
241 * Array with already loaded items or true if all items have been loaded.
243 protected $mLoadedItems = [];
247 * String Initialization data source if mLoadedItems!==true. May be one of:
248 * - 'defaults' anonymous user initialised from class defaults
249 * - 'name' initialise from mName
250 * - 'id' initialise from mId
251 * - 'session' log in from session if possible
253 * Use the User::newFrom*() family of functions to set this.
258 * Lazy-initialized variables, invalidated with clearInstanceCache
262 protected $mDatePreference;
270 protected $mBlockreason;
272 protected $mEffectiveGroups;
274 protected $mImplicitGroups;
276 protected $mFormerGroups;
278 protected $mGlobalBlock;
295 protected $mAllowUsertalk;
298 private $mBlockedFromCreateAccount = false;
300 /** @var integer User::READ_* constant bitfield used to load data */
301 protected $queryFlagsUsed = self
::READ_NORMAL
;
303 public static $idCacheByName = [];
306 * Lightweight constructor for an anonymous user.
307 * Use the User::newFrom* factory functions for other kinds of users.
311 * @see newFromConfirmationCode()
312 * @see newFromSession()
315 public function __construct() {
316 $this->clearInstanceCache( 'defaults' );
322 public function __toString() {
323 return $this->getName();
327 * Test if it's safe to load this User object.
329 * You should typically check this before using $wgUser or
330 * RequestContext::getUser in a method that might be called before the
331 * system has been fully initialized. If the object is unsafe, you should
332 * use an anonymous user:
334 * $user = $wgUser->isSafeToLoad() ? $wgUser : new User;
340 public function isSafeToLoad() {
341 global $wgFullyInitialised;
343 // The user is safe to load if:
344 // * MW_NO_SESSION is undefined AND $wgFullyInitialised is true (safe to use session data)
345 // * mLoadedItems === true (already loaded)
346 // * mFrom !== 'session' (sessions not involved at all)
348 return ( !defined( 'MW_NO_SESSION' ) && $wgFullyInitialised ) ||
349 $this->mLoadedItems
=== true ||
$this->mFrom
!== 'session';
353 * Load the user table data for this object from the source given by mFrom.
355 * @param integer $flags User::READ_* constant bitfield
357 public function load( $flags = self
::READ_NORMAL
) {
358 global $wgFullyInitialised;
360 if ( $this->mLoadedItems
=== true ) {
364 // Set it now to avoid infinite recursion in accessors
365 $oldLoadedItems = $this->mLoadedItems
;
366 $this->mLoadedItems
= true;
367 $this->queryFlagsUsed
= $flags;
369 // If this is called too early, things are likely to break.
370 if ( !$wgFullyInitialised && $this->mFrom
=== 'session' ) {
371 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
372 ->warning( 'User::loadFromSession called before the end of Setup.php', [
373 'exception' => new Exception( 'User::loadFromSession called before the end of Setup.php' ),
375 $this->loadDefaults();
376 $this->mLoadedItems
= $oldLoadedItems;
380 switch ( $this->mFrom
) {
382 $this->loadDefaults();
385 // Make sure this thread sees its own changes
386 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
387 $flags |
= self
::READ_LATEST
;
388 $this->queryFlagsUsed
= $flags;
391 $this->mId
= self
::idFromName( $this->mName
, $flags );
393 // Nonexistent user placeholder object
394 $this->loadDefaults( $this->mName
);
396 $this->loadFromId( $flags );
400 $this->loadFromId( $flags );
403 if ( !$this->loadFromSession() ) {
404 // Loading from session failed. Load defaults.
405 $this->loadDefaults();
407 Hooks
::run( 'UserLoadAfterLoadFromSession', [ $this ] );
410 throw new UnexpectedValueException(
411 "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
416 * Load user table data, given mId has already been set.
417 * @param integer $flags User::READ_* constant bitfield
418 * @return bool False if the ID does not exist, true otherwise
420 public function loadFromId( $flags = self
::READ_NORMAL
) {
421 if ( $this->mId
== 0 ) {
422 // Anonymous users are not in the database (don't need cache)
423 $this->loadDefaults();
427 // Try cache (unless this needs data from the master DB).
428 // NOTE: if this thread called saveSettings(), the cache was cleared.
429 $latest = DBAccessObjectUtils
::hasFlags( $flags, self
::READ_LATEST
);
431 if ( !$this->loadFromDatabase( $flags ) ) {
432 // Can't load from ID
436 $this->loadFromCache();
439 $this->mLoadedItems
= true;
440 $this->queryFlagsUsed
= $flags;
447 * @param string $wikiId
448 * @param integer $userId
450 public static function purge( $wikiId, $userId ) {
451 $cache = ObjectCache
::getMainWANInstance();
452 $key = $cache->makeGlobalKey( 'user', 'id', $wikiId, $userId );
453 $cache->delete( $key );
458 * @param WANObjectCache $cache
461 protected function getCacheKey( WANObjectCache
$cache ) {
462 return $cache->makeGlobalKey( 'user', 'id', wfWikiID(), $this->mId
);
466 * Load user data from shared cache, given mId has already been set.
471 protected function loadFromCache() {
472 $cache = ObjectCache
::getMainWANInstance();
473 $data = $cache->getWithSetCallback(
474 $this->getCacheKey( $cache ),
476 function ( $oldValue, &$ttl, array &$setOpts ) {
477 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_SLAVE
) );
478 wfDebug( "User: cache miss for user {$this->mId}\n" );
480 $this->loadFromDatabase( self
::READ_NORMAL
);
482 $this->loadOptions();
485 foreach ( self
::$mCacheVars as $name ) {
486 $data[$name] = $this->$name;
492 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'version' => self
::VERSION
]
495 // Restore from cache
496 foreach ( self
::$mCacheVars as $name ) {
497 $this->$name = $data[$name];
503 /** @name newFrom*() static factory methods */
507 * Static factory method for creation from username.
509 * This is slightly less efficient than newFromId(), so use newFromId() if
510 * you have both an ID and a name handy.
512 * @param string $name Username, validated by Title::newFromText()
513 * @param string|bool $validate Validate username. Takes the same parameters as
514 * User::getCanonicalName(), except that true is accepted as an alias
515 * for 'valid', for BC.
517 * @return User|bool User object, or false if the username is invalid
518 * (e.g. if it contains illegal characters or is an IP address). If the
519 * username is not present in the database, the result will be a user object
520 * with a name, zero user ID and default settings.
522 public static function newFromName( $name, $validate = 'valid' ) {
523 if ( $validate === true ) {
526 $name = self
::getCanonicalName( $name, $validate );
527 if ( $name === false ) {
530 // Create unloaded user object
534 $u->setItemLoaded( 'name' );
540 * Static factory method for creation from a given user ID.
542 * @param int $id Valid user ID
543 * @return User The corresponding User object
545 public static function newFromId( $id ) {
549 $u->setItemLoaded( 'id' );
554 * Factory method to fetch whichever user has a given email confirmation code.
555 * This code is generated when an account is created or its e-mail address
558 * If the code is invalid or has expired, returns NULL.
560 * @param string $code Confirmation code
561 * @param int $flags User::READ_* bitfield
564 public static function newFromConfirmationCode( $code, $flags = 0 ) {
565 $db = ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
566 ?
wfGetDB( DB_MASTER
)
567 : wfGetDB( DB_SLAVE
);
569 $id = $db->selectField(
573 'user_email_token' => md5( $code ),
574 'user_email_token_expires > ' . $db->addQuotes( $db->timestamp() ),
578 return $id ? User
::newFromId( $id ) : null;
582 * Create a new user object using data from session. If the login
583 * credentials are invalid, the result is an anonymous user.
585 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
588 public static function newFromSession( WebRequest
$request = null ) {
590 $user->mFrom
= 'session';
591 $user->mRequest
= $request;
596 * Create a new user object from a user row.
597 * The row should have the following fields from the user table in it:
598 * - either user_name or user_id to load further data if needed (or both)
600 * - all other fields (email, etc.)
601 * It is useless to provide the remaining fields if either user_id,
602 * user_name and user_real_name are not provided because the whole row
603 * will be loaded once more from the database when accessing them.
605 * @param stdClass $row A row from the user table
606 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
609 public static function newFromRow( $row, $data = null ) {
611 $user->loadFromRow( $row, $data );
616 * Static factory method for creation of a "system" user from username.
618 * A "system" user is an account that's used to attribute logged actions
619 * taken by MediaWiki itself, as opposed to a bot or human user. Examples
620 * might include the 'Maintenance script' or 'Conversion script' accounts
621 * used by various scripts in the maintenance/ directory or accounts such
622 * as 'MediaWiki message delivery' used by the MassMessage extension.
624 * This can optionally create the user if it doesn't exist, and "steal" the
625 * account if it does exist.
627 * "Stealing" an existing user is intended to make it impossible for normal
628 * authentication processes to use the account, effectively disabling the
629 * account for normal use:
630 * - Email is invalidated, to prevent account recovery by emailing a
631 * temporary password and to disassociate the account from the existing
633 * - The token is set to a magic invalid value, to kill existing sessions
634 * and to prevent $this->setToken() calls from resetting the token to a
636 * - SessionManager is instructed to prevent new sessions for the user, to
637 * do things like deauthorizing OAuth consumers.
638 * - AuthManager is instructed to revoke access, to invalidate or remove
639 * passwords and other credentials.
641 * @param string $name Username
642 * @param array $options Options are:
643 * - validate: As for User::getCanonicalName(), default 'valid'
644 * - create: Whether to create the user if it doesn't already exist, default true
645 * - steal: Whether to "disable" the account for normal use if it already
646 * exists, default false
650 public static function newSystemUser( $name, $options = [] ) {
651 global $wgDisableAuthManager;
654 'validate' => 'valid',
659 $name = self
::getCanonicalName( $name, $options['validate'] );
660 if ( $name === false ) {
664 $fields = self
::selectFields();
665 if ( $wgDisableAuthManager ) {
666 $fields = array_merge( $fields, [ 'user_password', 'user_newpassword' ] );
669 $dbw = wfGetDB( DB_MASTER
);
670 $row = $dbw->selectRow(
673 [ 'user_name' => $name ],
677 // No user. Create it?
678 return $options['create'] ? self
::createNew( $name ) : null;
680 $user = self
::newFromRow( $row );
682 // A user is considered to exist as a non-system user if it can
683 // authenticate, or has an email set, or has a non-invalid token.
684 if ( !$user->mEmail
&& $user->mToken
=== self
::INVALID_TOKEN
) {
685 if ( $wgDisableAuthManager ) {
686 $passwordFactory = new PasswordFactory();
687 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
689 $password = $passwordFactory->newFromCiphertext( $row->user_password
);
690 } catch ( PasswordError
$e ) {
691 wfDebug( 'Invalid password hash found in database.' );
692 $password = PasswordFactory
::newInvalidPassword();
695 $newpassword = $passwordFactory->newFromCiphertext( $row->user_newpassword
);
696 } catch ( PasswordError
$e ) {
697 wfDebug( 'Invalid password hash found in database.' );
698 $newpassword = PasswordFactory
::newInvalidPassword();
700 $canAuthenticate = !$password instanceof InvalidPassword ||
701 !$newpassword instanceof InvalidPassword
;
703 $canAuthenticate = AuthManager
::singleton()->userCanAuthenticate( $name );
706 if ( $user->mEmail ||
$user->mToken
!== self
::INVALID_TOKEN ||
$canAuthenticate ) {
707 // User exists. Steal it?
708 if ( !$options['steal'] ) {
712 if ( $wgDisableAuthManager ) {
713 $nopass = PasswordFactory
::newInvalidPassword()->toString();
717 'user_password' => $nopass,
718 'user_newpassword' => $nopass,
719 'user_newpass_time' => null,
721 [ 'user_id' => $user->getId() ],
725 AuthManager
::singleton()->revokeAccessForUser( $name );
728 $user->invalidateEmail();
729 $user->mToken
= self
::INVALID_TOKEN
;
730 $user->saveSettings();
731 SessionManager
::singleton()->preventSessionsForUser( $user->getName() );
740 * Get the username corresponding to a given user ID
741 * @param int $id User ID
742 * @return string|bool The corresponding username
744 public static function whoIs( $id ) {
745 return UserCache
::singleton()->getProp( $id, 'name' );
749 * Get the real name of a user given their user ID
751 * @param int $id User ID
752 * @return string|bool The corresponding user's real name
754 public static function whoIsReal( $id ) {
755 return UserCache
::singleton()->getProp( $id, 'real_name' );
759 * Get database id given a user name
760 * @param string $name Username
761 * @param integer $flags User::READ_* constant bitfield
762 * @return int|null The corresponding user's ID, or null if user is nonexistent
764 public static function idFromName( $name, $flags = self
::READ_NORMAL
) {
765 $nt = Title
::makeTitleSafe( NS_USER
, $name );
766 if ( is_null( $nt ) ) {
771 if ( !( $flags & self
::READ_LATEST
) && isset( self
::$idCacheByName[$name] ) ) {
772 return self
::$idCacheByName[$name];
775 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
776 $db = wfGetDB( $index );
781 [ 'user_name' => $nt->getText() ],
786 if ( $s === false ) {
789 $result = $s->user_id
;
792 self
::$idCacheByName[$name] = $result;
794 if ( count( self
::$idCacheByName ) > 1000 ) {
795 self
::$idCacheByName = [];
802 * Reset the cache used in idFromName(). For use in tests.
804 public static function resetIdByNameCache() {
805 self
::$idCacheByName = [];
809 * Does the string match an anonymous IP address?
811 * This function exists for username validation, in order to reject
812 * usernames which are similar in form to IP addresses. Strings such
813 * as 300.300.300.300 will return true because it looks like an IP
814 * address, despite not being strictly valid.
816 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
817 * address because the usemod software would "cloak" anonymous IP
818 * addresses like this, if we allowed accounts like this to be created
819 * new users could get the old edits of these anonymous users.
821 * @param string $name Name to match
824 public static function isIP( $name ) {
825 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
826 || IP
::isIPv6( $name );
830 * Is the input a valid username?
832 * Checks if the input is a valid username, we don't want an empty string,
833 * an IP address, anything that contains slashes (would mess up subpages),
834 * is longer than the maximum allowed username size or doesn't begin with
837 * @param string $name Name to match
840 public static function isValidUserName( $name ) {
841 global $wgContLang, $wgMaxNameChars;
844 || User
::isIP( $name )
845 ||
strpos( $name, '/' ) !== false
846 ||
strlen( $name ) > $wgMaxNameChars
847 ||
$name != $wgContLang->ucfirst( $name )
852 // Ensure that the name can't be misresolved as a different title,
853 // such as with extra namespace keys at the start.
854 $parsed = Title
::newFromText( $name );
855 if ( is_null( $parsed )
856 ||
$parsed->getNamespace()
857 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
861 // Check an additional blacklist of troublemaker characters.
862 // Should these be merged into the title char list?
863 $unicodeBlacklist = '/[' .
864 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
865 '\x{00a0}' . # non-breaking space
866 '\x{2000}-\x{200f}' . # various whitespace
867 '\x{2028}-\x{202f}' . # breaks and control chars
868 '\x{3000}' . # ideographic space
869 '\x{e000}-\x{f8ff}' . # private use
871 if ( preg_match( $unicodeBlacklist, $name ) ) {
879 * Usernames which fail to pass this function will be blocked
880 * from user login and new account registrations, but may be used
881 * internally by batch processes.
883 * If an account already exists in this form, login will be blocked
884 * by a failure to pass this function.
886 * @param string $name Name to match
889 public static function isUsableName( $name ) {
890 global $wgReservedUsernames;
891 // Must be a valid username, obviously ;)
892 if ( !self
::isValidUserName( $name ) ) {
896 static $reservedUsernames = false;
897 if ( !$reservedUsernames ) {
898 $reservedUsernames = $wgReservedUsernames;
899 Hooks
::run( 'UserGetReservedNames', [ &$reservedUsernames ] );
902 // Certain names may be reserved for batch processes.
903 foreach ( $reservedUsernames as $reserved ) {
904 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
905 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
907 if ( $reserved == $name ) {
915 * Usernames which fail to pass this function will be blocked
916 * from new account registrations, but may be used internally
917 * either by batch processes or by user accounts which have
918 * already been created.
920 * Additional blacklisting may be added here rather than in
921 * isValidUserName() to avoid disrupting existing accounts.
923 * @param string $name String to match
926 public static function isCreatableName( $name ) {
927 global $wgInvalidUsernameCharacters;
929 // Ensure that the username isn't longer than 235 bytes, so that
930 // (at least for the builtin skins) user javascript and css files
931 // will work. (bug 23080)
932 if ( strlen( $name ) > 235 ) {
933 wfDebugLog( 'username', __METHOD__
.
934 ": '$name' invalid due to length" );
938 // Preg yells if you try to give it an empty string
939 if ( $wgInvalidUsernameCharacters !== '' ) {
940 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
941 wfDebugLog( 'username', __METHOD__
.
942 ": '$name' invalid due to wgInvalidUsernameCharacters" );
947 return self
::isUsableName( $name );
951 * Is the input a valid password for this user?
953 * @param string $password Desired password
956 public function isValidPassword( $password ) {
957 // simple boolean wrapper for getPasswordValidity
958 return $this->getPasswordValidity( $password ) === true;
962 * Given unvalidated password input, return error message on failure.
964 * @param string $password Desired password
965 * @return bool|string|array True on success, string or array of error message on failure
967 public function getPasswordValidity( $password ) {
968 $result = $this->checkPasswordValidity( $password );
969 if ( $result->isGood() ) {
973 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
974 $messages[] = $error['message'];
976 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
977 $messages[] = $warning['message'];
979 if ( count( $messages ) === 1 ) {
987 * Check if this is a valid password for this user
989 * Create a Status object based on the password's validity.
990 * The Status should be set to fatal if the user should not
991 * be allowed to log in, and should have any errors that
992 * would block changing the password.
994 * If the return value of this is not OK, the password
995 * should not be checked. If the return value is not Good,
996 * the password can be checked, but the user should not be
997 * able to set their password to this.
999 * @param string $password Desired password
1000 * @param string $purpose one of 'login', 'create', 'reset'
1004 public function checkPasswordValidity( $password, $purpose = 'login' ) {
1005 global $wgPasswordPolicy;
1007 $upp = new UserPasswordPolicy(
1008 $wgPasswordPolicy['policies'],
1009 $wgPasswordPolicy['checks']
1012 $status = Status
::newGood();
1013 $result = false; // init $result to false for the internal checks
1015 if ( !Hooks
::run( 'isValidPassword', [ $password, &$result, $this ] ) ) {
1016 $status->error( $result );
1020 if ( $result === false ) {
1021 $status->merge( $upp->checkUserPassword( $this, $password, $purpose ) );
1023 } elseif ( $result === true ) {
1026 $status->error( $result );
1027 return $status; // the isValidPassword hook set a string $result and returned true
1032 * Given unvalidated user input, return a canonical username, or false if
1033 * the username is invalid.
1034 * @param string $name User input
1035 * @param string|bool $validate Type of validation to use:
1036 * - false No validation
1037 * - 'valid' Valid for batch processes
1038 * - 'usable' Valid for batch processes and login
1039 * - 'creatable' Valid for batch processes, login and account creation
1041 * @throws InvalidArgumentException
1042 * @return bool|string
1044 public static function getCanonicalName( $name, $validate = 'valid' ) {
1045 // Force usernames to capital
1047 $name = $wgContLang->ucfirst( $name );
1049 # Reject names containing '#'; these will be cleaned up
1050 # with title normalisation, but then it's too late to
1052 if ( strpos( $name, '#' ) !== false ) {
1056 // Clean up name according to title rules,
1057 // but only when validation is requested (bug 12654)
1058 $t = ( $validate !== false ) ?
1059 Title
::newFromText( $name, NS_USER
) : Title
::makeTitle( NS_USER
, $name );
1060 // Check for invalid titles
1061 if ( is_null( $t ) ||
$t->getNamespace() !== NS_USER ||
$t->isExternal() ) {
1065 // Reject various classes of invalid names
1066 $name = AuthManager
::callLegacyAuthPlugin(
1067 'getCanonicalName', [ $t->getText() ], $t->getText()
1070 switch ( $validate ) {
1074 if ( !User
::isValidUserName( $name ) ) {
1079 if ( !User
::isUsableName( $name ) ) {
1084 if ( !User
::isCreatableName( $name ) ) {
1089 throw new InvalidArgumentException(
1090 'Invalid parameter value for $validate in ' . __METHOD__
);
1096 * Count the number of edits of a user
1098 * @param int $uid User ID to check
1099 * @return int The user's edit count
1101 * @deprecated since 1.21 in favour of User::getEditCount
1103 public static function edits( $uid ) {
1104 wfDeprecated( __METHOD__
, '1.21' );
1105 $user = self
::newFromId( $uid );
1106 return $user->getEditCount();
1110 * Return a random password.
1112 * @deprecated since 1.27, use PasswordFactory::generateRandomPasswordString()
1113 * @return string New random password
1115 public static function randomPassword() {
1116 global $wgMinimalPasswordLength;
1117 return PasswordFactory
::generateRandomPasswordString( $wgMinimalPasswordLength );
1121 * Set cached properties to default.
1123 * @note This no longer clears uncached lazy-initialised properties;
1124 * the constructor does that instead.
1126 * @param string|bool $name
1128 public function loadDefaults( $name = false ) {
1130 $this->mName
= $name;
1131 $this->mRealName
= '';
1133 $this->mOptionOverrides
= null;
1134 $this->mOptionsLoaded
= false;
1136 $loggedOut = $this->mRequest
&& !defined( 'MW_NO_SESSION' )
1137 ?
$this->mRequest
->getSession()->getLoggedOutTimestamp() : 0;
1138 if ( $loggedOut !== 0 ) {
1139 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1141 $this->mTouched
= '1'; # Allow any pages to be cached
1144 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1145 $this->mEmailAuthenticated
= null;
1146 $this->mEmailToken
= '';
1147 $this->mEmailTokenExpires
= null;
1148 $this->mRegistration
= wfTimestamp( TS_MW
);
1149 $this->mGroups
= [];
1151 Hooks
::run( 'UserLoadDefaults', [ $this, $name ] );
1155 * Return whether an item has been loaded.
1157 * @param string $item Item to check. Current possibilities:
1161 * @param string $all 'all' to check if the whole object has been loaded
1162 * or any other string to check if only the item is available (e.g.
1166 public function isItemLoaded( $item, $all = 'all' ) {
1167 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1168 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1172 * Set that an item has been loaded
1174 * @param string $item
1176 protected function setItemLoaded( $item ) {
1177 if ( is_array( $this->mLoadedItems
) ) {
1178 $this->mLoadedItems
[$item] = true;
1183 * Load user data from the session.
1185 * @return bool True if the user is logged in, false otherwise.
1187 private function loadFromSession() {
1190 Hooks
::run( 'UserLoadFromSession', [ $this, &$result ], '1.27' );
1191 if ( $result !== null ) {
1195 // MediaWiki\Session\Session already did the necessary authentication of the user
1196 // returned here, so just use it if applicable.
1197 $session = $this->getRequest()->getSession();
1198 $user = $session->getUser();
1199 if ( $user->isLoggedIn() ) {
1200 $this->loadFromUserObject( $user );
1201 // Other code expects these to be set in the session, so set them.
1202 $session->set( 'wsUserID', $this->getId() );
1203 $session->set( 'wsUserName', $this->getName() );
1204 $session->set( 'wsToken', $this->getToken() );
1212 * Load user and user_group data from the database.
1213 * $this->mId must be set, this is how the user is identified.
1215 * @param integer $flags User::READ_* constant bitfield
1216 * @return bool True if the user exists, false if the user is anonymous
1218 public function loadFromDatabase( $flags = self
::READ_LATEST
) {
1220 $this->mId
= intval( $this->mId
);
1222 if ( !$this->mId
) {
1223 // Anonymous users are not in the database
1224 $this->loadDefaults();
1228 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
1229 $db = wfGetDB( $index );
1231 $s = $db->selectRow(
1233 self
::selectFields(),
1234 [ 'user_id' => $this->mId
],
1239 $this->queryFlagsUsed
= $flags;
1240 Hooks
::run( 'UserLoadFromDatabase', [ $this, &$s ] );
1242 if ( $s !== false ) {
1243 // Initialise user table data
1244 $this->loadFromRow( $s );
1245 $this->mGroups
= null; // deferred
1246 $this->getEditCount(); // revalidation for nulls
1251 $this->loadDefaults();
1257 * Initialize this object from a row from the user table.
1259 * @param stdClass $row Row from the user table to load.
1260 * @param array $data Further user data to load into the object
1262 * user_groups Array with groups out of the user_groups table
1263 * user_properties Array with properties out of the user_properties table
1265 protected function loadFromRow( $row, $data = null ) {
1268 $this->mGroups
= null; // deferred
1270 if ( isset( $row->user_name
) ) {
1271 $this->mName
= $row->user_name
;
1272 $this->mFrom
= 'name';
1273 $this->setItemLoaded( 'name' );
1278 if ( isset( $row->user_real_name
) ) {
1279 $this->mRealName
= $row->user_real_name
;
1280 $this->setItemLoaded( 'realname' );
1285 if ( isset( $row->user_id
) ) {
1286 $this->mId
= intval( $row->user_id
);
1287 $this->mFrom
= 'id';
1288 $this->setItemLoaded( 'id' );
1293 if ( isset( $row->user_id
) && isset( $row->user_name
) ) {
1294 self
::$idCacheByName[$row->user_name
] = $row->user_id
;
1297 if ( isset( $row->user_editcount
) ) {
1298 $this->mEditCount
= $row->user_editcount
;
1303 if ( isset( $row->user_touched
) ) {
1304 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1309 if ( isset( $row->user_token
) ) {
1310 // The definition for the column is binary(32), so trim the NULs
1311 // that appends. The previous definition was char(32), so trim
1313 $this->mToken
= rtrim( $row->user_token
, " \0" );
1314 if ( $this->mToken
=== '' ) {
1315 $this->mToken
= null;
1321 if ( isset( $row->user_email
) ) {
1322 $this->mEmail
= $row->user_email
;
1323 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1324 $this->mEmailToken
= $row->user_email_token
;
1325 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1326 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1332 $this->mLoadedItems
= true;
1335 if ( is_array( $data ) ) {
1336 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1337 $this->mGroups
= $data['user_groups'];
1339 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1340 $this->loadOptions( $data['user_properties'] );
1346 * Load the data for this user object from another user object.
1350 protected function loadFromUserObject( $user ) {
1352 $user->loadGroups();
1353 $user->loadOptions();
1354 foreach ( self
::$mCacheVars as $var ) {
1355 $this->$var = $user->$var;
1360 * Load the groups from the database if they aren't already loaded.
1362 private function loadGroups() {
1363 if ( is_null( $this->mGroups
) ) {
1364 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
1365 ?
wfGetDB( DB_MASTER
)
1366 : wfGetDB( DB_SLAVE
);
1367 $res = $db->select( 'user_groups',
1369 [ 'ug_user' => $this->mId
],
1371 $this->mGroups
= [];
1372 foreach ( $res as $row ) {
1373 $this->mGroups
[] = $row->ug_group
;
1379 * Add the user to the group if he/she meets given criteria.
1381 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1382 * possible to remove manually via Special:UserRights. In such case it
1383 * will not be re-added automatically. The user will also not lose the
1384 * group if they no longer meet the criteria.
1386 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1388 * @return array Array of groups the user has been promoted to.
1390 * @see $wgAutopromoteOnce
1392 public function addAutopromoteOnceGroups( $event ) {
1393 global $wgAutopromoteOnceLogInRC;
1395 if ( wfReadOnly() ||
!$this->getId() ) {
1399 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1400 if ( !count( $toPromote ) ) {
1404 if ( !$this->checkAndSetTouched() ) {
1405 return []; // raced out (bug T48834)
1408 $oldGroups = $this->getGroups(); // previous groups
1409 foreach ( $toPromote as $group ) {
1410 $this->addGroup( $group );
1412 // update groups in external authentication database
1413 Hooks
::run( 'UserGroupsChanged', [ $this, $toPromote, [], false, false ] );
1414 AuthManager
::callLegacyAuthPlugin( 'updateExternalDBGroups', [ $this, $toPromote ] );
1416 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1418 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1419 $logEntry->setPerformer( $this );
1420 $logEntry->setTarget( $this->getUserPage() );
1421 $logEntry->setParameters( [
1422 '4::oldgroups' => $oldGroups,
1423 '5::newgroups' => $newGroups,
1425 $logid = $logEntry->insert();
1426 if ( $wgAutopromoteOnceLogInRC ) {
1427 $logEntry->publish( $logid );
1434 * Builds update conditions. Additional conditions may be added to $conditions to
1435 * protected against race conditions using a compare-and-set (CAS) mechanism
1436 * based on comparing $this->mTouched with the user_touched field.
1438 * @param DatabaseBase $db
1439 * @param array $conditions WHERE conditions for use with DatabaseBase::update
1440 * @return array WHERE conditions for use with DatabaseBase::update
1442 protected function makeUpdateConditions( DatabaseBase
$db, array $conditions ) {
1443 if ( $this->mTouched
) {
1444 // CAS check: only update if the row wasn't changed sicne it was loaded.
1445 $conditions['user_touched'] = $db->timestamp( $this->mTouched
);
1452 * Bump user_touched if it didn't change since this object was loaded
1454 * On success, the mTouched field is updated.
1455 * The user serialization cache is always cleared.
1457 * @return bool Whether user_touched was actually updated
1460 protected function checkAndSetTouched() {
1463 if ( !$this->mId
) {
1464 return false; // anon
1467 // Get a new user_touched that is higher than the old one
1468 $newTouched = $this->newTouchedTimestamp();
1470 $dbw = wfGetDB( DB_MASTER
);
1471 $dbw->update( 'user',
1472 [ 'user_touched' => $dbw->timestamp( $newTouched ) ],
1473 $this->makeUpdateConditions( $dbw, [
1474 'user_id' => $this->mId
,
1478 $success = ( $dbw->affectedRows() > 0 );
1481 $this->mTouched
= $newTouched;
1482 $this->clearSharedCache();
1484 // Clears on failure too since that is desired if the cache is stale
1485 $this->clearSharedCache( 'refresh' );
1492 * Clear various cached data stored in this object. The cache of the user table
1493 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1495 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1496 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1498 public function clearInstanceCache( $reloadFrom = false ) {
1499 $this->mNewtalk
= -1;
1500 $this->mDatePreference
= null;
1501 $this->mBlockedby
= -1; # Unset
1502 $this->mHash
= false;
1503 $this->mRights
= null;
1504 $this->mEffectiveGroups
= null;
1505 $this->mImplicitGroups
= null;
1506 $this->mGroups
= null;
1507 $this->mOptions
= null;
1508 $this->mOptionsLoaded
= false;
1509 $this->mEditCount
= null;
1511 if ( $reloadFrom ) {
1512 $this->mLoadedItems
= [];
1513 $this->mFrom
= $reloadFrom;
1518 * Combine the language default options with any site-specific options
1519 * and add the default language variants.
1521 * @return array Array of String options
1523 public static function getDefaultOptions() {
1524 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1526 static $defOpt = null;
1527 static $defOptLang = null;
1529 if ( $defOpt !== null && $defOptLang === $wgContLang->getCode() ) {
1530 // $wgContLang does not change (and should not change) mid-request,
1531 // but the unit tests change it anyway, and expect this method to
1532 // return values relevant to the current $wgContLang.
1536 $defOpt = $wgDefaultUserOptions;
1537 // Default language setting
1538 $defOptLang = $wgContLang->getCode();
1539 $defOpt['language'] = $defOptLang;
1540 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1541 $defOpt[$langCode == $wgContLang->getCode() ?
'variant' : "variant-$langCode"] = $langCode;
1543 $namespaces = MediaWikiServices
::getInstance()->getSearchEngineConfig()->searchableNamespaces();
1544 foreach ( $namespaces as $nsnum => $nsname ) {
1545 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1547 $defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1549 Hooks
::run( 'UserGetDefaultOptions', [ &$defOpt ] );
1555 * Get a given default option value.
1557 * @param string $opt Name of option to retrieve
1558 * @return string Default option value
1560 public static function getDefaultOption( $opt ) {
1561 $defOpts = self
::getDefaultOptions();
1562 if ( isset( $defOpts[$opt] ) ) {
1563 return $defOpts[$opt];
1570 * Get blocking information
1571 * @param bool $bFromSlave Whether to check the slave database first.
1572 * To improve performance, non-critical checks are done against slaves.
1573 * Check when actually saving should be done against master.
1575 private function getBlockedStatus( $bFromSlave = true ) {
1576 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1578 if ( -1 != $this->mBlockedby
) {
1582 wfDebug( __METHOD__
. ": checking...\n" );
1584 // Initialize data...
1585 // Otherwise something ends up stomping on $this->mBlockedby when
1586 // things get lazy-loaded later, causing false positive block hits
1587 // due to -1 !== 0. Probably session-related... Nothing should be
1588 // overwriting mBlockedby, surely?
1591 # We only need to worry about passing the IP address to the Block generator if the
1592 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1593 # know which IP address they're actually coming from
1595 if ( !$this->isAllowed( 'ipblock-exempt' ) ) {
1596 // $wgUser->getName() only works after the end of Setup.php. Until
1597 // then, assume it's a logged-out user.
1598 $globalUserName = $wgUser->isSafeToLoad()
1599 ?
$wgUser->getName()
1600 : IP
::sanitizeIP( $wgUser->getRequest()->getIP() );
1601 if ( $this->getName() === $globalUserName ) {
1602 $ip = $this->getRequest()->getIP();
1607 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1610 if ( !$block instanceof Block
&& $ip !== null && !in_array( $ip, $wgProxyWhitelist ) ) {
1612 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1614 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1615 $block->mReason
= wfMessage( 'proxyblockreason' )->text();
1616 $block->setTarget( $ip );
1617 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1619 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1620 $block->mReason
= wfMessage( 'sorbsreason' )->text();
1621 $block->setTarget( $ip );
1625 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1626 if ( !$block instanceof Block
1627 && $wgApplyIpBlocksToXff
1629 && !in_array( $ip, $wgProxyWhitelist )
1631 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1632 $xff = array_map( 'trim', explode( ',', $xff ) );
1633 $xff = array_diff( $xff, [ $ip ] );
1634 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1635 $block = Block
::chooseBlock( $xffblocks, $xff );
1636 if ( $block instanceof Block
) {
1637 # Mangle the reason to alert the user that the block
1638 # originated from matching the X-Forwarded-For header.
1639 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->text();
1643 if ( $block instanceof Block
) {
1644 wfDebug( __METHOD__
. ": Found block.\n" );
1645 $this->mBlock
= $block;
1646 $this->mBlockedby
= $block->getByName();
1647 $this->mBlockreason
= $block->mReason
;
1648 $this->mHideName
= $block->mHideName
;
1649 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1651 $this->mBlockedby
= '';
1652 $this->mHideName
= 0;
1653 $this->mAllowUsertalk
= false;
1657 Hooks
::run( 'GetBlockedStatus', [ &$this ] );
1662 * Whether the given IP is in a DNS blacklist.
1664 * @param string $ip IP to check
1665 * @param bool $checkWhitelist Whether to check the whitelist first
1666 * @return bool True if blacklisted.
1668 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1669 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1671 if ( !$wgEnableDnsBlacklist ) {
1675 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1679 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1683 * Whether the given IP is in a given DNS blacklist.
1685 * @param string $ip IP to check
1686 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1687 * @return bool True if blacklisted.
1689 public function inDnsBlacklist( $ip, $bases ) {
1692 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1693 if ( IP
::isIPv4( $ip ) ) {
1694 // Reverse IP, bug 21255
1695 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1697 foreach ( (array)$bases as $base ) {
1699 // If we have an access key, use that too (ProjectHoneypot, etc.)
1701 if ( is_array( $base ) ) {
1702 if ( count( $base ) >= 2 ) {
1703 // Access key is 1, base URL is 0
1704 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1706 $host = "$ipReversed.{$base[0]}";
1708 $basename = $base[0];
1710 $host = "$ipReversed.$base";
1714 $ipList = gethostbynamel( $host );
1717 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
1721 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
1730 * Check if an IP address is in the local proxy list
1736 public static function isLocallyBlockedProxy( $ip ) {
1737 global $wgProxyList;
1739 if ( !$wgProxyList ) {
1743 if ( !is_array( $wgProxyList ) ) {
1744 // Load from the specified file
1745 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1748 if ( !is_array( $wgProxyList ) ) {
1750 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1752 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1753 // Old-style flipped proxy list
1762 * Is this user subject to rate limiting?
1764 * @return bool True if rate limited
1766 public function isPingLimitable() {
1767 global $wgRateLimitsExcludedIPs;
1768 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1769 // No other good way currently to disable rate limits
1770 // for specific IPs. :P
1771 // But this is a crappy hack and should die.
1774 return !$this->isAllowed( 'noratelimit' );
1778 * Primitive rate limits: enforce maximum actions per time period
1779 * to put a brake on flooding.
1781 * The method generates both a generic profiling point and a per action one
1782 * (suffix being "-$action".
1784 * @note When using a shared cache like memcached, IP-address
1785 * last-hit counters will be shared across wikis.
1787 * @param string $action Action to enforce; 'edit' if unspecified
1788 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1789 * @return bool True if a rate limiter was tripped
1791 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1792 // Call the 'PingLimiter' hook
1794 if ( !Hooks
::run( 'PingLimiter', [ &$this, $action, &$result, $incrBy ] ) ) {
1798 global $wgRateLimits;
1799 if ( !isset( $wgRateLimits[$action] ) ) {
1803 // Some groups shouldn't trigger the ping limiter, ever
1804 if ( !$this->isPingLimitable() ) {
1808 $limits = $wgRateLimits[$action];
1810 $id = $this->getId();
1812 $isNewbie = $this->isNewbie();
1816 if ( isset( $limits['anon'] ) ) {
1817 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1820 // limits for logged-in users
1821 if ( isset( $limits['user'] ) ) {
1822 $userLimit = $limits['user'];
1824 // limits for newbie logged-in users
1825 if ( $isNewbie && isset( $limits['newbie'] ) ) {
1826 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1830 // limits for anons and for newbie logged-in users
1833 if ( isset( $limits['ip'] ) ) {
1834 $ip = $this->getRequest()->getIP();
1835 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1837 // subnet-based limits
1838 if ( isset( $limits['subnet'] ) ) {
1839 $ip = $this->getRequest()->getIP();
1840 $subnet = IP
::getSubnet( $ip );
1841 if ( $subnet !== false ) {
1842 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1847 // Check for group-specific permissions
1848 // If more than one group applies, use the group with the highest limit ratio (max/period)
1849 foreach ( $this->getGroups() as $group ) {
1850 if ( isset( $limits[$group] ) ) {
1851 if ( $userLimit === false
1852 ||
$limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1854 $userLimit = $limits[$group];
1859 // Set the user limit key
1860 if ( $userLimit !== false ) {
1861 list( $max, $period ) = $userLimit;
1862 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
1863 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1866 // ip-based limits for all ping-limitable users
1867 if ( isset( $limits['ip-all'] ) ) {
1868 $ip = $this->getRequest()->getIP();
1869 // ignore if user limit is more permissive
1870 if ( $isNewbie ||
$userLimit === false
1871 ||
$limits['ip-all'][0] / $limits['ip-all'][1] > $userLimit[0] / $userLimit[1] ) {
1872 $keys["mediawiki:limiter:$action:ip-all:$ip"] = $limits['ip-all'];
1876 // subnet-based limits for all ping-limitable users
1877 if ( isset( $limits['subnet-all'] ) ) {
1878 $ip = $this->getRequest()->getIP();
1879 $subnet = IP
::getSubnet( $ip );
1880 if ( $subnet !== false ) {
1881 // ignore if user limit is more permissive
1882 if ( $isNewbie ||
$userLimit === false
1883 ||
$limits['ip-all'][0] / $limits['ip-all'][1]
1884 > $userLimit[0] / $userLimit[1] ) {
1885 $keys["mediawiki:limiter:$action:subnet-all:$subnet"] = $limits['subnet-all'];
1890 $cache = ObjectCache
::getLocalClusterInstance();
1893 foreach ( $keys as $key => $limit ) {
1894 list( $max, $period ) = $limit;
1895 $summary = "(limit $max in {$period}s)";
1896 $count = $cache->get( $key );
1899 if ( $count >= $max ) {
1900 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1901 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1904 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1907 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1908 if ( $incrBy > 0 ) {
1909 $cache->add( $key, 0, intval( $period ) ); // first ping
1912 if ( $incrBy > 0 ) {
1913 $cache->incr( $key, $incrBy );
1921 * Check if user is blocked
1923 * @param bool $bFromSlave Whether to check the slave database instead of
1924 * the master. Hacked from false due to horrible probs on site.
1925 * @return bool True if blocked, false otherwise
1927 public function isBlocked( $bFromSlave = true ) {
1928 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
1932 * Get the block affecting the user, or null if the user is not blocked
1934 * @param bool $bFromSlave Whether to check the slave database instead of the master
1935 * @return Block|null
1937 public function getBlock( $bFromSlave = true ) {
1938 $this->getBlockedStatus( $bFromSlave );
1939 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
1943 * Check if user is blocked from editing a particular article
1945 * @param Title $title Title to check
1946 * @param bool $bFromSlave Whether to check the slave database instead of the master
1949 public function isBlockedFrom( $title, $bFromSlave = false ) {
1950 global $wgBlockAllowsUTEdit;
1952 $blocked = $this->isBlocked( $bFromSlave );
1953 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
1954 // If a user's name is suppressed, they cannot make edits anywhere
1955 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName()
1956 && $title->getNamespace() == NS_USER_TALK
) {
1958 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
1961 Hooks
::run( 'UserIsBlockedFrom', [ $this, $title, &$blocked, &$allowUsertalk ] );
1967 * If user is blocked, return the name of the user who placed the block
1968 * @return string Name of blocker
1970 public function blockedBy() {
1971 $this->getBlockedStatus();
1972 return $this->mBlockedby
;
1976 * If user is blocked, return the specified reason for the block
1977 * @return string Blocking reason
1979 public function blockedFor() {
1980 $this->getBlockedStatus();
1981 return $this->mBlockreason
;
1985 * If user is blocked, return the ID for the block
1986 * @return int Block ID
1988 public function getBlockId() {
1989 $this->getBlockedStatus();
1990 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
1994 * Check if user is blocked on all wikis.
1995 * Do not use for actual edit permission checks!
1996 * This is intended for quick UI checks.
1998 * @param string $ip IP address, uses current client if none given
1999 * @return bool True if blocked, false otherwise
2001 public function isBlockedGlobally( $ip = '' ) {
2002 return $this->getGlobalBlock( $ip ) instanceof Block
;
2006 * Check if user is blocked on all wikis.
2007 * Do not use for actual edit permission checks!
2008 * This is intended for quick UI checks.
2010 * @param string $ip IP address, uses current client if none given
2011 * @return Block|null Block object if blocked, null otherwise
2012 * @throws FatalError
2013 * @throws MWException
2015 public function getGlobalBlock( $ip = '' ) {
2016 if ( $this->mGlobalBlock
!== null ) {
2017 return $this->mGlobalBlock ?
: null;
2019 // User is already an IP?
2020 if ( IP
::isIPAddress( $this->getName() ) ) {
2021 $ip = $this->getName();
2023 $ip = $this->getRequest()->getIP();
2027 Hooks
::run( 'UserIsBlockedGlobally', [ &$this, $ip, &$blocked, &$block ] );
2029 if ( $blocked && $block === null ) {
2030 // back-compat: UserIsBlockedGlobally didn't have $block param first
2032 $block->setTarget( $ip );
2035 $this->mGlobalBlock
= $blocked ?
$block : false;
2036 return $this->mGlobalBlock ?
: null;
2040 * Check if user account is locked
2042 * @return bool True if locked, false otherwise
2044 public function isLocked() {
2045 if ( $this->mLocked
!== null ) {
2046 return $this->mLocked
;
2048 $authUser = AuthManager
::callLegacyAuthPlugin( 'getUserInstance', [ &$this ], null );
2049 $this->mLocked
= $authUser && $authUser->isLocked();
2050 Hooks
::run( 'UserIsLocked', [ $this, &$this->mLocked
] );
2051 return $this->mLocked
;
2055 * Check if user account is hidden
2057 * @return bool True if hidden, false otherwise
2059 public function isHidden() {
2060 if ( $this->mHideName
!== null ) {
2061 return $this->mHideName
;
2063 $this->getBlockedStatus();
2064 if ( !$this->mHideName
) {
2065 $authUser = AuthManager
::callLegacyAuthPlugin( 'getUserInstance', [ &$this ], null );
2066 $this->mHideName
= $authUser && $authUser->isHidden();
2067 Hooks
::run( 'UserIsHidden', [ $this, &$this->mHideName
] );
2069 return $this->mHideName
;
2073 * Get the user's ID.
2074 * @return int The user's ID; 0 if the user is anonymous or nonexistent
2076 public function getId() {
2077 if ( $this->mId
=== null && $this->mName
!== null && User
::isIP( $this->mName
) ) {
2078 // Special case, we know the user is anonymous
2080 } elseif ( !$this->isItemLoaded( 'id' ) ) {
2081 // Don't load if this was initialized from an ID
2085 return (int)$this->mId
;
2089 * Set the user and reload all fields according to a given ID
2090 * @param int $v User ID to reload
2092 public function setId( $v ) {
2094 $this->clearInstanceCache( 'id' );
2098 * Get the user name, or the IP of an anonymous user
2099 * @return string User's name or IP address
2101 public function getName() {
2102 if ( $this->isItemLoaded( 'name', 'only' ) ) {
2103 // Special case optimisation
2104 return $this->mName
;
2107 if ( $this->mName
=== false ) {
2109 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
2111 return $this->mName
;
2116 * Set the user name.
2118 * This does not reload fields from the database according to the given
2119 * name. Rather, it is used to create a temporary "nonexistent user" for
2120 * later addition to the database. It can also be used to set the IP
2121 * address for an anonymous user to something other than the current
2124 * @note User::newFromName() has roughly the same function, when the named user
2126 * @param string $str New user name to set
2128 public function setName( $str ) {
2130 $this->mName
= $str;
2134 * Get the user's name escaped by underscores.
2135 * @return string Username escaped by underscores.
2137 public function getTitleKey() {
2138 return str_replace( ' ', '_', $this->getName() );
2142 * Check if the user has new messages.
2143 * @return bool True if the user has new messages
2145 public function getNewtalk() {
2148 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2149 if ( $this->mNewtalk
=== -1 ) {
2150 $this->mNewtalk
= false; # reset talk page status
2152 // Check memcached separately for anons, who have no
2153 // entire User object stored in there.
2154 if ( !$this->mId
) {
2155 global $wgDisableAnonTalk;
2156 if ( $wgDisableAnonTalk ) {
2157 // Anon newtalk disabled by configuration.
2158 $this->mNewtalk
= false;
2160 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
2163 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2167 return (bool)$this->mNewtalk
;
2171 * Return the data needed to construct links for new talk page message
2172 * alerts. If there are new messages, this will return an associative array
2173 * with the following data:
2174 * wiki: The database name of the wiki
2175 * link: Root-relative link to the user's talk page
2176 * rev: The last talk page revision that the user has seen or null. This
2177 * is useful for building diff links.
2178 * If there are no new messages, it returns an empty array.
2179 * @note This function was designed to accomodate multiple talk pages, but
2180 * currently only returns a single link and revision.
2183 public function getNewMessageLinks() {
2185 if ( !Hooks
::run( 'UserRetrieveNewTalks', [ &$this, &$talks ] ) ) {
2187 } elseif ( !$this->getNewtalk() ) {
2190 $utp = $this->getTalkPage();
2191 $dbr = wfGetDB( DB_SLAVE
);
2192 // Get the "last viewed rev" timestamp from the oldest message notification
2193 $timestamp = $dbr->selectField( 'user_newtalk',
2194 'MIN(user_last_timestamp)',
2195 $this->isAnon() ?
[ 'user_ip' => $this->getName() ] : [ 'user_id' => $this->getId() ],
2197 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2198 return [ [ 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ] ];
2202 * Get the revision ID for the last talk page revision viewed by the talk
2204 * @return int|null Revision ID or null
2206 public function getNewMessageRevisionId() {
2207 $newMessageRevisionId = null;
2208 $newMessageLinks = $this->getNewMessageLinks();
2209 if ( $newMessageLinks ) {
2210 // Note: getNewMessageLinks() never returns more than a single link
2211 // and it is always for the same wiki, but we double-check here in
2212 // case that changes some time in the future.
2213 if ( count( $newMessageLinks ) === 1
2214 && $newMessageLinks[0]['wiki'] === wfWikiID()
2215 && $newMessageLinks[0]['rev']
2217 /** @var Revision $newMessageRevision */
2218 $newMessageRevision = $newMessageLinks[0]['rev'];
2219 $newMessageRevisionId = $newMessageRevision->getId();
2222 return $newMessageRevisionId;
2226 * Internal uncached check for new messages
2229 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2230 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2231 * @return bool True if the user has new messages
2233 protected function checkNewtalk( $field, $id ) {
2234 $dbr = wfGetDB( DB_SLAVE
);
2236 $ok = $dbr->selectField( 'user_newtalk', $field, [ $field => $id ], __METHOD__
);
2238 return $ok !== false;
2242 * Add or update the new messages flag
2243 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2244 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2245 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2246 * @return bool True if successful, false otherwise
2248 protected function updateNewtalk( $field, $id, $curRev = null ) {
2249 // Get timestamp of the talk page revision prior to the current one
2250 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2251 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2252 // Mark the user as having new messages since this revision
2253 $dbw = wfGetDB( DB_MASTER
);
2254 $dbw->insert( 'user_newtalk',
2255 [ $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ],
2258 if ( $dbw->affectedRows() ) {
2259 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2262 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2268 * Clear the new messages flag for the given user
2269 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2270 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2271 * @return bool True if successful, false otherwise
2273 protected function deleteNewtalk( $field, $id ) {
2274 $dbw = wfGetDB( DB_MASTER
);
2275 $dbw->delete( 'user_newtalk',
2278 if ( $dbw->affectedRows() ) {
2279 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2282 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2288 * Update the 'You have new messages!' status.
2289 * @param bool $val Whether the user has new messages
2290 * @param Revision $curRev New, as yet unseen revision of the user talk
2291 * page. Ignored if null or !$val.
2293 public function setNewtalk( $val, $curRev = null ) {
2294 if ( wfReadOnly() ) {
2299 $this->mNewtalk
= $val;
2301 if ( $this->isAnon() ) {
2303 $id = $this->getName();
2306 $id = $this->getId();
2310 $changed = $this->updateNewtalk( $field, $id, $curRev );
2312 $changed = $this->deleteNewtalk( $field, $id );
2316 $this->invalidateCache();
2321 * Generate a current or new-future timestamp to be stored in the
2322 * user_touched field when we update things.
2323 * @return string Timestamp in TS_MW format
2325 private function newTouchedTimestamp() {
2326 global $wgClockSkewFudge;
2328 $time = wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2329 if ( $this->mTouched
&& $time <= $this->mTouched
) {
2330 $time = wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $this->mTouched
) +
1 );
2337 * Clear user data from memcached
2339 * Use after applying updates to the database; caller's
2340 * responsibility to update user_touched if appropriate.
2342 * Called implicitly from invalidateCache() and saveSettings().
2344 * @param string $mode Use 'refresh' to clear now; otherwise before DB commit
2346 public function clearSharedCache( $mode = 'changed' ) {
2347 if ( !$this->getId() ) {
2351 $cache = ObjectCache
::getMainWANInstance();
2352 $key = $this->getCacheKey( $cache );
2353 if ( $mode === 'refresh' ) {
2354 $cache->delete( $key, 1 );
2356 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle(
2357 function() use ( $cache, $key ) {
2358 $cache->delete( $key );
2365 * Immediately touch the user data cache for this account
2367 * Calls touch() and removes account data from memcached
2369 public function invalidateCache() {
2371 $this->clearSharedCache();
2375 * Update the "touched" timestamp for the user
2377 * This is useful on various login/logout events when making sure that
2378 * a browser or proxy that has multiple tenants does not suffer cache
2379 * pollution where the new user sees the old users content. The value
2380 * of getTouched() is checked when determining 304 vs 200 responses.
2381 * Unlike invalidateCache(), this preserves the User object cache and
2382 * avoids database writes.
2386 public function touch() {
2387 $id = $this->getId();
2389 $key = wfMemcKey( 'user-quicktouched', 'id', $id );
2390 ObjectCache
::getMainWANInstance()->touchCheckKey( $key );
2391 $this->mQuickTouched
= null;
2396 * Validate the cache for this account.
2397 * @param string $timestamp A timestamp in TS_MW format
2400 public function validateCache( $timestamp ) {
2401 return ( $timestamp >= $this->getTouched() );
2405 * Get the user touched timestamp
2407 * Use this value only to validate caches via inequalities
2408 * such as in the case of HTTP If-Modified-Since response logic
2410 * @return string TS_MW Timestamp
2412 public function getTouched() {
2416 if ( $this->mQuickTouched
=== null ) {
2417 $key = wfMemcKey( 'user-quicktouched', 'id', $this->mId
);
2418 $cache = ObjectCache
::getMainWANInstance();
2420 $this->mQuickTouched
= wfTimestamp( TS_MW
, $cache->getCheckKeyTime( $key ) );
2423 return max( $this->mTouched
, $this->mQuickTouched
);
2426 return $this->mTouched
;
2430 * Get the user_touched timestamp field (time of last DB updates)
2431 * @return string TS_MW Timestamp
2434 public function getDBTouched() {
2437 return $this->mTouched
;
2441 * @deprecated Removed in 1.27.
2445 public function getPassword() {
2446 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2450 * @deprecated Removed in 1.27.
2454 public function getTemporaryPassword() {
2455 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2459 * Set the password and reset the random token.
2460 * Calls through to authentication plugin if necessary;
2461 * will have no effect if the auth plugin refuses to
2462 * pass the change through or if the legal password
2465 * As a special case, setting the password to null
2466 * wipes it, so the account cannot be logged in until
2467 * a new password is set, for instance via e-mail.
2469 * @deprecated since 1.27, use AuthManager instead
2470 * @param string $str New password to set
2471 * @throws PasswordError On failure
2474 public function setPassword( $str ) {
2475 global $wgAuth, $wgDisableAuthManager;
2477 if ( !$wgDisableAuthManager ) {
2478 return $this->setPasswordInternal( $str );
2481 if ( $str !== null ) {
2482 if ( !$wgAuth->allowPasswordChange() ) {
2483 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2486 $status = $this->checkPasswordValidity( $str );
2487 if ( !$status->isGood() ) {
2488 throw new PasswordError( $status->getMessage()->text() );
2492 if ( !$wgAuth->setPassword( $this, $str ) ) {
2493 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2496 $this->setOption( 'watchlisttoken', false );
2497 $this->setPasswordInternal( $str );
2503 * Set the password and reset the random token unconditionally.
2505 * @deprecated since 1.27, use AuthManager instead
2506 * @param string|null $str New password to set or null to set an invalid
2507 * password hash meaning that the user will not be able to log in
2508 * through the web interface.
2510 public function setInternalPassword( $str ) {
2511 global $wgAuth, $wgDisableAuthManager;
2513 if ( !$wgDisableAuthManager ) {
2514 $this->setPasswordInternal( $str );
2517 if ( $wgAuth->allowSetLocalPassword() ) {
2518 $this->setOption( 'watchlisttoken', false );
2519 $this->setPasswordInternal( $str );
2524 * Actually set the password and such
2525 * @since 1.27 cannot set a password for a user not in the database
2526 * @param string|null $str New password to set or null to set an invalid
2527 * password hash meaning that the user will not be able to log in
2528 * through the web interface.
2529 * @return bool Success
2531 private function setPasswordInternal( $str ) {
2532 global $wgDisableAuthManager;
2534 if ( $wgDisableAuthManager ) {
2535 $id = self
::idFromName( $this->getName(), self
::READ_LATEST
);
2537 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2540 $passwordFactory = new PasswordFactory();
2541 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
2542 $dbw = wfGetDB( DB_MASTER
);
2546 'user_password' => $passwordFactory->newFromPlaintext( $str )->toString(),
2547 'user_newpassword' => PasswordFactory
::newInvalidPassword()->toString(),
2548 'user_newpass_time' => $dbw->timestampOrNull( null ),
2556 // When the main password is changed, invalidate all bot passwords too
2557 BotPassword
::invalidateAllPasswordsForUser( $this->getName() );
2559 $manager = AuthManager
::singleton();
2561 // If the user doesn't exist yet, fail
2562 if ( !$manager->userExists( $this->getName() ) ) {
2563 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2566 $status = $this->changeAuthenticationData( [
2567 'username' => $this->getName(),
2571 if ( !$status->isGood() ) {
2572 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
2573 ->info( __METHOD__
. ': Password change rejected: '
2574 . $status->getWikiText( null, null, 'en' ) );
2578 $this->setOption( 'watchlisttoken', false );
2581 SessionManager
::singleton()->invalidateSessionsForUser( $this );
2587 * Changes credentials of the user.
2589 * This is a convenience wrapper around AuthManager::changeAuthenticationData.
2590 * Note that this can return a status that isOK() but not isGood() on certain types of failures,
2591 * e.g. when no provider handled the change.
2593 * @param array $data A set of authentication data in fieldname => value format. This is the
2594 * same data you would pass the changeauthenticationdata API - 'username', 'password' etc.
2598 public function changeAuthenticationData( array $data ) {
2599 global $wgDisableAuthManager;
2600 if ( $wgDisableAuthManager ) {
2601 throw new LogicException( __METHOD__
. ' cannot be called when $wgDisableAuthManager '
2605 $manager = AuthManager
::singleton();
2606 $reqs = $manager->getAuthenticationRequests( AuthManager
::ACTION_CHANGE
, $this );
2607 $reqs = AuthenticationRequest
::loadRequestsFromSubmission( $reqs, $data );
2609 $status = Status
::newGood( 'ignored' );
2610 foreach ( $reqs as $req ) {
2611 $status->merge( $manager->allowsAuthenticationDataChange( $req ), true );
2613 if ( $status->getValue() === 'ignored' ) {
2614 $status->warning( 'authenticationdatachange-ignored' );
2617 if ( $status->isGood() ) {
2618 foreach ( $reqs as $req ) {
2619 $manager->changeAuthenticationData( $req );
2626 * Get the user's current token.
2627 * @param bool $forceCreation Force the generation of a new token if the
2628 * user doesn't have one (default=true for backwards compatibility).
2629 * @return string|null Token
2631 public function getToken( $forceCreation = true ) {
2632 global $wgAuthenticationTokenVersion;
2635 if ( !$this->mToken
&& $forceCreation ) {
2639 if ( !$this->mToken
) {
2640 // The user doesn't have a token, return null to indicate that.
2642 } elseif ( $this->mToken
=== self
::INVALID_TOKEN
) {
2643 // We return a random value here so existing token checks are very
2645 return MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2646 } elseif ( $wgAuthenticationTokenVersion === null ) {
2647 // $wgAuthenticationTokenVersion not in use, so return the raw secret
2648 return $this->mToken
;
2650 // $wgAuthenticationTokenVersion in use, so hmac it.
2651 $ret = MWCryptHash
::hmac( $wgAuthenticationTokenVersion, $this->mToken
, false );
2653 // The raw hash can be overly long. Shorten it up.
2654 $len = max( 32, self
::TOKEN_LENGTH
);
2655 if ( strlen( $ret ) < $len ) {
2656 // Should never happen, even md5 is 128 bits
2657 throw new \
UnexpectedValueException( 'Hmac returned less than 128 bits' );
2659 return substr( $ret, -$len );
2664 * Set the random token (used for persistent authentication)
2665 * Called from loadDefaults() among other places.
2667 * @param string|bool $token If specified, set the token to this value
2669 public function setToken( $token = false ) {
2671 if ( $this->mToken
=== self
::INVALID_TOKEN
) {
2672 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
2673 ->debug( __METHOD__
. ": Ignoring attempt to set token for system user \"$this\"" );
2674 } elseif ( !$token ) {
2675 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2677 $this->mToken
= $token;
2682 * Set the password for a password reminder or new account email
2684 * @deprecated Removed in 1.27. Use PasswordReset instead.
2685 * @param string $str New password to set or null to set an invalid
2686 * password hash meaning that the user will not be able to use it
2687 * @param bool $throttle If true, reset the throttle timestamp to the present
2689 public function setNewpassword( $str, $throttle = true ) {
2690 global $wgDisableAuthManager;
2692 if ( $wgDisableAuthManager ) {
2693 $id = $this->getId();
2695 throw new LogicException( 'Cannot set new password for a user that is not in the database.' );
2698 $dbw = wfGetDB( DB_MASTER
);
2700 $passwordFactory = new PasswordFactory();
2701 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
2703 'user_newpassword' => $passwordFactory->newFromPlaintext( $str )->toString(),
2706 if ( $str === null ) {
2707 $update['user_newpass_time'] = null;
2708 } elseif ( $throttle ) {
2709 $update['user_newpass_time'] = $dbw->timestamp();
2712 $dbw->update( 'user', $update, [ 'user_id' => $id ], __METHOD__
);
2714 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2719 * Has password reminder email been sent within the last
2720 * $wgPasswordReminderResendTime hours?
2721 * @deprecated Removed in 1.27. See above.
2724 public function isPasswordReminderThrottled() {
2725 global $wgPasswordReminderResendTime, $wgDisableAuthManager;
2727 if ( $wgDisableAuthManager ) {
2728 if ( !$wgPasswordReminderResendTime ) {
2734 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
2735 ?
wfGetDB( DB_MASTER
)
2736 : wfGetDB( DB_SLAVE
);
2737 $newpassTime = $db->selectField(
2739 'user_newpass_time',
2740 [ 'user_id' => $this->getId() ],
2744 if ( $newpassTime === null ) {
2747 $expiry = wfTimestamp( TS_UNIX
, $newpassTime ) +
$wgPasswordReminderResendTime * 3600;
2748 return time() < $expiry;
2750 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2755 * Get the user's e-mail address
2756 * @return string User's email address
2758 public function getEmail() {
2760 Hooks
::run( 'UserGetEmail', [ $this, &$this->mEmail
] );
2761 return $this->mEmail
;
2765 * Get the timestamp of the user's e-mail authentication
2766 * @return string TS_MW timestamp
2768 public function getEmailAuthenticationTimestamp() {
2770 Hooks
::run( 'UserGetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
2771 return $this->mEmailAuthenticated
;
2775 * Set the user's e-mail address
2776 * @param string $str New e-mail address
2778 public function setEmail( $str ) {
2780 if ( $str == $this->mEmail
) {
2783 $this->invalidateEmail();
2784 $this->mEmail
= $str;
2785 Hooks
::run( 'UserSetEmail', [ $this, &$this->mEmail
] );
2789 * Set the user's e-mail address and a confirmation mail if needed.
2792 * @param string $str New e-mail address
2795 public function setEmailWithConfirmation( $str ) {
2796 global $wgEnableEmail, $wgEmailAuthentication;
2798 if ( !$wgEnableEmail ) {
2799 return Status
::newFatal( 'emaildisabled' );
2802 $oldaddr = $this->getEmail();
2803 if ( $str === $oldaddr ) {
2804 return Status
::newGood( true );
2807 $type = $oldaddr != '' ?
'changed' : 'set';
2808 $notificationResult = null;
2810 if ( $wgEmailAuthentication ) {
2811 // Send the user an email notifying the user of the change in registered
2812 // email address on their previous email address
2813 if ( $type == 'changed' ) {
2814 $change = $str != '' ?
'changed' : 'removed';
2815 $notificationResult = $this->sendMail(
2816 wfMessage( 'notificationemail_subject_' . $change )->text(),
2817 wfMessage( 'notificationemail_body_' . $change,
2818 $this->getRequest()->getIP(),
2825 $this->setEmail( $str );
2827 if ( $str !== '' && $wgEmailAuthentication ) {
2828 // Send a confirmation request to the new address if needed
2829 $result = $this->sendConfirmationMail( $type );
2831 if ( $notificationResult !== null ) {
2832 $result->merge( $notificationResult );
2835 if ( $result->isGood() ) {
2836 // Say to the caller that a confirmation and notification mail has been sent
2837 $result->value
= 'eauth';
2840 $result = Status
::newGood( true );
2847 * Get the user's real name
2848 * @return string User's real name
2850 public function getRealName() {
2851 if ( !$this->isItemLoaded( 'realname' ) ) {
2855 return $this->mRealName
;
2859 * Set the user's real name
2860 * @param string $str New real name
2862 public function setRealName( $str ) {
2864 $this->mRealName
= $str;
2868 * Get the user's current setting for a given option.
2870 * @param string $oname The option to check
2871 * @param string $defaultOverride A default value returned if the option does not exist
2872 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2873 * @return string User's current value for the option
2874 * @see getBoolOption()
2875 * @see getIntOption()
2877 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2878 global $wgHiddenPrefs;
2879 $this->loadOptions();
2881 # We want 'disabled' preferences to always behave as the default value for
2882 # users, even if they have set the option explicitly in their settings (ie they
2883 # set it, and then it was disabled removing their ability to change it). But
2884 # we don't want to erase the preferences in the database in case the preference
2885 # is re-enabled again. So don't touch $mOptions, just override the returned value
2886 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2887 return self
::getDefaultOption( $oname );
2890 if ( array_key_exists( $oname, $this->mOptions
) ) {
2891 return $this->mOptions
[$oname];
2893 return $defaultOverride;
2898 * Get all user's options
2900 * @param int $flags Bitwise combination of:
2901 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2902 * to the default value. (Since 1.25)
2905 public function getOptions( $flags = 0 ) {
2906 global $wgHiddenPrefs;
2907 $this->loadOptions();
2908 $options = $this->mOptions
;
2910 # We want 'disabled' preferences to always behave as the default value for
2911 # users, even if they have set the option explicitly in their settings (ie they
2912 # set it, and then it was disabled removing their ability to change it). But
2913 # we don't want to erase the preferences in the database in case the preference
2914 # is re-enabled again. So don't touch $mOptions, just override the returned value
2915 foreach ( $wgHiddenPrefs as $pref ) {
2916 $default = self
::getDefaultOption( $pref );
2917 if ( $default !== null ) {
2918 $options[$pref] = $default;
2922 if ( $flags & self
::GETOPTIONS_EXCLUDE_DEFAULTS
) {
2923 $options = array_diff_assoc( $options, self
::getDefaultOptions() );
2930 * Get the user's current setting for a given option, as a boolean value.
2932 * @param string $oname The option to check
2933 * @return bool User's current value for the option
2936 public function getBoolOption( $oname ) {
2937 return (bool)$this->getOption( $oname );
2941 * Get the user's current setting for a given option, as an integer value.
2943 * @param string $oname The option to check
2944 * @param int $defaultOverride A default value returned if the option does not exist
2945 * @return int User's current value for the option
2948 public function getIntOption( $oname, $defaultOverride = 0 ) {
2949 $val = $this->getOption( $oname );
2951 $val = $defaultOverride;
2953 return intval( $val );
2957 * Set the given option for a user.
2959 * You need to call saveSettings() to actually write to the database.
2961 * @param string $oname The option to set
2962 * @param mixed $val New value to set
2964 public function setOption( $oname, $val ) {
2965 $this->loadOptions();
2967 // Explicitly NULL values should refer to defaults
2968 if ( is_null( $val ) ) {
2969 $val = self
::getDefaultOption( $oname );
2972 $this->mOptions
[$oname] = $val;
2976 * Get a token stored in the preferences (like the watchlist one),
2977 * resetting it if it's empty (and saving changes).
2979 * @param string $oname The option name to retrieve the token from
2980 * @return string|bool User's current value for the option, or false if this option is disabled.
2981 * @see resetTokenFromOption()
2983 * @deprecated 1.26 Applications should use the OAuth extension
2985 public function getTokenFromOption( $oname ) {
2986 global $wgHiddenPrefs;
2988 $id = $this->getId();
2989 if ( !$id ||
in_array( $oname, $wgHiddenPrefs ) ) {
2993 $token = $this->getOption( $oname );
2995 // Default to a value based on the user token to avoid space
2996 // wasted on storing tokens for all users. When this option
2997 // is set manually by the user, only then is it stored.
2998 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
3005 * Reset a token stored in the preferences (like the watchlist one).
3006 * *Does not* save user's preferences (similarly to setOption()).
3008 * @param string $oname The option name to reset the token in
3009 * @return string|bool New token value, or false if this option is disabled.
3010 * @see getTokenFromOption()
3013 public function resetTokenFromOption( $oname ) {
3014 global $wgHiddenPrefs;
3015 if ( in_array( $oname, $wgHiddenPrefs ) ) {
3019 $token = MWCryptRand
::generateHex( 40 );
3020 $this->setOption( $oname, $token );
3025 * Return a list of the types of user options currently returned by
3026 * User::getOptionKinds().
3028 * Currently, the option kinds are:
3029 * - 'registered' - preferences which are registered in core MediaWiki or
3030 * by extensions using the UserGetDefaultOptions hook.
3031 * - 'registered-multiselect' - as above, using the 'multiselect' type.
3032 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
3033 * - 'userjs' - preferences with names starting with 'userjs-', intended to
3034 * be used by user scripts.
3035 * - 'special' - "preferences" that are not accessible via User::getOptions
3036 * or User::setOptions.
3037 * - 'unused' - preferences about which MediaWiki doesn't know anything.
3038 * These are usually legacy options, removed in newer versions.
3040 * The API (and possibly others) use this function to determine the possible
3041 * option types for validation purposes, so make sure to update this when a
3042 * new option kind is added.
3044 * @see User::getOptionKinds
3045 * @return array Option kinds
3047 public static function listOptionKinds() {
3050 'registered-multiselect',
3051 'registered-checkmatrix',
3059 * Return an associative array mapping preferences keys to the kind of a preference they're
3060 * used for. Different kinds are handled differently when setting or reading preferences.
3062 * See User::listOptionKinds for the list of valid option types that can be provided.
3064 * @see User::listOptionKinds
3065 * @param IContextSource $context
3066 * @param array $options Assoc. array with options keys to check as keys.
3067 * Defaults to $this->mOptions.
3068 * @return array The key => kind mapping data
3070 public function getOptionKinds( IContextSource
$context, $options = null ) {
3071 $this->loadOptions();
3072 if ( $options === null ) {
3073 $options = $this->mOptions
;
3076 $prefs = Preferences
::getPreferences( $this, $context );
3079 // Pull out the "special" options, so they don't get converted as
3080 // multiselect or checkmatrix.
3081 $specialOptions = array_fill_keys( Preferences
::getSaveBlacklist(), true );
3082 foreach ( $specialOptions as $name => $value ) {
3083 unset( $prefs[$name] );
3086 // Multiselect and checkmatrix options are stored in the database with
3087 // one key per option, each having a boolean value. Extract those keys.
3088 $multiselectOptions = [];
3089 foreach ( $prefs as $name => $info ) {
3090 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
3091 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
3092 $opts = HTMLFormField
::flattenOptions( $info['options'] );
3093 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
3095 foreach ( $opts as $value ) {
3096 $multiselectOptions["$prefix$value"] = true;
3099 unset( $prefs[$name] );
3102 $checkmatrixOptions = [];
3103 foreach ( $prefs as $name => $info ) {
3104 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
3105 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
3106 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
3107 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
3108 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
3110 foreach ( $columns as $column ) {
3111 foreach ( $rows as $row ) {
3112 $checkmatrixOptions["$prefix$column-$row"] = true;
3116 unset( $prefs[$name] );
3120 // $value is ignored
3121 foreach ( $options as $key => $value ) {
3122 if ( isset( $prefs[$key] ) ) {
3123 $mapping[$key] = 'registered';
3124 } elseif ( isset( $multiselectOptions[$key] ) ) {
3125 $mapping[$key] = 'registered-multiselect';
3126 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
3127 $mapping[$key] = 'registered-checkmatrix';
3128 } elseif ( isset( $specialOptions[$key] ) ) {
3129 $mapping[$key] = 'special';
3130 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
3131 $mapping[$key] = 'userjs';
3133 $mapping[$key] = 'unused';
3141 * Reset certain (or all) options to the site defaults
3143 * The optional parameter determines which kinds of preferences will be reset.
3144 * Supported values are everything that can be reported by getOptionKinds()
3145 * and 'all', which forces a reset of *all* preferences and overrides everything else.
3147 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
3148 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
3149 * for backwards-compatibility.
3150 * @param IContextSource|null $context Context source used when $resetKinds
3151 * does not contain 'all', passed to getOptionKinds().
3152 * Defaults to RequestContext::getMain() when null.
3154 public function resetOptions(
3155 $resetKinds = [ 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ],
3156 IContextSource
$context = null
3159 $defaultOptions = self
::getDefaultOptions();
3161 if ( !is_array( $resetKinds ) ) {
3162 $resetKinds = [ $resetKinds ];
3165 if ( in_array( 'all', $resetKinds ) ) {
3166 $newOptions = $defaultOptions;
3168 if ( $context === null ) {
3169 $context = RequestContext
::getMain();
3172 $optionKinds = $this->getOptionKinds( $context );
3173 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
3176 // Use default values for the options that should be deleted, and
3177 // copy old values for the ones that shouldn't.
3178 foreach ( $this->mOptions
as $key => $value ) {
3179 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
3180 if ( array_key_exists( $key, $defaultOptions ) ) {
3181 $newOptions[$key] = $defaultOptions[$key];
3184 $newOptions[$key] = $value;
3189 Hooks
::run( 'UserResetAllOptions', [ $this, &$newOptions, $this->mOptions
, $resetKinds ] );
3191 $this->mOptions
= $newOptions;
3192 $this->mOptionsLoaded
= true;
3196 * Get the user's preferred date format.
3197 * @return string User's preferred date format
3199 public function getDatePreference() {
3200 // Important migration for old data rows
3201 if ( is_null( $this->mDatePreference
) ) {
3203 $value = $this->getOption( 'date' );
3204 $map = $wgLang->getDatePreferenceMigrationMap();
3205 if ( isset( $map[$value] ) ) {
3206 $value = $map[$value];
3208 $this->mDatePreference
= $value;
3210 return $this->mDatePreference
;
3214 * Determine based on the wiki configuration and the user's options,
3215 * whether this user must be over HTTPS no matter what.
3219 public function requiresHTTPS() {
3220 global $wgSecureLogin;
3221 if ( !$wgSecureLogin ) {
3224 $https = $this->getBoolOption( 'prefershttps' );
3225 Hooks
::run( 'UserRequiresHTTPS', [ $this, &$https ] );
3227 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
3234 * Get the user preferred stub threshold
3238 public function getStubThreshold() {
3239 global $wgMaxArticleSize; # Maximum article size, in Kb
3240 $threshold = $this->getIntOption( 'stubthreshold' );
3241 if ( $threshold > $wgMaxArticleSize * 1024 ) {
3242 // If they have set an impossible value, disable the preference
3243 // so we can use the parser cache again.
3250 * Get the permissions this user has.
3251 * @return array Array of String permission names
3253 public function getRights() {
3254 if ( is_null( $this->mRights
) ) {
3255 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
3257 // Deny any rights denied by the user's session, unless this
3258 // endpoint has no sessions.
3259 if ( !defined( 'MW_NO_SESSION' ) ) {
3260 $allowedRights = $this->getRequest()->getSession()->getAllowedUserRights();
3261 if ( $allowedRights !== null ) {
3262 $this->mRights
= array_intersect( $this->mRights
, $allowedRights );
3266 Hooks
::run( 'UserGetRights', [ $this, &$this->mRights
] );
3267 // Force reindexation of rights when a hook has unset one of them
3268 $this->mRights
= array_values( array_unique( $this->mRights
) );
3270 return $this->mRights
;
3274 * Get the list of explicit group memberships this user has.
3275 * The implicit * and user groups are not included.
3276 * @return array Array of String internal group names
3278 public function getGroups() {
3280 $this->loadGroups();
3281 return $this->mGroups
;
3285 * Get the list of implicit group memberships this user has.
3286 * This includes all explicit groups, plus 'user' if logged in,
3287 * '*' for all accounts, and autopromoted groups
3288 * @param bool $recache Whether to avoid the cache
3289 * @return array Array of String internal group names
3291 public function getEffectiveGroups( $recache = false ) {
3292 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
3293 $this->mEffectiveGroups
= array_unique( array_merge(
3294 $this->getGroups(), // explicit groups
3295 $this->getAutomaticGroups( $recache ) // implicit groups
3297 // Hook for additional groups
3298 Hooks
::run( 'UserEffectiveGroups', [ &$this, &$this->mEffectiveGroups
] );
3299 // Force reindexation of groups when a hook has unset one of them
3300 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
3302 return $this->mEffectiveGroups
;
3306 * Get the list of implicit group memberships this user has.
3307 * This includes 'user' if logged in, '*' for all accounts,
3308 * and autopromoted groups
3309 * @param bool $recache Whether to avoid the cache
3310 * @return array Array of String internal group names
3312 public function getAutomaticGroups( $recache = false ) {
3313 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
3314 $this->mImplicitGroups
= [ '*' ];
3315 if ( $this->getId() ) {
3316 $this->mImplicitGroups
[] = 'user';
3318 $this->mImplicitGroups
= array_unique( array_merge(
3319 $this->mImplicitGroups
,
3320 Autopromote
::getAutopromoteGroups( $this )
3324 // Assure data consistency with rights/groups,
3325 // as getEffectiveGroups() depends on this function
3326 $this->mEffectiveGroups
= null;
3329 return $this->mImplicitGroups
;
3333 * Returns the groups the user has belonged to.
3335 * The user may still belong to the returned groups. Compare with getGroups().
3337 * The function will not return groups the user had belonged to before MW 1.17
3339 * @return array Names of the groups the user has belonged to.
3341 public function getFormerGroups() {
3344 if ( is_null( $this->mFormerGroups
) ) {
3345 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3346 ?
wfGetDB( DB_MASTER
)
3347 : wfGetDB( DB_SLAVE
);
3348 $res = $db->select( 'user_former_groups',
3350 [ 'ufg_user' => $this->mId
],
3352 $this->mFormerGroups
= [];
3353 foreach ( $res as $row ) {
3354 $this->mFormerGroups
[] = $row->ufg_group
;
3358 return $this->mFormerGroups
;
3362 * Get the user's edit count.
3363 * @return int|null Null for anonymous users
3365 public function getEditCount() {
3366 if ( !$this->getId() ) {
3370 if ( $this->mEditCount
=== null ) {
3371 /* Populate the count, if it has not been populated yet */
3372 $dbr = wfGetDB( DB_SLAVE
);
3373 // check if the user_editcount field has been initialized
3374 $count = $dbr->selectField(
3375 'user', 'user_editcount',
3376 [ 'user_id' => $this->mId
],
3380 if ( $count === null ) {
3381 // it has not been initialized. do so.
3382 $count = $this->initEditCount();
3384 $this->mEditCount
= $count;
3386 return (int)$this->mEditCount
;
3390 * Add the user to the given group.
3391 * This takes immediate effect.
3392 * @param string $group Name of the group to add
3395 public function addGroup( $group ) {
3398 if ( !Hooks
::run( 'UserAddGroup', [ $this, &$group ] ) ) {
3402 $dbw = wfGetDB( DB_MASTER
);
3403 if ( $this->getId() ) {
3404 $dbw->insert( 'user_groups',
3406 'ug_user' => $this->getId(),
3407 'ug_group' => $group,
3413 $this->loadGroups();
3414 $this->mGroups
[] = $group;
3415 // In case loadGroups was not called before, we now have the right twice.
3416 // Get rid of the duplicate.
3417 $this->mGroups
= array_unique( $this->mGroups
);
3419 // Refresh the groups caches, and clear the rights cache so it will be
3420 // refreshed on the next call to $this->getRights().
3421 $this->getEffectiveGroups( true );
3422 $this->mRights
= null;
3424 $this->invalidateCache();
3430 * Remove the user from the given group.
3431 * This takes immediate effect.
3432 * @param string $group Name of the group to remove
3435 public function removeGroup( $group ) {
3437 if ( !Hooks
::run( 'UserRemoveGroup', [ $this, &$group ] ) ) {
3441 $dbw = wfGetDB( DB_MASTER
);
3442 $dbw->delete( 'user_groups',
3444 'ug_user' => $this->getId(),
3445 'ug_group' => $group,
3448 // Remember that the user was in this group
3449 $dbw->insert( 'user_former_groups',
3451 'ufg_user' => $this->getId(),
3452 'ufg_group' => $group,
3458 $this->loadGroups();
3459 $this->mGroups
= array_diff( $this->mGroups
, [ $group ] );
3461 // Refresh the groups caches, and clear the rights cache so it will be
3462 // refreshed on the next call to $this->getRights().
3463 $this->getEffectiveGroups( true );
3464 $this->mRights
= null;
3466 $this->invalidateCache();
3472 * Get whether the user is logged in
3475 public function isLoggedIn() {
3476 return $this->getId() != 0;
3480 * Get whether the user is anonymous
3483 public function isAnon() {
3484 return !$this->isLoggedIn();
3488 * @return bool Whether this user is flagged as being a bot role account
3491 public function isBot() {
3492 if ( in_array( 'bot', $this->getGroups() ) && $this->isAllowed( 'bot' ) ) {
3497 Hooks
::run( "UserIsBot", [ $this, &$isBot ] );
3503 * Check if user is allowed to access a feature / make an action
3505 * @param string ... Permissions to test
3506 * @return bool True if user is allowed to perform *any* of the given actions
3508 public function isAllowedAny() {
3509 $permissions = func_get_args();
3510 foreach ( $permissions as $permission ) {
3511 if ( $this->isAllowed( $permission ) ) {
3520 * @param string ... Permissions to test
3521 * @return bool True if the user is allowed to perform *all* of the given actions
3523 public function isAllowedAll() {
3524 $permissions = func_get_args();
3525 foreach ( $permissions as $permission ) {
3526 if ( !$this->isAllowed( $permission ) ) {
3534 * Internal mechanics of testing a permission
3535 * @param string $action
3538 public function isAllowed( $action = '' ) {
3539 if ( $action === '' ) {
3540 return true; // In the spirit of DWIM
3542 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3543 // by misconfiguration: 0 == 'foo'
3544 return in_array( $action, $this->getRights(), true );
3548 * Check whether to enable recent changes patrol features for this user
3549 * @return bool True or false
3551 public function useRCPatrol() {
3552 global $wgUseRCPatrol;
3553 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3557 * Check whether to enable new pages patrol features for this user
3558 * @return bool True or false
3560 public function useNPPatrol() {
3561 global $wgUseRCPatrol, $wgUseNPPatrol;
3563 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3564 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3569 * Check whether to enable new files patrol features for this user
3570 * @return bool True or false
3572 public function useFilePatrol() {
3573 global $wgUseRCPatrol, $wgUseFilePatrol;
3575 ( $wgUseRCPatrol ||
$wgUseFilePatrol )
3576 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3581 * Get the WebRequest object to use with this object
3583 * @return WebRequest
3585 public function getRequest() {
3586 if ( $this->mRequest
) {
3587 return $this->mRequest
;
3595 * Check the watched status of an article.
3596 * @since 1.22 $checkRights parameter added
3597 * @param Title $title Title of the article to look at
3598 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3599 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3602 public function isWatched( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3603 if ( $title->isWatchable() && ( !$checkRights ||
$this->isAllowed( 'viewmywatchlist' ) ) ) {
3604 return MediaWikiServices
::getInstance()->getWatchedItemStore()->isWatched( $this, $title );
3611 * @since 1.22 $checkRights parameter added
3612 * @param Title $title Title of the article to look at
3613 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3614 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3616 public function addWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3617 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3618 MediaWikiServices
::getInstance()->getWatchedItemStore()->addWatchBatchForUser(
3620 [ $title->getSubjectPage(), $title->getTalkPage() ]
3623 $this->invalidateCache();
3627 * Stop watching an article.
3628 * @since 1.22 $checkRights parameter added
3629 * @param Title $title Title of the article to look at
3630 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3631 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3633 public function removeWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3634 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3635 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
3636 $store->removeWatch( $this, $title->getSubjectPage() );
3637 $store->removeWatch( $this, $title->getTalkPage() );
3639 $this->invalidateCache();
3643 * Clear the user's notification timestamp for the given title.
3644 * If e-notif e-mails are on, they will receive notification mails on
3645 * the next change of the page if it's watched etc.
3646 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3647 * @param Title $title Title of the article to look at
3648 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3650 public function clearNotification( &$title, $oldid = 0 ) {
3651 global $wgUseEnotif, $wgShowUpdatedMarker;
3653 // Do nothing if the database is locked to writes
3654 if ( wfReadOnly() ) {
3658 // Do nothing if not allowed to edit the watchlist
3659 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3663 // If we're working on user's talk page, we should update the talk page message indicator
3664 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3665 if ( !Hooks
::run( 'UserClearNewTalkNotification', [ &$this, $oldid ] ) ) {
3669 // Try to update the DB post-send and only if needed...
3670 DeferredUpdates
::addCallableUpdate( function() use ( $title, $oldid ) {
3671 if ( !$this->getNewtalk() ) {
3672 return; // no notifications to clear
3675 // Delete the last notifications (they stack up)
3676 $this->setNewtalk( false );
3678 // If there is a new, unseen, revision, use its timestamp
3680 ?
$title->getNextRevisionID( $oldid, Title
::GAID_FOR_UPDATE
)
3683 $this->setNewtalk( true, Revision
::newFromId( $nextid ) );
3688 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3692 if ( $this->isAnon() ) {
3693 // Nothing else to do...
3697 // Only update the timestamp if the page is being watched.
3698 // The query to find out if it is watched is cached both in memcached and per-invocation,
3699 // and when it does have to be executed, it can be on a slave
3700 // If this is the user's newtalk page, we always update the timestamp
3702 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3706 MediaWikiServices
::getInstance()->getWatchedItemStore()
3707 ->resetNotificationTimestamp( $this, $title, $force, $oldid );
3711 * Resets all of the given user's page-change notification timestamps.
3712 * If e-notif e-mails are on, they will receive notification mails on
3713 * the next change of any watched page.
3714 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3716 public function clearAllNotifications() {
3717 if ( wfReadOnly() ) {
3721 // Do nothing if not allowed to edit the watchlist
3722 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3726 global $wgUseEnotif, $wgShowUpdatedMarker;
3727 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3728 $this->setNewtalk( false );
3731 $id = $this->getId();
3733 $dbw = wfGetDB( DB_MASTER
);
3734 $dbw->update( 'watchlist',
3735 [ /* SET */ 'wl_notificationtimestamp' => null ],
3736 [ /* WHERE */ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ],
3739 // We also need to clear here the "you have new message" notification for the own user_talk page;
3740 // it's cleared one page view later in WikiPage::doViewUpdates().
3745 * Set a cookie on the user's client. Wrapper for
3746 * WebResponse::setCookie
3747 * @deprecated since 1.27
3748 * @param string $name Name of the cookie to set
3749 * @param string $value Value to set
3750 * @param int $exp Expiration time, as a UNIX time value;
3751 * if 0 or not specified, use the default $wgCookieExpiration
3752 * @param bool $secure
3753 * true: Force setting the secure attribute when setting the cookie
3754 * false: Force NOT setting the secure attribute when setting the cookie
3755 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3756 * @param array $params Array of options sent passed to WebResponse::setcookie()
3757 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3760 protected function setCookie(
3761 $name, $value, $exp = 0, $secure = null, $params = [], $request = null
3763 wfDeprecated( __METHOD__
, '1.27' );
3764 if ( $request === null ) {
3765 $request = $this->getRequest();
3767 $params['secure'] = $secure;
3768 $request->response()->setCookie( $name, $value, $exp, $params );
3772 * Clear a cookie on the user's client
3773 * @deprecated since 1.27
3774 * @param string $name Name of the cookie to clear
3775 * @param bool $secure
3776 * true: Force setting the secure attribute when setting the cookie
3777 * false: Force NOT setting the secure attribute when setting the cookie
3778 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3779 * @param array $params Array of options sent passed to WebResponse::setcookie()
3781 protected function clearCookie( $name, $secure = null, $params = [] ) {
3782 wfDeprecated( __METHOD__
, '1.27' );
3783 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3787 * Set an extended login cookie on the user's client. The expiry of the cookie
3788 * is controlled by the $wgExtendedLoginCookieExpiration configuration
3791 * @see User::setCookie
3793 * @deprecated since 1.27
3794 * @param string $name Name of the cookie to set
3795 * @param string $value Value to set
3796 * @param bool $secure
3797 * true: Force setting the secure attribute when setting the cookie
3798 * false: Force NOT setting the secure attribute when setting the cookie
3799 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3801 protected function setExtendedLoginCookie( $name, $value, $secure ) {
3802 global $wgExtendedLoginCookieExpiration, $wgCookieExpiration;
3804 wfDeprecated( __METHOD__
, '1.27' );
3807 $exp +
= $wgExtendedLoginCookieExpiration !== null
3808 ?
$wgExtendedLoginCookieExpiration
3809 : $wgCookieExpiration;
3811 $this->setCookie( $name, $value, $exp, $secure );
3815 * Persist this user's session (e.g. set cookies)
3817 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3819 * @param bool $secure Whether to force secure/insecure cookies or use default
3820 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3822 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3824 if ( 0 == $this->mId
) {
3828 $session = $this->getRequest()->getSession();
3829 if ( $request && $session->getRequest() !== $request ) {
3830 $session = $session->sessionWithRequest( $request );
3832 $delay = $session->delaySave();
3834 if ( !$session->getUser()->equals( $this ) ) {
3835 if ( !$session->canSetUser() ) {
3836 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3837 ->warning( __METHOD__
.
3838 ": Cannot save user \"$this\" to a user \"{$session->getUser()}\"'s immutable session"
3842 $session->setUser( $this );
3845 $session->setRememberUser( $rememberMe );
3846 if ( $secure !== null ) {
3847 $session->setForceHTTPS( $secure );
3850 $session->persist();
3852 ScopedCallback
::consume( $delay );
3856 * Log this user out.
3858 public function logout() {
3859 if ( Hooks
::run( 'UserLogout', [ &$this ] ) ) {
3865 * Clear the user's session, and reset the instance cache.
3868 public function doLogout() {
3869 $session = $this->getRequest()->getSession();
3870 if ( !$session->canSetUser() ) {
3871 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3872 ->warning( __METHOD__
. ": Cannot log out of an immutable session" );
3873 $error = 'immutable';
3874 } elseif ( !$session->getUser()->equals( $this ) ) {
3875 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3876 ->warning( __METHOD__
.
3877 ": Cannot log user \"$this\" out of a user \"{$session->getUser()}\"'s session"
3879 // But we still may as well make this user object anon
3880 $this->clearInstanceCache( 'defaults' );
3881 $error = 'wronguser';
3883 $this->clearInstanceCache( 'defaults' );
3884 $delay = $session->delaySave();
3885 $session->unpersist(); // Clear cookies (T127436)
3886 $session->setLoggedOutTimestamp( time() );
3887 $session->setUser( new User
);
3888 $session->set( 'wsUserID', 0 ); // Other code expects this
3889 $session->resetAllTokens();
3890 ScopedCallback
::consume( $delay );
3893 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authmanager' )->info( 'Logout', [
3894 'event' => 'logout',
3895 'successful' => $error === false,
3896 'status' => $error ?
: 'success',
3901 * Save this user's settings into the database.
3902 * @todo Only rarely do all these fields need to be set!
3904 public function saveSettings() {
3905 if ( wfReadOnly() ) {
3906 // @TODO: caller should deal with this instead!
3907 // This should really just be an exception.
3908 MWExceptionHandler
::logException( new DBExpectedError(
3910 "Could not update user with ID '{$this->mId}'; DB is read-only."
3916 if ( 0 == $this->mId
) {
3920 // Get a new user_touched that is higher than the old one.
3921 // This will be used for a CAS check as a last-resort safety
3922 // check against race conditions and slave lag.
3923 $newTouched = $this->newTouchedTimestamp();
3925 $dbw = wfGetDB( DB_MASTER
);
3926 $dbw->update( 'user',
3928 'user_name' => $this->mName
,
3929 'user_real_name' => $this->mRealName
,
3930 'user_email' => $this->mEmail
,
3931 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3932 'user_touched' => $dbw->timestamp( $newTouched ),
3933 'user_token' => strval( $this->mToken
),
3934 'user_email_token' => $this->mEmailToken
,
3935 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
3936 ], $this->makeUpdateConditions( $dbw, [ /* WHERE */
3937 'user_id' => $this->mId
,
3941 if ( !$dbw->affectedRows() ) {
3942 // Maybe the problem was a missed cache update; clear it to be safe
3943 $this->clearSharedCache( 'refresh' );
3944 // User was changed in the meantime or loaded with stale data
3945 $from = ( $this->queryFlagsUsed
& self
::READ_LATEST
) ?
'master' : 'slave';
3946 throw new MWException(
3947 "CAS update failed on user_touched for user ID '{$this->mId}' (read from $from);" .
3948 " the version of the user to be saved is older than the current version."
3952 $this->mTouched
= $newTouched;
3953 $this->saveOptions();
3955 Hooks
::run( 'UserSaveSettings', [ $this ] );
3956 $this->clearSharedCache();
3957 $this->getUserPage()->invalidateCache();
3961 * If only this user's username is known, and it exists, return the user ID.
3963 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
3966 public function idForName( $flags = 0 ) {
3967 $s = trim( $this->getName() );
3972 $db = ( ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
)
3973 ?
wfGetDB( DB_MASTER
)
3974 : wfGetDB( DB_SLAVE
);
3976 $options = ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
)
3977 ?
[ 'LOCK IN SHARE MODE' ]
3980 $id = $db->selectField( 'user',
3981 'user_id', [ 'user_name' => $s ], __METHOD__
, $options );
3987 * Add a user to the database, return the user object
3989 * @param string $name Username to add
3990 * @param array $params Array of Strings Non-default parameters to save to
3991 * the database as user_* fields:
3992 * - email: The user's email address.
3993 * - email_authenticated: The email authentication timestamp.
3994 * - real_name: The user's real name.
3995 * - options: An associative array of non-default options.
3996 * - token: Random authentication token. Do not set.
3997 * - registration: Registration timestamp. Do not set.
3999 * @return User|null User object, or null if the username already exists.
4001 public static function createNew( $name, $params = [] ) {
4002 foreach ( [ 'password', 'newpassword', 'newpass_time', 'password_expires' ] as $field ) {
4003 if ( isset( $params[$field] ) ) {
4004 wfDeprecated( __METHOD__
. " with param '$field'", '1.27' );
4005 unset( $params[$field] );
4011 $user->setToken(); // init token
4012 if ( isset( $params['options'] ) ) {
4013 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
4014 unset( $params['options'] );
4016 $dbw = wfGetDB( DB_MASTER
);
4017 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
4019 $noPass = PasswordFactory
::newInvalidPassword()->toString();
4022 'user_id' => $seqVal,
4023 'user_name' => $name,
4024 'user_password' => $noPass,
4025 'user_newpassword' => $noPass,
4026 'user_email' => $user->mEmail
,
4027 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
4028 'user_real_name' => $user->mRealName
,
4029 'user_token' => strval( $user->mToken
),
4030 'user_registration' => $dbw->timestamp( $user->mRegistration
),
4031 'user_editcount' => 0,
4032 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
4034 foreach ( $params as $name => $value ) {
4035 $fields["user_$name"] = $value;
4037 $dbw->insert( 'user', $fields, __METHOD__
, [ 'IGNORE' ] );
4038 if ( $dbw->affectedRows() ) {
4039 $newUser = User
::newFromId( $dbw->insertId() );
4047 * Add this existing user object to the database. If the user already
4048 * exists, a fatal status object is returned, and the user object is
4049 * initialised with the data from the database.
4051 * Previously, this function generated a DB error due to a key conflict
4052 * if the user already existed. Many extension callers use this function
4053 * in code along the lines of:
4055 * $user = User::newFromName( $name );
4056 * if ( !$user->isLoggedIn() ) {
4057 * $user->addToDatabase();
4059 * // do something with $user...
4061 * However, this was vulnerable to a race condition (bug 16020). By
4062 * initialising the user object if the user exists, we aim to support this
4063 * calling sequence as far as possible.
4065 * Note that if the user exists, this function will acquire a write lock,
4066 * so it is still advisable to make the call conditional on isLoggedIn(),
4067 * and to commit the transaction after calling.
4069 * @throws MWException
4072 public function addToDatabase() {
4074 if ( !$this->mToken
) {
4075 $this->setToken(); // init token
4078 $this->mTouched
= $this->newTouchedTimestamp();
4080 $noPass = PasswordFactory
::newInvalidPassword()->toString();
4082 $dbw = wfGetDB( DB_MASTER
);
4083 $inWrite = $dbw->writesOrCallbacksPending();
4084 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
4085 $dbw->insert( 'user',
4087 'user_id' => $seqVal,
4088 'user_name' => $this->mName
,
4089 'user_password' => $noPass,
4090 'user_newpassword' => $noPass,
4091 'user_email' => $this->mEmail
,
4092 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
4093 'user_real_name' => $this->mRealName
,
4094 'user_token' => strval( $this->mToken
),
4095 'user_registration' => $dbw->timestamp( $this->mRegistration
),
4096 'user_editcount' => 0,
4097 'user_touched' => $dbw->timestamp( $this->mTouched
),
4101 if ( !$dbw->affectedRows() ) {
4102 // The queries below cannot happen in the same REPEATABLE-READ snapshot.
4103 // Handle this by COMMIT, if possible, or by LOCK IN SHARE MODE otherwise.
4105 // Can't commit due to pending writes that may need atomicity.
4106 // This may cause some lock contention unlike the case below.
4107 $options = [ 'LOCK IN SHARE MODE' ];
4108 $flags = self
::READ_LOCKING
;
4110 // Often, this case happens early in views before any writes when
4111 // using CentralAuth. It's should be OK to commit and break the snapshot.
4112 $dbw->commit( __METHOD__
, 'flush' );
4114 $flags = self
::READ_LATEST
;
4116 $this->mId
= $dbw->selectField( 'user', 'user_id',
4117 [ 'user_name' => $this->mName
], __METHOD__
, $options );
4120 if ( $this->loadFromDatabase( $flags ) ) {
4125 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
4126 "to insert user '{$this->mName}' row, but it was not present in select!" );
4128 return Status
::newFatal( 'userexists' );
4130 $this->mId
= $dbw->insertId();
4131 self
::$idCacheByName[$this->mName
] = $this->mId
;
4133 // Clear instance cache other than user table data, which is already accurate
4134 $this->clearInstanceCache();
4136 $this->saveOptions();
4137 return Status
::newGood();
4141 * If this user is logged-in and blocked,
4142 * block any IP address they've successfully logged in from.
4143 * @return bool A block was spread
4145 public function spreadAnyEditBlock() {
4146 if ( $this->isLoggedIn() && $this->isBlocked() ) {
4147 return $this->spreadBlock();
4154 * If this (non-anonymous) user is blocked,
4155 * block the IP address they've successfully logged in from.
4156 * @return bool A block was spread
4158 protected function spreadBlock() {
4159 wfDebug( __METHOD__
. "()\n" );
4161 if ( $this->mId
== 0 ) {
4165 $userblock = Block
::newFromTarget( $this->getName() );
4166 if ( !$userblock ) {
4170 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
4174 * Get whether the user is explicitly blocked from account creation.
4175 * @return bool|Block
4177 public function isBlockedFromCreateAccount() {
4178 $this->getBlockedStatus();
4179 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
4180 return $this->mBlock
;
4183 # bug 13611: if the IP address the user is trying to create an account from is
4184 # blocked with createaccount disabled, prevent new account creation there even
4185 # when the user is logged in
4186 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
4187 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
4189 return $this->mBlockedFromCreateAccount
instanceof Block
4190 && $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
4191 ?
$this->mBlockedFromCreateAccount
4196 * Get whether the user is blocked from using Special:Emailuser.
4199 public function isBlockedFromEmailuser() {
4200 $this->getBlockedStatus();
4201 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
4205 * Get whether the user is allowed to create an account.
4208 public function isAllowedToCreateAccount() {
4209 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
4213 * Get this user's personal page title.
4215 * @return Title User's personal page title
4217 public function getUserPage() {
4218 return Title
::makeTitle( NS_USER
, $this->getName() );
4222 * Get this user's talk page title.
4224 * @return Title User's talk page title
4226 public function getTalkPage() {
4227 $title = $this->getUserPage();
4228 return $title->getTalkPage();
4232 * Determine whether the user is a newbie. Newbies are either
4233 * anonymous IPs, or the most recently created accounts.
4236 public function isNewbie() {
4237 return !$this->isAllowed( 'autoconfirmed' );
4241 * Check to see if the given clear-text password is one of the accepted passwords
4242 * @deprecated since 1.27, use AuthManager instead
4243 * @param string $password User password
4244 * @return bool True if the given password is correct, otherwise False
4246 public function checkPassword( $password ) {
4247 global $wgAuth, $wgLegacyEncoding, $wgDisableAuthManager;
4249 if ( $wgDisableAuthManager ) {
4252 // Some passwords will give a fatal Status, which means there is
4253 // some sort of technical or security reason for this password to
4254 // be completely invalid and should never be checked (e.g., T64685)
4255 if ( !$this->checkPasswordValidity( $password )->isOK() ) {
4259 // Certain authentication plugins do NOT want to save
4260 // domain passwords in a mysql database, so we should
4261 // check this (in case $wgAuth->strict() is false).
4262 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
4264 } elseif ( $wgAuth->strict() ) {
4265 // Auth plugin doesn't allow local authentication
4267 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
4268 // Auth plugin doesn't allow local authentication for this user name
4272 $passwordFactory = new PasswordFactory();
4273 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4274 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
4275 ?
wfGetDB( DB_MASTER
)
4276 : wfGetDB( DB_SLAVE
);
4279 $mPassword = $passwordFactory->newFromCiphertext( $db->selectField(
4280 'user', 'user_password', [ 'user_id' => $this->getId() ], __METHOD__
4282 } catch ( PasswordError
$e ) {
4283 wfDebug( 'Invalid password hash found in database.' );
4284 $mPassword = PasswordFactory
::newInvalidPassword();
4287 if ( !$mPassword->equals( $password ) ) {
4288 if ( $wgLegacyEncoding ) {
4289 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
4290 // Check for this with iconv
4291 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
4292 if ( $cp1252Password === $password ||
!$mPassword->equals( $cp1252Password ) ) {
4300 if ( $passwordFactory->needsUpdate( $mPassword ) && !wfReadOnly() ) {
4301 $this->setPasswordInternal( $password );
4306 $manager = AuthManager
::singleton();
4307 $reqs = AuthenticationRequest
::loadRequestsFromSubmission(
4308 $manager->getAuthenticationRequests( AuthManager
::ACTION_LOGIN
),
4310 'username' => $this->getName(),
4311 'password' => $password,
4314 $res = AuthManager
::singleton()->beginAuthentication( $reqs, 'null:' );
4315 switch ( $res->status
) {
4316 case AuthenticationResponse
::PASS
:
4318 case AuthenticationResponse
::FAIL
:
4319 // Hope it's not a PreAuthenticationProvider that failed...
4320 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
4321 ->info( __METHOD__
. ': Authentication failed: ' . $res->message
->plain() );
4324 throw new BadMethodCallException(
4325 'AuthManager returned a response unsupported by ' . __METHOD__
4332 * Check if the given clear-text password matches the temporary password
4333 * sent by e-mail for password reset operations.
4335 * @deprecated since 1.27, use AuthManager instead
4336 * @param string $plaintext
4337 * @return bool True if matches, false otherwise
4339 public function checkTemporaryPassword( $plaintext ) {
4340 global $wgNewPasswordExpiry, $wgDisableAuthManager;
4342 if ( $wgDisableAuthManager ) {
4345 $passwordFactory = new PasswordFactory();
4346 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4347 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
4348 ?
wfGetDB( DB_MASTER
)
4349 : wfGetDB( DB_SLAVE
);
4351 $row = $db->selectRow(
4353 [ 'user_newpassword', 'user_newpass_time' ],
4354 [ 'user_id' => $this->getId() ],
4358 $newPassword = $passwordFactory->newFromCiphertext( $row->user_newpassword
);
4359 } catch ( PasswordError
$e ) {
4360 wfDebug( 'Invalid password hash found in database.' );
4361 $newPassword = PasswordFactory
::newInvalidPassword();
4364 if ( $newPassword->equals( $plaintext ) ) {
4365 if ( is_null( $row->user_newpass_time
) ) {
4368 $expiry = wfTimestamp( TS_UNIX
, $row->user_newpass_time
) +
$wgNewPasswordExpiry;
4369 return ( time() < $expiry );
4374 // Can't check the temporary password individually.
4375 return $this->checkPassword( $plaintext );
4380 * Initialize (if necessary) and return a session token value
4381 * which can be used in edit forms to show that the user's
4382 * login credentials aren't being hijacked with a foreign form
4386 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4387 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4388 * @return MediaWiki\Session\Token The new edit token
4390 public function getEditTokenObject( $salt = '', $request = null ) {
4391 if ( $this->isAnon() ) {
4392 return new LoggedOutEditToken();
4396 $request = $this->getRequest();
4398 return $request->getSession()->getToken( $salt );
4402 * Initialize (if necessary) and return a session token value
4403 * which can be used in edit forms to show that the user's
4404 * login credentials aren't being hijacked with a foreign form
4408 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4409 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4410 * @return string The new edit token
4412 public function getEditToken( $salt = '', $request = null ) {
4413 return $this->getEditTokenObject( $salt, $request )->toString();
4417 * Get the embedded timestamp from a token.
4418 * @deprecated since 1.27, use \MediaWiki\Session\Token::getTimestamp instead.
4419 * @param string $val Input token
4422 public static function getEditTokenTimestamp( $val ) {
4423 wfDeprecated( __METHOD__
, '1.27' );
4424 return MediaWiki\Session\Token
::getTimestamp( $val );
4428 * Check given value against the token value stored in the session.
4429 * A match should confirm that the form was submitted from the
4430 * user's own login session, not a form submission from a third-party
4433 * @param string $val Input value to compare
4434 * @param string $salt Optional function-specific data for hashing
4435 * @param WebRequest|null $request Object to use or null to use $wgRequest
4436 * @param int $maxage Fail tokens older than this, in seconds
4437 * @return bool Whether the token matches
4439 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4440 return $this->getEditTokenObject( $salt, $request )->match( $val, $maxage );
4444 * Check given value against the token value stored in the session,
4445 * ignoring the suffix.
4447 * @param string $val Input value to compare
4448 * @param string $salt Optional function-specific data for hashing
4449 * @param WebRequest|null $request Object to use or null to use $wgRequest
4450 * @param int $maxage Fail tokens older than this, in seconds
4451 * @return bool Whether the token matches
4453 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4454 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . Token
::SUFFIX
;
4455 return $this->matchEditToken( $val, $salt, $request, $maxage );
4459 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4460 * mail to the user's given address.
4462 * @param string $type Message to send, either "created", "changed" or "set"
4465 public function sendConfirmationMail( $type = 'created' ) {
4467 $expiration = null; // gets passed-by-ref and defined in next line.
4468 $token = $this->confirmationToken( $expiration );
4469 $url = $this->confirmationTokenUrl( $token );
4470 $invalidateURL = $this->invalidationTokenUrl( $token );
4471 $this->saveSettings();
4473 if ( $type == 'created' ||
$type === false ) {
4474 $message = 'confirmemail_body';
4475 } elseif ( $type === true ) {
4476 $message = 'confirmemail_body_changed';
4478 // Messages: confirmemail_body_changed, confirmemail_body_set
4479 $message = 'confirmemail_body_' . $type;
4482 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4483 wfMessage( $message,
4484 $this->getRequest()->getIP(),
4487 $wgLang->userTimeAndDate( $expiration, $this ),
4489 $wgLang->userDate( $expiration, $this ),
4490 $wgLang->userTime( $expiration, $this ) )->text() );
4494 * Send an e-mail to this user's account. Does not check for
4495 * confirmed status or validity.
4497 * @param string $subject Message subject
4498 * @param string $body Message body
4499 * @param User|null $from Optional sending user; if unspecified, default
4500 * $wgPasswordSender will be used.
4501 * @param string $replyto Reply-To address
4504 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4505 global $wgPasswordSender;
4507 if ( $from instanceof User
) {
4508 $sender = MailAddress
::newFromUser( $from );
4510 $sender = new MailAddress( $wgPasswordSender,
4511 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4513 $to = MailAddress
::newFromUser( $this );
4515 return UserMailer
::send( $to, $sender, $subject, $body, [
4516 'replyTo' => $replyto,
4521 * Generate, store, and return a new e-mail confirmation code.
4522 * A hash (unsalted, since it's used as a key) is stored.
4524 * @note Call saveSettings() after calling this function to commit
4525 * this change to the database.
4527 * @param string &$expiration Accepts the expiration time
4528 * @return string New token
4530 protected function confirmationToken( &$expiration ) {
4531 global $wgUserEmailConfirmationTokenExpiry;
4533 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4534 $expiration = wfTimestamp( TS_MW
, $expires );
4536 $token = MWCryptRand
::generateHex( 32 );
4537 $hash = md5( $token );
4538 $this->mEmailToken
= $hash;
4539 $this->mEmailTokenExpires
= $expiration;
4544 * Return a URL the user can use to confirm their email address.
4545 * @param string $token Accepts the email confirmation token
4546 * @return string New token URL
4548 protected function confirmationTokenUrl( $token ) {
4549 return $this->getTokenUrl( 'ConfirmEmail', $token );
4553 * Return a URL the user can use to invalidate their email address.
4554 * @param string $token Accepts the email confirmation token
4555 * @return string New token URL
4557 protected function invalidationTokenUrl( $token ) {
4558 return $this->getTokenUrl( 'InvalidateEmail', $token );
4562 * Internal function to format the e-mail validation/invalidation URLs.
4563 * This uses a quickie hack to use the
4564 * hardcoded English names of the Special: pages, for ASCII safety.
4566 * @note Since these URLs get dropped directly into emails, using the
4567 * short English names avoids insanely long URL-encoded links, which
4568 * also sometimes can get corrupted in some browsers/mailers
4569 * (bug 6957 with Gmail and Internet Explorer).
4571 * @param string $page Special page
4572 * @param string $token Token
4573 * @return string Formatted URL
4575 protected function getTokenUrl( $page, $token ) {
4576 // Hack to bypass localization of 'Special:'
4577 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4578 return $title->getCanonicalURL();
4582 * Mark the e-mail address confirmed.
4584 * @note Call saveSettings() after calling this function to commit the change.
4588 public function confirmEmail() {
4589 // Check if it's already confirmed, so we don't touch the database
4590 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4591 if ( !$this->isEmailConfirmed() ) {
4592 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4593 Hooks
::run( 'ConfirmEmailComplete', [ $this ] );
4599 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4600 * address if it was already confirmed.
4602 * @note Call saveSettings() after calling this function to commit the change.
4603 * @return bool Returns true
4605 public function invalidateEmail() {
4607 $this->mEmailToken
= null;
4608 $this->mEmailTokenExpires
= null;
4609 $this->setEmailAuthenticationTimestamp( null );
4611 Hooks
::run( 'InvalidateEmailComplete', [ $this ] );
4616 * Set the e-mail authentication timestamp.
4617 * @param string $timestamp TS_MW timestamp
4619 public function setEmailAuthenticationTimestamp( $timestamp ) {
4621 $this->mEmailAuthenticated
= $timestamp;
4622 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
4626 * Is this user allowed to send e-mails within limits of current
4627 * site configuration?
4630 public function canSendEmail() {
4631 global $wgEnableEmail, $wgEnableUserEmail;
4632 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4635 $canSend = $this->isEmailConfirmed();
4636 Hooks
::run( 'UserCanSendEmail', [ &$this, &$canSend ] );
4641 * Is this user allowed to receive e-mails within limits of current
4642 * site configuration?
4645 public function canReceiveEmail() {
4646 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4650 * Is this user's e-mail address valid-looking and confirmed within
4651 * limits of the current site configuration?
4653 * @note If $wgEmailAuthentication is on, this may require the user to have
4654 * confirmed their address by returning a code or using a password
4655 * sent to the address from the wiki.
4659 public function isEmailConfirmed() {
4660 global $wgEmailAuthentication;
4663 if ( Hooks
::run( 'EmailConfirmed', [ &$this, &$confirmed ] ) ) {
4664 if ( $this->isAnon() ) {
4667 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4670 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4680 * Check whether there is an outstanding request for e-mail confirmation.
4683 public function isEmailConfirmationPending() {
4684 global $wgEmailAuthentication;
4685 return $wgEmailAuthentication &&
4686 !$this->isEmailConfirmed() &&
4687 $this->mEmailToken
&&
4688 $this->mEmailTokenExpires
> wfTimestamp();
4692 * Get the timestamp of account creation.
4694 * @return string|bool|null Timestamp of account creation, false for
4695 * non-existent/anonymous user accounts, or null if existing account
4696 * but information is not in database.
4698 public function getRegistration() {
4699 if ( $this->isAnon() ) {
4703 return $this->mRegistration
;
4707 * Get the timestamp of the first edit
4709 * @return string|bool Timestamp of first edit, or false for
4710 * non-existent/anonymous user accounts.
4712 public function getFirstEditTimestamp() {
4713 if ( $this->getId() == 0 ) {
4714 return false; // anons
4716 $dbr = wfGetDB( DB_SLAVE
);
4717 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4718 [ 'rev_user' => $this->getId() ],
4720 [ 'ORDER BY' => 'rev_timestamp ASC' ]
4723 return false; // no edits
4725 return wfTimestamp( TS_MW
, $time );
4729 * Get the permissions associated with a given list of groups
4731 * @param array $groups Array of Strings List of internal group names
4732 * @return array Array of Strings List of permission key names for given groups combined
4734 public static function getGroupPermissions( $groups ) {
4735 global $wgGroupPermissions, $wgRevokePermissions;
4737 // grant every granted permission first
4738 foreach ( $groups as $group ) {
4739 if ( isset( $wgGroupPermissions[$group] ) ) {
4740 $rights = array_merge( $rights,
4741 // array_filter removes empty items
4742 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4745 // now revoke the revoked permissions
4746 foreach ( $groups as $group ) {
4747 if ( isset( $wgRevokePermissions[$group] ) ) {
4748 $rights = array_diff( $rights,
4749 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4752 return array_unique( $rights );
4756 * Get all the groups who have a given permission
4758 * @param string $role Role to check
4759 * @return array Array of Strings List of internal group names with the given permission
4761 public static function getGroupsWithPermission( $role ) {
4762 global $wgGroupPermissions;
4763 $allowedGroups = [];
4764 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4765 if ( self
::groupHasPermission( $group, $role ) ) {
4766 $allowedGroups[] = $group;
4769 return $allowedGroups;
4773 * Check, if the given group has the given permission
4775 * If you're wanting to check whether all users have a permission, use
4776 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4780 * @param string $group Group to check
4781 * @param string $role Role to check
4784 public static function groupHasPermission( $group, $role ) {
4785 global $wgGroupPermissions, $wgRevokePermissions;
4786 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4787 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4791 * Check if all users may be assumed to have the given permission
4793 * We generally assume so if the right is granted to '*' and isn't revoked
4794 * on any group. It doesn't attempt to take grants or other extension
4795 * limitations on rights into account in the general case, though, as that
4796 * would require it to always return false and defeat the purpose.
4797 * Specifically, session-based rights restrictions (such as OAuth or bot
4798 * passwords) are applied based on the current session.
4801 * @param string $right Right to check
4804 public static function isEveryoneAllowed( $right ) {
4805 global $wgGroupPermissions, $wgRevokePermissions;
4808 // Use the cached results, except in unit tests which rely on
4809 // being able change the permission mid-request
4810 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4811 return $cache[$right];
4814 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4815 $cache[$right] = false;
4819 // If it's revoked anywhere, then everyone doesn't have it
4820 foreach ( $wgRevokePermissions as $rights ) {
4821 if ( isset( $rights[$right] ) && $rights[$right] ) {
4822 $cache[$right] = false;
4827 // Remove any rights that aren't allowed to the global-session user,
4828 // unless there are no sessions for this endpoint.
4829 if ( !defined( 'MW_NO_SESSION' ) ) {
4830 $allowedRights = SessionManager
::getGlobalSession()->getAllowedUserRights();
4831 if ( $allowedRights !== null && !in_array( $right, $allowedRights, true ) ) {
4832 $cache[$right] = false;
4837 // Allow extensions to say false
4838 if ( !Hooks
::run( 'UserIsEveryoneAllowed', [ $right ] ) ) {
4839 $cache[$right] = false;
4843 $cache[$right] = true;
4848 * Get the localized descriptive name for a group, if it exists
4850 * @param string $group Internal group name
4851 * @return string Localized descriptive group name
4853 public static function getGroupName( $group ) {
4854 $msg = wfMessage( "group-$group" );
4855 return $msg->isBlank() ?
$group : $msg->text();
4859 * Get the localized descriptive name for a member of a group, if it exists
4861 * @param string $group Internal group name
4862 * @param string $username Username for gender (since 1.19)
4863 * @return string Localized name for group member
4865 public static function getGroupMember( $group, $username = '#' ) {
4866 $msg = wfMessage( "group-$group-member", $username );
4867 return $msg->isBlank() ?
$group : $msg->text();
4871 * Return the set of defined explicit groups.
4872 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4873 * are not included, as they are defined automatically, not in the database.
4874 * @return array Array of internal group names
4876 public static function getAllGroups() {
4877 global $wgGroupPermissions, $wgRevokePermissions;
4879 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4880 self
::getImplicitGroups()
4885 * Get a list of all available permissions.
4886 * @return string[] Array of permission names
4888 public static function getAllRights() {
4889 if ( self
::$mAllRights === false ) {
4890 global $wgAvailableRights;
4891 if ( count( $wgAvailableRights ) ) {
4892 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
4894 self
::$mAllRights = self
::$mCoreRights;
4896 Hooks
::run( 'UserGetAllRights', [ &self
::$mAllRights ] );
4898 return self
::$mAllRights;
4902 * Get a list of implicit groups
4903 * @return array Array of Strings Array of internal group names
4905 public static function getImplicitGroups() {
4906 global $wgImplicitGroups;
4908 $groups = $wgImplicitGroups;
4909 # Deprecated, use $wgImplicitGroups instead
4910 Hooks
::run( 'UserGetImplicitGroups', [ &$groups ], '1.25' );
4916 * Get the title of a page describing a particular group
4918 * @param string $group Internal group name
4919 * @return Title|bool Title of the page if it exists, false otherwise
4921 public static function getGroupPage( $group ) {
4922 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4923 if ( $msg->exists() ) {
4924 $title = Title
::newFromText( $msg->text() );
4925 if ( is_object( $title ) ) {
4933 * Create a link to the group in HTML, if available;
4934 * else return the group name.
4936 * @param string $group Internal name of the group
4937 * @param string $text The text of the link
4938 * @return string HTML link to the group
4940 public static function makeGroupLinkHTML( $group, $text = '' ) {
4941 if ( $text == '' ) {
4942 $text = self
::getGroupName( $group );
4944 $title = self
::getGroupPage( $group );
4946 return Linker
::link( $title, htmlspecialchars( $text ) );
4948 return htmlspecialchars( $text );
4953 * Create a link to the group in Wikitext, if available;
4954 * else return the group name.
4956 * @param string $group Internal name of the group
4957 * @param string $text The text of the link
4958 * @return string Wikilink to the group
4960 public static function makeGroupLinkWiki( $group, $text = '' ) {
4961 if ( $text == '' ) {
4962 $text = self
::getGroupName( $group );
4964 $title = self
::getGroupPage( $group );
4966 $page = $title->getFullText();
4967 return "[[$page|$text]]";
4974 * Returns an array of the groups that a particular group can add/remove.
4976 * @param string $group The group to check for whether it can add/remove
4977 * @return array Array( 'add' => array( addablegroups ),
4978 * 'remove' => array( removablegroups ),
4979 * 'add-self' => array( addablegroups to self),
4980 * 'remove-self' => array( removable groups from self) )
4982 public static function changeableByGroup( $group ) {
4983 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4992 if ( empty( $wgAddGroups[$group] ) ) {
4993 // Don't add anything to $groups
4994 } elseif ( $wgAddGroups[$group] === true ) {
4995 // You get everything
4996 $groups['add'] = self
::getAllGroups();
4997 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4998 $groups['add'] = $wgAddGroups[$group];
5001 // Same thing for remove
5002 if ( empty( $wgRemoveGroups[$group] ) ) {
5004 } elseif ( $wgRemoveGroups[$group] === true ) {
5005 $groups['remove'] = self
::getAllGroups();
5006 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
5007 $groups['remove'] = $wgRemoveGroups[$group];
5010 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
5011 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
5012 foreach ( $wgGroupsAddToSelf as $key => $value ) {
5013 if ( is_int( $key ) ) {
5014 $wgGroupsAddToSelf['user'][] = $value;
5019 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
5020 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
5021 if ( is_int( $key ) ) {
5022 $wgGroupsRemoveFromSelf['user'][] = $value;
5027 // Now figure out what groups the user can add to him/herself
5028 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
5030 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
5031 // No idea WHY this would be used, but it's there
5032 $groups['add-self'] = User
::getAllGroups();
5033 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
5034 $groups['add-self'] = $wgGroupsAddToSelf[$group];
5037 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
5039 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
5040 $groups['remove-self'] = User
::getAllGroups();
5041 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
5042 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
5049 * Returns an array of groups that this user can add and remove
5050 * @return array Array( 'add' => array( addablegroups ),
5051 * 'remove' => array( removablegroups ),
5052 * 'add-self' => array( addablegroups to self),
5053 * 'remove-self' => array( removable groups from self) )
5055 public function changeableGroups() {
5056 if ( $this->isAllowed( 'userrights' ) ) {
5057 // This group gives the right to modify everything (reverse-
5058 // compatibility with old "userrights lets you change
5060 // Using array_merge to make the groups reindexed
5061 $all = array_merge( User
::getAllGroups() );
5070 // Okay, it's not so simple, we will have to go through the arrays
5077 $addergroups = $this->getEffectiveGroups();
5079 foreach ( $addergroups as $addergroup ) {
5080 $groups = array_merge_recursive(
5081 $groups, $this->changeableByGroup( $addergroup )
5083 $groups['add'] = array_unique( $groups['add'] );
5084 $groups['remove'] = array_unique( $groups['remove'] );
5085 $groups['add-self'] = array_unique( $groups['add-self'] );
5086 $groups['remove-self'] = array_unique( $groups['remove-self'] );
5092 * Deferred version of incEditCountImmediate()
5094 public function incEditCount() {
5095 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle( function() {
5096 $this->incEditCountImmediate();
5101 * Increment the user's edit-count field.
5102 * Will have no effect for anonymous users.
5105 public function incEditCountImmediate() {
5106 if ( $this->isAnon() ) {
5110 $dbw = wfGetDB( DB_MASTER
);
5111 // No rows will be "affected" if user_editcount is NULL
5114 [ 'user_editcount=user_editcount+1' ],
5115 [ 'user_id' => $this->getId(), 'user_editcount IS NOT NULL' ],
5118 // Lazy initialization check...
5119 if ( $dbw->affectedRows() == 0 ) {
5120 // Now here's a goddamn hack...
5121 $dbr = wfGetDB( DB_SLAVE
);
5122 if ( $dbr !== $dbw ) {
5123 // If we actually have a slave server, the count is
5124 // at least one behind because the current transaction
5125 // has not been committed and replicated.
5126 $this->initEditCount( 1 );
5128 // But if DB_SLAVE is selecting the master, then the
5129 // count we just read includes the revision that was
5130 // just added in the working transaction.
5131 $this->initEditCount();
5134 // Edit count in user cache too
5135 $this->invalidateCache();
5139 * Initialize user_editcount from data out of the revision table
5141 * @param int $add Edits to add to the count from the revision table
5142 * @return int Number of edits
5144 protected function initEditCount( $add = 0 ) {
5145 // Pull from a slave to be less cruel to servers
5146 // Accuracy isn't the point anyway here
5147 $dbr = wfGetDB( DB_SLAVE
);
5148 $count = (int)$dbr->selectField(
5151 [ 'rev_user' => $this->getId() ],
5154 $count = $count +
$add;
5156 $dbw = wfGetDB( DB_MASTER
);
5159 [ 'user_editcount' => $count ],
5160 [ 'user_id' => $this->getId() ],
5168 * Get the description of a given right
5170 * @param string $right Right to query
5171 * @return string Localized description of the right
5173 public static function getRightDescription( $right ) {
5174 $key = "right-$right";
5175 $msg = wfMessage( $key );
5176 return $msg->isBlank() ?
$right : $msg->text();
5180 * Make a new-style password hash
5182 * @param string $password Plain-text password
5183 * @param bool|string $salt Optional salt, may be random or the user ID.
5184 * If unspecified or false, will generate one automatically
5185 * @return string Password hash
5186 * @deprecated since 1.24, use Password class
5188 public static function crypt( $password, $salt = false ) {
5189 wfDeprecated( __METHOD__
, '1.24' );
5190 $passwordFactory = new PasswordFactory();
5191 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
5192 $hash = $passwordFactory->newFromPlaintext( $password );
5193 return $hash->toString();
5197 * Compare a password hash with a plain-text password. Requires the user
5198 * ID if there's a chance that the hash is an old-style hash.
5200 * @param string $hash Password hash
5201 * @param string $password Plain-text password to compare
5202 * @param string|bool $userId User ID for old-style password salt
5205 * @deprecated since 1.24, use Password class
5207 public static function comparePasswords( $hash, $password, $userId = false ) {
5208 wfDeprecated( __METHOD__
, '1.24' );
5210 // Check for *really* old password hashes that don't even have a type
5211 // The old hash format was just an md5 hex hash, with no type information
5212 if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) {
5213 global $wgPasswordSalt;
5214 if ( $wgPasswordSalt ) {
5215 $password = ":B:{$userId}:{$hash}";
5217 $password = ":A:{$hash}";
5221 $passwordFactory = new PasswordFactory();
5222 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
5223 $hash = $passwordFactory->newFromCiphertext( $hash );
5224 return $hash->equals( $password );
5228 * Add a newuser log entry for this user.
5229 * Before 1.19 the return value was always true.
5231 * @deprecated since 1.27, AuthManager handles logging
5232 * @param string|bool $action Account creation type.
5233 * - String, one of the following values:
5234 * - 'create' for an anonymous user creating an account for himself.
5235 * This will force the action's performer to be the created user itself,
5236 * no matter the value of $wgUser
5237 * - 'create2' for a logged in user creating an account for someone else
5238 * - 'byemail' when the created user will receive its password by e-mail
5239 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
5240 * - Boolean means whether the account was created by e-mail (deprecated):
5241 * - true will be converted to 'byemail'
5242 * - false will be converted to 'create' if this object is the same as
5243 * $wgUser and to 'create2' otherwise
5244 * @param string $reason User supplied reason
5245 * @return int|bool True if not $wgNewUserLog or not $wgDisableAuthManager;
5246 * otherwise ID of log item or 0 on failure
5248 public function addNewUserLogEntry( $action = false, $reason = '' ) {
5249 global $wgUser, $wgNewUserLog, $wgDisableAuthManager;
5250 if ( !$wgDisableAuthManager ||
empty( $wgNewUserLog ) ) {
5251 return true; // disabled
5254 if ( $action === true ) {
5255 $action = 'byemail';
5256 } elseif ( $action === false ) {
5257 if ( $this->equals( $wgUser ) ) {
5260 $action = 'create2';
5264 if ( $action === 'create' ||
$action === 'autocreate' ) {
5267 $performer = $wgUser;
5270 $logEntry = new ManualLogEntry( 'newusers', $action );
5271 $logEntry->setPerformer( $performer );
5272 $logEntry->setTarget( $this->getUserPage() );
5273 $logEntry->setComment( $reason );
5274 $logEntry->setParameters( [
5275 '4::userid' => $this->getId(),
5277 $logid = $logEntry->insert();
5279 if ( $action !== 'autocreate' ) {
5280 $logEntry->publish( $logid );
5287 * Add an autocreate newuser log entry for this user
5288 * Used by things like CentralAuth and perhaps other authplugins.
5289 * Consider calling addNewUserLogEntry() directly instead.
5291 * @deprecated since 1.27, AuthManager handles logging
5294 public function addNewUserLogEntryAutoCreate() {
5295 $this->addNewUserLogEntry( 'autocreate' );
5301 * Load the user options either from cache, the database or an array
5303 * @param array $data Rows for the current user out of the user_properties table
5305 protected function loadOptions( $data = null ) {
5310 if ( $this->mOptionsLoaded
) {
5314 $this->mOptions
= self
::getDefaultOptions();
5316 if ( !$this->getId() ) {
5317 // For unlogged-in users, load language/variant options from request.
5318 // There's no need to do it for logged-in users: they can set preferences,
5319 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5320 // so don't override user's choice (especially when the user chooses site default).
5321 $variant = $wgContLang->getDefaultVariant();
5322 $this->mOptions
['variant'] = $variant;
5323 $this->mOptions
['language'] = $variant;
5324 $this->mOptionsLoaded
= true;
5328 // Maybe load from the object
5329 if ( !is_null( $this->mOptionOverrides
) ) {
5330 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5331 foreach ( $this->mOptionOverrides
as $key => $value ) {
5332 $this->mOptions
[$key] = $value;
5335 if ( !is_array( $data ) ) {
5336 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5337 // Load from database
5338 $dbr = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
5339 ?
wfGetDB( DB_MASTER
)
5340 : wfGetDB( DB_SLAVE
);
5342 $res = $dbr->select(
5344 [ 'up_property', 'up_value' ],
5345 [ 'up_user' => $this->getId() ],
5349 $this->mOptionOverrides
= [];
5351 foreach ( $res as $row ) {
5352 $data[$row->up_property
] = $row->up_value
;
5355 foreach ( $data as $property => $value ) {
5356 $this->mOptionOverrides
[$property] = $value;
5357 $this->mOptions
[$property] = $value;
5361 $this->mOptionsLoaded
= true;
5363 Hooks
::run( 'UserLoadOptions', [ $this, &$this->mOptions
] );
5367 * Saves the non-default options for this user, as previously set e.g. via
5368 * setOption(), in the database's "user_properties" (preferences) table.
5369 * Usually used via saveSettings().
5371 protected function saveOptions() {
5372 $this->loadOptions();
5374 // Not using getOptions(), to keep hidden preferences in database
5375 $saveOptions = $this->mOptions
;
5377 // Allow hooks to abort, for instance to save to a global profile.
5378 // Reset options to default state before saving.
5379 if ( !Hooks
::run( 'UserSaveOptions', [ $this, &$saveOptions ] ) ) {
5383 $userId = $this->getId();
5385 $insert_rows = []; // all the new preference rows
5386 foreach ( $saveOptions as $key => $value ) {
5387 // Don't bother storing default values
5388 $defaultOption = self
::getDefaultOption( $key );
5389 if ( ( $defaultOption === null && $value !== false && $value !== null )
5390 ||
$value != $defaultOption
5393 'up_user' => $userId,
5394 'up_property' => $key,
5395 'up_value' => $value,
5400 $dbw = wfGetDB( DB_MASTER
);
5402 $res = $dbw->select( 'user_properties',
5403 [ 'up_property', 'up_value' ], [ 'up_user' => $userId ], __METHOD__
);
5405 // Find prior rows that need to be removed or updated. These rows will
5406 // all be deleted (the later so that INSERT IGNORE applies the new values).
5408 foreach ( $res as $row ) {
5409 if ( !isset( $saveOptions[$row->up_property
] )
5410 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
5412 $keysDelete[] = $row->up_property
;
5416 if ( count( $keysDelete ) ) {
5417 // Do the DELETE by PRIMARY KEY for prior rows.
5418 // In the past a very large portion of calls to this function are for setting
5419 // 'rememberpassword' for new accounts (a preference that has since been removed).
5420 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5421 // caused gap locks on [max user ID,+infinity) which caused high contention since
5422 // updates would pile up on each other as they are for higher (newer) user IDs.
5423 // It might not be necessary these days, but it shouldn't hurt either.
5424 $dbw->delete( 'user_properties',
5425 [ 'up_user' => $userId, 'up_property' => $keysDelete ], __METHOD__
);
5427 // Insert the new preference rows
5428 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, [ 'IGNORE' ] );
5432 * Lazily instantiate and return a factory object for making passwords
5434 * @deprecated since 1.27, create a PasswordFactory directly instead
5435 * @return PasswordFactory
5437 public static function getPasswordFactory() {
5438 wfDeprecated( __METHOD__
, '1.27' );
5439 $ret = new PasswordFactory();
5440 $ret->init( RequestContext
::getMain()->getConfig() );
5445 * Provide an array of HTML5 attributes to put on an input element
5446 * intended for the user to enter a new password. This may include
5447 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
5449 * Do *not* use this when asking the user to enter his current password!
5450 * Regardless of configuration, users may have invalid passwords for whatever
5451 * reason (e.g., they were set before requirements were tightened up).
5452 * Only use it when asking for a new password, like on account creation or
5455 * Obviously, you still need to do server-side checking.
5457 * NOTE: A combination of bugs in various browsers means that this function
5458 * actually just returns array() unconditionally at the moment. May as
5459 * well keep it around for when the browser bugs get fixed, though.
5461 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
5463 * @deprecated since 1.27
5464 * @return array Array of HTML attributes suitable for feeding to
5465 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
5466 * That will get confused by the boolean attribute syntax used.)
5468 public static function passwordChangeInputAttribs() {
5469 global $wgMinimalPasswordLength;
5471 if ( $wgMinimalPasswordLength == 0 ) {
5475 # Note that the pattern requirement will always be satisfied if the
5476 # input is empty, so we need required in all cases.
5478 # @todo FIXME: Bug 23769: This needs to not claim the password is required
5479 # if e-mail confirmation is being used. Since HTML5 input validation
5480 # is b0rked anyway in some browsers, just return nothing. When it's
5481 # re-enabled, fix this code to not output required for e-mail
5483 # $ret = array( 'required' );
5486 # We can't actually do this right now, because Opera 9.6 will print out
5487 # the entered password visibly in its error message! When other
5488 # browsers add support for this attribute, or Opera fixes its support,
5489 # we can add support with a version check to avoid doing this on Opera
5490 # versions where it will be a problem. Reported to Opera as
5491 # DSK-262266, but they don't have a public bug tracker for us to follow.
5493 if ( $wgMinimalPasswordLength > 1 ) {
5494 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
5495 $ret['title'] = wfMessage( 'passwordtooshort' )
5496 ->numParams( $wgMinimalPasswordLength )->text();
5504 * Return the list of user fields that should be selected to create
5505 * a new user object.
5508 public static function selectFields() {
5516 'user_email_authenticated',
5518 'user_email_token_expires',
5519 'user_registration',
5525 * Factory function for fatal permission-denied errors
5528 * @param string $permission User right required
5531 static function newFatalPermissionDeniedStatus( $permission ) {
5534 $groups = array_map(
5535 [ 'User', 'makeGroupLinkWiki' ],
5536 User
::getGroupsWithPermission( $permission )
5540 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5542 return Status
::newFatal( 'badaccess-group0' );
5547 * Get a new instance of this user that was loaded from the master via a locking read
5549 * Use this instead of the main context User when updating that user. This avoids races
5550 * where that user was loaded from a slave or even the master but without proper locks.
5552 * @return User|null Returns null if the user was not found in the DB
5555 public function getInstanceForUpdate() {
5556 if ( !$this->getId() ) {
5557 return null; // anon
5560 $user = self
::newFromId( $this->getId() );
5561 if ( !$user->loadFromId( self
::READ_EXCLUSIVE
) ) {
5569 * Checks if two user objects point to the same user.
5575 public function equals( User
$user ) {
5576 return $this->getName() === $user->getName();