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;
202 * An in-process cache for user data lookup
205 protected static $inProcessCache;
207 /** Cache variables */
218 /** @var string TS_MW timestamp from the DB */
220 /** @var string TS_MW timestamp from cache */
221 protected $mQuickTouched;
225 public $mEmailAuthenticated;
227 protected $mEmailToken;
229 protected $mEmailTokenExpires;
231 protected $mRegistration;
233 protected $mEditCount;
237 protected $mOptionOverrides;
241 * Bool Whether the cache variables have been loaded.
244 public $mOptionsLoaded;
247 * Array with already loaded items or true if all items have been loaded.
249 protected $mLoadedItems = [];
253 * String Initialization data source if mLoadedItems!==true. May be one of:
254 * - 'defaults' anonymous user initialised from class defaults
255 * - 'name' initialise from mName
256 * - 'id' initialise from mId
257 * - 'session' log in from session if possible
259 * Use the User::newFrom*() family of functions to set this.
264 * Lazy-initialized variables, invalidated with clearInstanceCache
268 protected $mDatePreference;
276 protected $mBlockreason;
278 protected $mEffectiveGroups;
280 protected $mImplicitGroups;
282 protected $mFormerGroups;
284 protected $mGlobalBlock;
301 protected $mAllowUsertalk;
304 private $mBlockedFromCreateAccount = false;
306 /** @var integer User::READ_* constant bitfield used to load data */
307 protected $queryFlagsUsed = self
::READ_NORMAL
;
309 public static $idCacheByName = [];
312 * Lightweight constructor for an anonymous user.
313 * Use the User::newFrom* factory functions for other kinds of users.
317 * @see newFromConfirmationCode()
318 * @see newFromSession()
321 public function __construct() {
322 $this->clearInstanceCache( 'defaults' );
328 public function __toString() {
329 return $this->getName();
333 * Test if it's safe to load this User object.
335 * You should typically check this before using $wgUser or
336 * RequestContext::getUser in a method that might be called before the
337 * system has been fully initialized. If the object is unsafe, you should
338 * use an anonymous user:
340 * $user = $wgUser->isSafeToLoad() ? $wgUser : new User;
346 public function isSafeToLoad() {
347 global $wgFullyInitialised;
349 // The user is safe to load if:
350 // * MW_NO_SESSION is undefined AND $wgFullyInitialised is true (safe to use session data)
351 // * mLoadedItems === true (already loaded)
352 // * mFrom !== 'session' (sessions not involved at all)
354 return ( !defined( 'MW_NO_SESSION' ) && $wgFullyInitialised ) ||
355 $this->mLoadedItems
=== true ||
$this->mFrom
!== 'session';
359 * Load the user table data for this object from the source given by mFrom.
361 * @param integer $flags User::READ_* constant bitfield
363 public function load( $flags = self
::READ_NORMAL
) {
364 global $wgFullyInitialised;
366 if ( $this->mLoadedItems
=== true ) {
370 // Set it now to avoid infinite recursion in accessors
371 $oldLoadedItems = $this->mLoadedItems
;
372 $this->mLoadedItems
= true;
373 $this->queryFlagsUsed
= $flags;
375 // If this is called too early, things are likely to break.
376 if ( !$wgFullyInitialised && $this->mFrom
=== 'session' ) {
377 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
378 ->warning( 'User::loadFromSession called before the end of Setup.php', [
379 'exception' => new Exception( 'User::loadFromSession called before the end of Setup.php' ),
381 $this->loadDefaults();
382 $this->mLoadedItems
= $oldLoadedItems;
386 switch ( $this->mFrom
) {
388 $this->loadDefaults();
391 // Make sure this thread sees its own changes
392 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
393 $flags |
= self
::READ_LATEST
;
394 $this->queryFlagsUsed
= $flags;
397 $this->mId
= self
::idFromName( $this->mName
, $flags );
399 // Nonexistent user placeholder object
400 $this->loadDefaults( $this->mName
);
402 $this->loadFromId( $flags );
406 $this->loadFromId( $flags );
409 if ( !$this->loadFromSession() ) {
410 // Loading from session failed. Load defaults.
411 $this->loadDefaults();
413 Hooks
::run( 'UserLoadAfterLoadFromSession', [ $this ] );
416 throw new UnexpectedValueException(
417 "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
422 * Load user table data, given mId has already been set.
423 * @param integer $flags User::READ_* constant bitfield
424 * @return bool False if the ID does not exist, true otherwise
426 public function loadFromId( $flags = self
::READ_NORMAL
) {
427 if ( $this->mId
== 0 ) {
428 $this->loadDefaults();
432 // Try cache (unless this needs data from the master DB).
433 // NOTE: if this thread called saveSettings(), the cache was cleared.
434 $latest = DBAccessObjectUtils
::hasFlags( $flags, self
::READ_LATEST
);
435 if ( $latest ||
!$this->loadFromCache() ) {
436 wfDebug( "User: cache miss for user {$this->mId}\n" );
437 // Load from DB (make sure this thread sees its own changes)
438 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
439 $flags |
= self
::READ_LATEST
;
441 if ( !$this->loadFromDatabase( $flags ) ) {
442 // Can't load from ID, user is anonymous
445 $this->saveToCache();
448 $this->mLoadedItems
= true;
449 $this->queryFlagsUsed
= $flags;
456 * @param string $wikiId
457 * @param integer $userId
459 public static function purge( $wikiId, $userId ) {
460 $cache = ObjectCache
::getMainWANInstance();
461 $processCache = self
::getInProcessCache();
462 $key = $cache->makeGlobalKey( 'user', 'id', $wikiId, $userId );
463 $cache->delete( $key );
464 $processCache->delete( $key );
469 * @param WANObjectCache $cache
472 protected function getCacheKey( WANObjectCache
$cache ) {
473 return $cache->makeGlobalKey( 'user', 'id', wfWikiID(), $this->mId
);
478 * @return HashBagOStuff
480 protected static function getInProcessCache() {
481 if ( !self
::$inProcessCache ) {
482 self
::$inProcessCache = new HashBagOStuff( [ 'maxKeys' => 10 ] );
484 return self
::$inProcessCache;
488 * Load user data from shared cache, given mId has already been set.
490 * @return bool false if the ID does not exist or data is invalid, true otherwise
493 protected function loadFromCache() {
494 if ( $this->mId
== 0 ) {
495 $this->loadDefaults();
499 $cache = ObjectCache
::getMainWANInstance();
500 $processCache = self
::getInProcessCache();
501 $key = $this->getCacheKey( $cache );
502 $data = $processCache->get( $key );
503 if ( !is_array( $data ) ) {
504 $data = $cache->get( $key );
505 if ( !is_array( $data )
506 ||
!isset( $data['mVersion'] )
507 ||
$data['mVersion'] < self
::VERSION
512 $processCache->set( $key, $data );
514 wfDebug( "User: got user {$this->mId} from cache\n" );
516 // Restore from cache
517 foreach ( self
::$mCacheVars as $name ) {
518 $this->$name = $data[$name];
525 * Save user data to the shared cache
527 * This method should not be called outside the User class
529 public function saveToCache() {
532 $this->loadOptions();
534 if ( $this->isAnon() ) {
535 // Anonymous users are uncached
540 foreach ( self
::$mCacheVars as $name ) {
541 $data[$name] = $this->$name;
543 $data['mVersion'] = self
::VERSION
;
544 $opts = Database
::getCacheSetOptions( wfGetDB( DB_SLAVE
) );
546 $cache = ObjectCache
::getMainWANInstance();
547 $processCache = self
::getInProcessCache();
548 $key = $this->getCacheKey( $cache );
549 $cache->set( $key, $data, $cache::TTL_HOUR
, $opts );
550 $processCache->set( $key, $data );
553 /** @name newFrom*() static factory methods */
557 * Static factory method for creation from username.
559 * This is slightly less efficient than newFromId(), so use newFromId() if
560 * you have both an ID and a name handy.
562 * @param string $name Username, validated by Title::newFromText()
563 * @param string|bool $validate Validate username. Takes the same parameters as
564 * User::getCanonicalName(), except that true is accepted as an alias
565 * for 'valid', for BC.
567 * @return User|bool User object, or false if the username is invalid
568 * (e.g. if it contains illegal characters or is an IP address). If the
569 * username is not present in the database, the result will be a user object
570 * with a name, zero user ID and default settings.
572 public static function newFromName( $name, $validate = 'valid' ) {
573 if ( $validate === true ) {
576 $name = self
::getCanonicalName( $name, $validate );
577 if ( $name === false ) {
580 // Create unloaded user object
584 $u->setItemLoaded( 'name' );
590 * Static factory method for creation from a given user ID.
592 * @param int $id Valid user ID
593 * @return User The corresponding User object
595 public static function newFromId( $id ) {
599 $u->setItemLoaded( 'id' );
604 * Factory method to fetch whichever user has a given email confirmation code.
605 * This code is generated when an account is created or its e-mail address
608 * If the code is invalid or has expired, returns NULL.
610 * @param string $code Confirmation code
611 * @param int $flags User::READ_* bitfield
614 public static function newFromConfirmationCode( $code, $flags = 0 ) {
615 $db = ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
616 ?
wfGetDB( DB_MASTER
)
617 : wfGetDB( DB_SLAVE
);
619 $id = $db->selectField(
623 'user_email_token' => md5( $code ),
624 'user_email_token_expires > ' . $db->addQuotes( $db->timestamp() ),
628 return $id ? User
::newFromId( $id ) : null;
632 * Create a new user object using data from session. If the login
633 * credentials are invalid, the result is an anonymous user.
635 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
638 public static function newFromSession( WebRequest
$request = null ) {
640 $user->mFrom
= 'session';
641 $user->mRequest
= $request;
646 * Create a new user object from a user row.
647 * The row should have the following fields from the user table in it:
648 * - either user_name or user_id to load further data if needed (or both)
650 * - all other fields (email, etc.)
651 * It is useless to provide the remaining fields if either user_id,
652 * user_name and user_real_name are not provided because the whole row
653 * will be loaded once more from the database when accessing them.
655 * @param stdClass $row A row from the user table
656 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
659 public static function newFromRow( $row, $data = null ) {
661 $user->loadFromRow( $row, $data );
666 * Static factory method for creation of a "system" user from username.
668 * A "system" user is an account that's used to attribute logged actions
669 * taken by MediaWiki itself, as opposed to a bot or human user. Examples
670 * might include the 'Maintenance script' or 'Conversion script' accounts
671 * used by various scripts in the maintenance/ directory or accounts such
672 * as 'MediaWiki message delivery' used by the MassMessage extension.
674 * This can optionally create the user if it doesn't exist, and "steal" the
675 * account if it does exist.
677 * "Stealing" an existing user is intended to make it impossible for normal
678 * authentication processes to use the account, effectively disabling the
679 * account for normal use:
680 * - Email is invalidated, to prevent account recovery by emailing a
681 * temporary password and to disassociate the account from the existing
683 * - The token is set to a magic invalid value, to kill existing sessions
684 * and to prevent $this->setToken() calls from resetting the token to a
686 * - SessionManager is instructed to prevent new sessions for the user, to
687 * do things like deauthorizing OAuth consumers.
688 * - AuthManager is instructed to revoke access, to invalidate or remove
689 * passwords and other credentials.
691 * @param string $name Username
692 * @param array $options Options are:
693 * - validate: As for User::getCanonicalName(), default 'valid'
694 * - create: Whether to create the user if it doesn't already exist, default true
695 * - steal: Whether to "disable" the account for normal use if it already
696 * exists, default false
700 public static function newSystemUser( $name, $options = [] ) {
701 global $wgDisableAuthManager;
704 'validate' => 'valid',
709 $name = self
::getCanonicalName( $name, $options['validate'] );
710 if ( $name === false ) {
714 $fields = self
::selectFields();
715 if ( $wgDisableAuthManager ) {
716 $fields = array_merge( $fields, [ 'user_password', 'user_newpassword' ] );
719 $dbw = wfGetDB( DB_MASTER
);
720 $row = $dbw->selectRow(
723 [ 'user_name' => $name ],
727 // No user. Create it?
728 return $options['create'] ? self
::createNew( $name ) : null;
730 $user = self
::newFromRow( $row );
732 // A user is considered to exist as a non-system user if it can
733 // authenticate, or has an email set, or has a non-invalid token.
734 if ( !$user->mEmail
&& $user->mToken
=== self
::INVALID_TOKEN
) {
735 if ( $wgDisableAuthManager ) {
736 $passwordFactory = new PasswordFactory();
737 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
739 $password = $passwordFactory->newFromCiphertext( $row->user_password
);
740 } catch ( PasswordError
$e ) {
741 wfDebug( 'Invalid password hash found in database.' );
742 $password = PasswordFactory
::newInvalidPassword();
745 $newpassword = $passwordFactory->newFromCiphertext( $row->user_newpassword
);
746 } catch ( PasswordError
$e ) {
747 wfDebug( 'Invalid password hash found in database.' );
748 $newpassword = PasswordFactory
::newInvalidPassword();
750 $canAuthenticate = !$password instanceof InvalidPassword ||
751 !$newpassword instanceof InvalidPassword
;
753 $canAuthenticate = AuthManager
::singleton()->userCanAuthenticate( $name );
756 if ( $user->mEmail ||
$user->mToken
!== self
::INVALID_TOKEN ||
$canAuthenticate ) {
757 // User exists. Steal it?
758 if ( !$options['steal'] ) {
762 if ( $wgDisableAuthManager ) {
763 $nopass = PasswordFactory
::newInvalidPassword()->toString();
767 'user_password' => $nopass,
768 'user_newpassword' => $nopass,
769 'user_newpass_time' => null,
771 [ 'user_id' => $user->getId() ],
775 AuthManager
::singleton()->revokeAccessForUser( $name );
778 $user->invalidateEmail();
779 $user->mToken
= self
::INVALID_TOKEN
;
780 $user->saveSettings();
781 SessionManager
::singleton()->preventSessionsForUser( $user->getName() );
790 * Get the username corresponding to a given user ID
791 * @param int $id User ID
792 * @return string|bool The corresponding username
794 public static function whoIs( $id ) {
795 return UserCache
::singleton()->getProp( $id, 'name' );
799 * Get the real name of a user given their user ID
801 * @param int $id User ID
802 * @return string|bool The corresponding user's real name
804 public static function whoIsReal( $id ) {
805 return UserCache
::singleton()->getProp( $id, 'real_name' );
809 * Get database id given a user name
810 * @param string $name Username
811 * @param integer $flags User::READ_* constant bitfield
812 * @return int|null The corresponding user's ID, or null if user is nonexistent
814 public static function idFromName( $name, $flags = self
::READ_NORMAL
) {
815 $nt = Title
::makeTitleSafe( NS_USER
, $name );
816 if ( is_null( $nt ) ) {
821 if ( !( $flags & self
::READ_LATEST
) && isset( self
::$idCacheByName[$name] ) ) {
822 return self
::$idCacheByName[$name];
825 $db = ( $flags & self
::READ_LATEST
)
826 ?
wfGetDB( DB_MASTER
)
827 : wfGetDB( DB_SLAVE
);
832 [ 'user_name' => $nt->getText() ],
836 if ( $s === false ) {
839 $result = $s->user_id
;
842 self
::$idCacheByName[$name] = $result;
844 if ( count( self
::$idCacheByName ) > 1000 ) {
845 self
::$idCacheByName = [];
852 * Reset the cache used in idFromName(). For use in tests.
854 public static function resetIdByNameCache() {
855 self
::$idCacheByName = [];
859 * Does the string match an anonymous IPv4 address?
861 * This function exists for username validation, in order to reject
862 * usernames which are similar in form to IP addresses. Strings such
863 * as 300.300.300.300 will return true because it looks like an IP
864 * address, despite not being strictly valid.
866 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
867 * address because the usemod software would "cloak" anonymous IP
868 * addresses like this, if we allowed accounts like this to be created
869 * new users could get the old edits of these anonymous users.
871 * @param string $name Name to match
874 public static function isIP( $name ) {
875 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
876 || IP
::isIPv6( $name );
880 * Is the input a valid username?
882 * Checks if the input is a valid username, we don't want an empty string,
883 * an IP address, anything that contains slashes (would mess up subpages),
884 * is longer than the maximum allowed username size or doesn't begin with
887 * @param string $name Name to match
890 public static function isValidUserName( $name ) {
891 global $wgContLang, $wgMaxNameChars;
894 || User
::isIP( $name )
895 ||
strpos( $name, '/' ) !== false
896 ||
strlen( $name ) > $wgMaxNameChars
897 ||
$name != $wgContLang->ucfirst( $name )
902 // Ensure that the name can't be misresolved as a different title,
903 // such as with extra namespace keys at the start.
904 $parsed = Title
::newFromText( $name );
905 if ( is_null( $parsed )
906 ||
$parsed->getNamespace()
907 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
911 // Check an additional blacklist of troublemaker characters.
912 // Should these be merged into the title char list?
913 $unicodeBlacklist = '/[' .
914 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
915 '\x{00a0}' . # non-breaking space
916 '\x{2000}-\x{200f}' . # various whitespace
917 '\x{2028}-\x{202f}' . # breaks and control chars
918 '\x{3000}' . # ideographic space
919 '\x{e000}-\x{f8ff}' . # private use
921 if ( preg_match( $unicodeBlacklist, $name ) ) {
929 * Usernames which fail to pass this function will be blocked
930 * from user login and new account registrations, but may be used
931 * internally by batch processes.
933 * If an account already exists in this form, login will be blocked
934 * by a failure to pass this function.
936 * @param string $name Name to match
939 public static function isUsableName( $name ) {
940 global $wgReservedUsernames;
941 // Must be a valid username, obviously ;)
942 if ( !self
::isValidUserName( $name ) ) {
946 static $reservedUsernames = false;
947 if ( !$reservedUsernames ) {
948 $reservedUsernames = $wgReservedUsernames;
949 Hooks
::run( 'UserGetReservedNames', [ &$reservedUsernames ] );
952 // Certain names may be reserved for batch processes.
953 foreach ( $reservedUsernames as $reserved ) {
954 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
955 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
957 if ( $reserved == $name ) {
965 * Usernames which fail to pass this function will be blocked
966 * from new account registrations, but may be used internally
967 * either by batch processes or by user accounts which have
968 * already been created.
970 * Additional blacklisting may be added here rather than in
971 * isValidUserName() to avoid disrupting existing accounts.
973 * @param string $name String to match
976 public static function isCreatableName( $name ) {
977 global $wgInvalidUsernameCharacters;
979 // Ensure that the username isn't longer than 235 bytes, so that
980 // (at least for the builtin skins) user javascript and css files
981 // will work. (bug 23080)
982 if ( strlen( $name ) > 235 ) {
983 wfDebugLog( 'username', __METHOD__
.
984 ": '$name' invalid due to length" );
988 // Preg yells if you try to give it an empty string
989 if ( $wgInvalidUsernameCharacters !== '' ) {
990 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
991 wfDebugLog( 'username', __METHOD__
.
992 ": '$name' invalid due to wgInvalidUsernameCharacters" );
997 return self
::isUsableName( $name );
1001 * Is the input a valid password for this user?
1003 * @param string $password Desired password
1006 public function isValidPassword( $password ) {
1007 // simple boolean wrapper for getPasswordValidity
1008 return $this->getPasswordValidity( $password ) === true;
1012 * Given unvalidated password input, return error message on failure.
1014 * @param string $password Desired password
1015 * @return bool|string|array True on success, string or array of error message on failure
1017 public function getPasswordValidity( $password ) {
1018 $result = $this->checkPasswordValidity( $password );
1019 if ( $result->isGood() ) {
1023 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
1024 $messages[] = $error['message'];
1026 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
1027 $messages[] = $warning['message'];
1029 if ( count( $messages ) === 1 ) {
1030 return $messages[0];
1037 * Check if this is a valid password for this user
1039 * Create a Status object based on the password's validity.
1040 * The Status should be set to fatal if the user should not
1041 * be allowed to log in, and should have any errors that
1042 * would block changing the password.
1044 * If the return value of this is not OK, the password
1045 * should not be checked. If the return value is not Good,
1046 * the password can be checked, but the user should not be
1047 * able to set their password to this.
1049 * @param string $password Desired password
1050 * @param string $purpose one of 'login', 'create', 'reset'
1054 public function checkPasswordValidity( $password, $purpose = 'login' ) {
1055 global $wgPasswordPolicy;
1057 $upp = new UserPasswordPolicy(
1058 $wgPasswordPolicy['policies'],
1059 $wgPasswordPolicy['checks']
1062 $status = Status
::newGood();
1063 $result = false; // init $result to false for the internal checks
1065 if ( !Hooks
::run( 'isValidPassword', [ $password, &$result, $this ] ) ) {
1066 $status->error( $result );
1070 if ( $result === false ) {
1071 $status->merge( $upp->checkUserPassword( $this, $password, $purpose ) );
1073 } elseif ( $result === true ) {
1076 $status->error( $result );
1077 return $status; // the isValidPassword hook set a string $result and returned true
1082 * Given unvalidated user input, return a canonical username, or false if
1083 * the username is invalid.
1084 * @param string $name User input
1085 * @param string|bool $validate Type of validation to use:
1086 * - false No validation
1087 * - 'valid' Valid for batch processes
1088 * - 'usable' Valid for batch processes and login
1089 * - 'creatable' Valid for batch processes, login and account creation
1091 * @throws InvalidArgumentException
1092 * @return bool|string
1094 public static function getCanonicalName( $name, $validate = 'valid' ) {
1095 // Force usernames to capital
1097 $name = $wgContLang->ucfirst( $name );
1099 # Reject names containing '#'; these will be cleaned up
1100 # with title normalisation, but then it's too late to
1102 if ( strpos( $name, '#' ) !== false ) {
1106 // Clean up name according to title rules,
1107 // but only when validation is requested (bug 12654)
1108 $t = ( $validate !== false ) ?
1109 Title
::newFromText( $name, NS_USER
) : Title
::makeTitle( NS_USER
, $name );
1110 // Check for invalid titles
1111 if ( is_null( $t ) ||
$t->getNamespace() !== NS_USER ||
$t->isExternal() ) {
1115 // Reject various classes of invalid names
1116 $name = AuthManager
::callLegacyAuthPlugin(
1117 'getCanonicalName', [ $t->getText() ], $t->getText()
1120 switch ( $validate ) {
1124 if ( !User
::isValidUserName( $name ) ) {
1129 if ( !User
::isUsableName( $name ) ) {
1134 if ( !User
::isCreatableName( $name ) ) {
1139 throw new InvalidArgumentException(
1140 'Invalid parameter value for $validate in ' . __METHOD__
);
1146 * Count the number of edits of a user
1148 * @param int $uid User ID to check
1149 * @return int The user's edit count
1151 * @deprecated since 1.21 in favour of User::getEditCount
1153 public static function edits( $uid ) {
1154 wfDeprecated( __METHOD__
, '1.21' );
1155 $user = self
::newFromId( $uid );
1156 return $user->getEditCount();
1160 * Return a random password.
1162 * @deprecated since 1.27, use PasswordFactory::generateRandomPasswordString()
1163 * @return string New random password
1165 public static function randomPassword() {
1166 global $wgMinimalPasswordLength;
1167 return PasswordFactory
::generateRandomPasswordString( $wgMinimalPasswordLength );
1171 * Set cached properties to default.
1173 * @note This no longer clears uncached lazy-initialised properties;
1174 * the constructor does that instead.
1176 * @param string|bool $name
1178 public function loadDefaults( $name = false ) {
1180 $this->mName
= $name;
1181 $this->mRealName
= '';
1183 $this->mOptionOverrides
= null;
1184 $this->mOptionsLoaded
= false;
1186 $loggedOut = $this->mRequest
&& !defined( 'MW_NO_SESSION' )
1187 ?
$this->mRequest
->getSession()->getLoggedOutTimestamp() : 0;
1188 if ( $loggedOut !== 0 ) {
1189 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1191 $this->mTouched
= '1'; # Allow any pages to be cached
1194 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1195 $this->mEmailAuthenticated
= null;
1196 $this->mEmailToken
= '';
1197 $this->mEmailTokenExpires
= null;
1198 $this->mRegistration
= wfTimestamp( TS_MW
);
1199 $this->mGroups
= [];
1201 Hooks
::run( 'UserLoadDefaults', [ $this, $name ] );
1205 * Return whether an item has been loaded.
1207 * @param string $item Item to check. Current possibilities:
1211 * @param string $all 'all' to check if the whole object has been loaded
1212 * or any other string to check if only the item is available (e.g.
1216 public function isItemLoaded( $item, $all = 'all' ) {
1217 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1218 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1222 * Set that an item has been loaded
1224 * @param string $item
1226 protected function setItemLoaded( $item ) {
1227 if ( is_array( $this->mLoadedItems
) ) {
1228 $this->mLoadedItems
[$item] = true;
1233 * Load user data from the session.
1235 * @return bool True if the user is logged in, false otherwise.
1237 private function loadFromSession() {
1240 Hooks
::run( 'UserLoadFromSession', [ $this, &$result ], '1.27' );
1241 if ( $result !== null ) {
1245 // MediaWiki\Session\Session already did the necessary authentication of the user
1246 // returned here, so just use it if applicable.
1247 $session = $this->getRequest()->getSession();
1248 $user = $session->getUser();
1249 if ( $user->isLoggedIn() ) {
1250 $this->loadFromUserObject( $user );
1251 // Other code expects these to be set in the session, so set them.
1252 $session->set( 'wsUserID', $this->getId() );
1253 $session->set( 'wsUserName', $this->getName() );
1254 $session->set( 'wsToken', $this->getToken() );
1262 * Load user and user_group data from the database.
1263 * $this->mId must be set, this is how the user is identified.
1265 * @param integer $flags User::READ_* constant bitfield
1266 * @return bool True if the user exists, false if the user is anonymous
1268 public function loadFromDatabase( $flags = self
::READ_LATEST
) {
1270 $this->mId
= intval( $this->mId
);
1273 if ( !$this->mId
) {
1274 $this->loadDefaults();
1278 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
1279 $db = wfGetDB( $index );
1281 $s = $db->selectRow(
1283 self
::selectFields(),
1284 [ 'user_id' => $this->mId
],
1289 $this->queryFlagsUsed
= $flags;
1290 Hooks
::run( 'UserLoadFromDatabase', [ $this, &$s ] );
1292 if ( $s !== false ) {
1293 // Initialise user table data
1294 $this->loadFromRow( $s );
1295 $this->mGroups
= null; // deferred
1296 $this->getEditCount(); // revalidation for nulls
1301 $this->loadDefaults();
1307 * Initialize this object from a row from the user table.
1309 * @param stdClass $row Row from the user table to load.
1310 * @param array $data Further user data to load into the object
1312 * user_groups Array with groups out of the user_groups table
1313 * user_properties Array with properties out of the user_properties table
1315 protected function loadFromRow( $row, $data = null ) {
1318 $this->mGroups
= null; // deferred
1320 if ( isset( $row->user_name
) ) {
1321 $this->mName
= $row->user_name
;
1322 $this->mFrom
= 'name';
1323 $this->setItemLoaded( 'name' );
1328 if ( isset( $row->user_real_name
) ) {
1329 $this->mRealName
= $row->user_real_name
;
1330 $this->setItemLoaded( 'realname' );
1335 if ( isset( $row->user_id
) ) {
1336 $this->mId
= intval( $row->user_id
);
1337 $this->mFrom
= 'id';
1338 $this->setItemLoaded( 'id' );
1343 if ( isset( $row->user_id
) && isset( $row->user_name
) ) {
1344 self
::$idCacheByName[$row->user_name
] = $row->user_id
;
1347 if ( isset( $row->user_editcount
) ) {
1348 $this->mEditCount
= $row->user_editcount
;
1353 if ( isset( $row->user_touched
) ) {
1354 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1359 if ( isset( $row->user_token
) ) {
1360 // The definition for the column is binary(32), so trim the NULs
1361 // that appends. The previous definition was char(32), so trim
1363 $this->mToken
= rtrim( $row->user_token
, " \0" );
1364 if ( $this->mToken
=== '' ) {
1365 $this->mToken
= null;
1371 if ( isset( $row->user_email
) ) {
1372 $this->mEmail
= $row->user_email
;
1373 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1374 $this->mEmailToken
= $row->user_email_token
;
1375 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1376 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1382 $this->mLoadedItems
= true;
1385 if ( is_array( $data ) ) {
1386 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1387 $this->mGroups
= $data['user_groups'];
1389 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1390 $this->loadOptions( $data['user_properties'] );
1396 * Load the data for this user object from another user object.
1400 protected function loadFromUserObject( $user ) {
1402 $user->loadGroups();
1403 $user->loadOptions();
1404 foreach ( self
::$mCacheVars as $var ) {
1405 $this->$var = $user->$var;
1410 * Load the groups from the database if they aren't already loaded.
1412 private function loadGroups() {
1413 if ( is_null( $this->mGroups
) ) {
1414 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
1415 ?
wfGetDB( DB_MASTER
)
1416 : wfGetDB( DB_SLAVE
);
1417 $res = $db->select( 'user_groups',
1419 [ 'ug_user' => $this->mId
],
1421 $this->mGroups
= [];
1422 foreach ( $res as $row ) {
1423 $this->mGroups
[] = $row->ug_group
;
1429 * Add the user to the group if he/she meets given criteria.
1431 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1432 * possible to remove manually via Special:UserRights. In such case it
1433 * will not be re-added automatically. The user will also not lose the
1434 * group if they no longer meet the criteria.
1436 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1438 * @return array Array of groups the user has been promoted to.
1440 * @see $wgAutopromoteOnce
1442 public function addAutopromoteOnceGroups( $event ) {
1443 global $wgAutopromoteOnceLogInRC;
1445 if ( wfReadOnly() ||
!$this->getId() ) {
1449 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1450 if ( !count( $toPromote ) ) {
1454 if ( !$this->checkAndSetTouched() ) {
1455 return []; // raced out (bug T48834)
1458 $oldGroups = $this->getGroups(); // previous groups
1459 foreach ( $toPromote as $group ) {
1460 $this->addGroup( $group );
1462 // update groups in external authentication database
1463 Hooks
::run( 'UserGroupsChanged', [ $this, $toPromote, [], false, false ] );
1464 AuthManager
::callLegacyAuthPlugin( 'updateExternalDBGroups', [ $this, $toPromote ] );
1466 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1468 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1469 $logEntry->setPerformer( $this );
1470 $logEntry->setTarget( $this->getUserPage() );
1471 $logEntry->setParameters( [
1472 '4::oldgroups' => $oldGroups,
1473 '5::newgroups' => $newGroups,
1475 $logid = $logEntry->insert();
1476 if ( $wgAutopromoteOnceLogInRC ) {
1477 $logEntry->publish( $logid );
1484 * Builds update conditions. Additional conditions may be added to $conditions to
1485 * protected against race conditions using a compare-and-set (CAS) mechanism
1486 * based on comparing $this->mTouched with the user_touched field.
1488 * @param DatabaseBase $db
1489 * @param array $conditions WHERE conditions for use with DatabaseBase::update
1490 * @return array WHERE conditions for use with DatabaseBase::update
1492 protected function makeUpdateConditions( DatabaseBase
$db, array $conditions ) {
1493 if ( $this->mTouched
) {
1494 // CAS check: only update if the row wasn't changed sicne it was loaded.
1495 $conditions['user_touched'] = $db->timestamp( $this->mTouched
);
1502 * Bump user_touched if it didn't change since this object was loaded
1504 * On success, the mTouched field is updated.
1505 * The user serialization cache is always cleared.
1507 * @return bool Whether user_touched was actually updated
1510 protected function checkAndSetTouched() {
1513 if ( !$this->mId
) {
1514 return false; // anon
1517 // Get a new user_touched that is higher than the old one
1518 $newTouched = $this->newTouchedTimestamp();
1520 $dbw = wfGetDB( DB_MASTER
);
1521 $dbw->update( 'user',
1522 [ 'user_touched' => $dbw->timestamp( $newTouched ) ],
1523 $this->makeUpdateConditions( $dbw, [
1524 'user_id' => $this->mId
,
1528 $success = ( $dbw->affectedRows() > 0 );
1531 $this->mTouched
= $newTouched;
1532 $this->clearSharedCache();
1534 // Clears on failure too since that is desired if the cache is stale
1535 $this->clearSharedCache( 'refresh' );
1542 * Clear various cached data stored in this object. The cache of the user table
1543 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1545 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1546 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1548 public function clearInstanceCache( $reloadFrom = false ) {
1549 $this->mNewtalk
= -1;
1550 $this->mDatePreference
= null;
1551 $this->mBlockedby
= -1; # Unset
1552 $this->mHash
= false;
1553 $this->mRights
= null;
1554 $this->mEffectiveGroups
= null;
1555 $this->mImplicitGroups
= null;
1556 $this->mGroups
= null;
1557 $this->mOptions
= null;
1558 $this->mOptionsLoaded
= false;
1559 $this->mEditCount
= null;
1561 if ( $reloadFrom ) {
1562 $this->mLoadedItems
= [];
1563 $this->mFrom
= $reloadFrom;
1568 * Combine the language default options with any site-specific options
1569 * and add the default language variants.
1571 * @return array Array of String options
1573 public static function getDefaultOptions() {
1574 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1576 static $defOpt = null;
1577 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1578 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1579 // mid-request and see that change reflected in the return value of this function.
1580 // Which is insane and would never happen during normal MW operation
1584 $defOpt = $wgDefaultUserOptions;
1585 // Default language setting
1586 $defOpt['language'] = $wgContLang->getCode();
1587 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1588 $defOpt[$langCode == $wgContLang->getCode() ?
'variant' : "variant-$langCode"] = $langCode;
1590 $namespaces = MediaWikiServices
::getInstance()->getSearchEngineConfig()->searchableNamespaces();
1591 foreach ( $namespaces as $nsnum => $nsname ) {
1592 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1594 $defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1596 Hooks
::run( 'UserGetDefaultOptions', [ &$defOpt ] );
1602 * Get a given default option value.
1604 * @param string $opt Name of option to retrieve
1605 * @return string Default option value
1607 public static function getDefaultOption( $opt ) {
1608 $defOpts = self
::getDefaultOptions();
1609 if ( isset( $defOpts[$opt] ) ) {
1610 return $defOpts[$opt];
1617 * Get blocking information
1618 * @param bool $bFromSlave Whether to check the slave database first.
1619 * To improve performance, non-critical checks are done against slaves.
1620 * Check when actually saving should be done against master.
1622 private function getBlockedStatus( $bFromSlave = true ) {
1623 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1625 if ( -1 != $this->mBlockedby
) {
1629 wfDebug( __METHOD__
. ": checking...\n" );
1631 // Initialize data...
1632 // Otherwise something ends up stomping on $this->mBlockedby when
1633 // things get lazy-loaded later, causing false positive block hits
1634 // due to -1 !== 0. Probably session-related... Nothing should be
1635 // overwriting mBlockedby, surely?
1638 # We only need to worry about passing the IP address to the Block generator if the
1639 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1640 # know which IP address they're actually coming from
1642 if ( !$this->isAllowed( 'ipblock-exempt' ) ) {
1643 // $wgUser->getName() only works after the end of Setup.php. Until
1644 // then, assume it's a logged-out user.
1645 $globalUserName = $wgUser->isSafeToLoad()
1646 ?
$wgUser->getName()
1647 : IP
::sanitizeIP( $wgUser->getRequest()->getIP() );
1648 if ( $this->getName() === $globalUserName ) {
1649 $ip = $this->getRequest()->getIP();
1654 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1657 if ( !$block instanceof Block
&& $ip !== null && !in_array( $ip, $wgProxyWhitelist ) ) {
1659 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1661 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1662 $block->mReason
= wfMessage( 'proxyblockreason' )->text();
1663 $block->setTarget( $ip );
1664 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1666 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1667 $block->mReason
= wfMessage( 'sorbsreason' )->text();
1668 $block->setTarget( $ip );
1672 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1673 if ( !$block instanceof Block
1674 && $wgApplyIpBlocksToXff
1676 && !in_array( $ip, $wgProxyWhitelist )
1678 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1679 $xff = array_map( 'trim', explode( ',', $xff ) );
1680 $xff = array_diff( $xff, [ $ip ] );
1681 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1682 $block = Block
::chooseBlock( $xffblocks, $xff );
1683 if ( $block instanceof Block
) {
1684 # Mangle the reason to alert the user that the block
1685 # originated from matching the X-Forwarded-For header.
1686 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->text();
1690 if ( $block instanceof Block
) {
1691 wfDebug( __METHOD__
. ": Found block.\n" );
1692 $this->mBlock
= $block;
1693 $this->mBlockedby
= $block->getByName();
1694 $this->mBlockreason
= $block->mReason
;
1695 $this->mHideName
= $block->mHideName
;
1696 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1698 $this->mBlockedby
= '';
1699 $this->mHideName
= 0;
1700 $this->mAllowUsertalk
= false;
1704 Hooks
::run( 'GetBlockedStatus', [ &$this ] );
1709 * Whether the given IP is in a DNS blacklist.
1711 * @param string $ip IP to check
1712 * @param bool $checkWhitelist Whether to check the whitelist first
1713 * @return bool True if blacklisted.
1715 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1716 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1718 if ( !$wgEnableDnsBlacklist ) {
1722 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1726 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1730 * Whether the given IP is in a given DNS blacklist.
1732 * @param string $ip IP to check
1733 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1734 * @return bool True if blacklisted.
1736 public function inDnsBlacklist( $ip, $bases ) {
1739 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1740 if ( IP
::isIPv4( $ip ) ) {
1741 // Reverse IP, bug 21255
1742 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1744 foreach ( (array)$bases as $base ) {
1746 // If we have an access key, use that too (ProjectHoneypot, etc.)
1748 if ( is_array( $base ) ) {
1749 if ( count( $base ) >= 2 ) {
1750 // Access key is 1, base URL is 0
1751 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1753 $host = "$ipReversed.{$base[0]}";
1755 $basename = $base[0];
1757 $host = "$ipReversed.$base";
1761 $ipList = gethostbynamel( $host );
1764 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
1768 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
1777 * Check if an IP address is in the local proxy list
1783 public static function isLocallyBlockedProxy( $ip ) {
1784 global $wgProxyList;
1786 if ( !$wgProxyList ) {
1790 if ( !is_array( $wgProxyList ) ) {
1791 // Load from the specified file
1792 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1795 if ( !is_array( $wgProxyList ) ) {
1797 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1799 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1800 // Old-style flipped proxy list
1809 * Is this user subject to rate limiting?
1811 * @return bool True if rate limited
1813 public function isPingLimitable() {
1814 global $wgRateLimitsExcludedIPs;
1815 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1816 // No other good way currently to disable rate limits
1817 // for specific IPs. :P
1818 // But this is a crappy hack and should die.
1821 return !$this->isAllowed( 'noratelimit' );
1825 * Primitive rate limits: enforce maximum actions per time period
1826 * to put a brake on flooding.
1828 * The method generates both a generic profiling point and a per action one
1829 * (suffix being "-$action".
1831 * @note When using a shared cache like memcached, IP-address
1832 * last-hit counters will be shared across wikis.
1834 * @param string $action Action to enforce; 'edit' if unspecified
1835 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1836 * @return bool True if a rate limiter was tripped
1838 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1839 // Call the 'PingLimiter' hook
1841 if ( !Hooks
::run( 'PingLimiter', [ &$this, $action, &$result, $incrBy ] ) ) {
1845 global $wgRateLimits;
1846 if ( !isset( $wgRateLimits[$action] ) ) {
1850 // Some groups shouldn't trigger the ping limiter, ever
1851 if ( !$this->isPingLimitable() ) {
1855 $limits = $wgRateLimits[$action];
1857 $id = $this->getId();
1859 $isNewbie = $this->isNewbie();
1863 if ( isset( $limits['anon'] ) ) {
1864 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1867 // limits for logged-in users
1868 if ( isset( $limits['user'] ) ) {
1869 $userLimit = $limits['user'];
1871 // limits for newbie logged-in users
1872 if ( $isNewbie && isset( $limits['newbie'] ) ) {
1873 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1877 // limits for anons and for newbie logged-in users
1880 if ( isset( $limits['ip'] ) ) {
1881 $ip = $this->getRequest()->getIP();
1882 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1884 // subnet-based limits
1885 if ( isset( $limits['subnet'] ) ) {
1886 $ip = $this->getRequest()->getIP();
1887 $subnet = IP
::getSubnet( $ip );
1888 if ( $subnet !== false ) {
1889 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1894 // Check for group-specific permissions
1895 // If more than one group applies, use the group with the highest limit ratio (max/period)
1896 foreach ( $this->getGroups() as $group ) {
1897 if ( isset( $limits[$group] ) ) {
1898 if ( $userLimit === false
1899 ||
$limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1901 $userLimit = $limits[$group];
1906 // Set the user limit key
1907 if ( $userLimit !== false ) {
1908 list( $max, $period ) = $userLimit;
1909 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
1910 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1913 // ip-based limits for all ping-limitable users
1914 if ( isset( $limits['ip-all'] ) ) {
1915 $ip = $this->getRequest()->getIP();
1916 // ignore if user limit is more permissive
1917 if ( $isNewbie ||
$userLimit === false
1918 ||
$limits['ip-all'][0] / $limits['ip-all'][1] > $userLimit[0] / $userLimit[1] ) {
1919 $keys["mediawiki:limiter:$action:ip-all:$ip"] = $limits['ip-all'];
1923 // subnet-based limits for all ping-limitable users
1924 if ( isset( $limits['subnet-all'] ) ) {
1925 $ip = $this->getRequest()->getIP();
1926 $subnet = IP
::getSubnet( $ip );
1927 if ( $subnet !== false ) {
1928 // ignore if user limit is more permissive
1929 if ( $isNewbie ||
$userLimit === false
1930 ||
$limits['ip-all'][0] / $limits['ip-all'][1]
1931 > $userLimit[0] / $userLimit[1] ) {
1932 $keys["mediawiki:limiter:$action:subnet-all:$subnet"] = $limits['subnet-all'];
1937 $cache = ObjectCache
::getLocalClusterInstance();
1940 foreach ( $keys as $key => $limit ) {
1941 list( $max, $period ) = $limit;
1942 $summary = "(limit $max in {$period}s)";
1943 $count = $cache->get( $key );
1946 if ( $count >= $max ) {
1947 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1948 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1951 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1954 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1955 if ( $incrBy > 0 ) {
1956 $cache->add( $key, 0, intval( $period ) ); // first ping
1959 if ( $incrBy > 0 ) {
1960 $cache->incr( $key, $incrBy );
1968 * Check if user is blocked
1970 * @param bool $bFromSlave Whether to check the slave database instead of
1971 * the master. Hacked from false due to horrible probs on site.
1972 * @return bool True if blocked, false otherwise
1974 public function isBlocked( $bFromSlave = true ) {
1975 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
1979 * Get the block affecting the user, or null if the user is not blocked
1981 * @param bool $bFromSlave Whether to check the slave database instead of the master
1982 * @return Block|null
1984 public function getBlock( $bFromSlave = true ) {
1985 $this->getBlockedStatus( $bFromSlave );
1986 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
1990 * Check if user is blocked from editing a particular article
1992 * @param Title $title Title to check
1993 * @param bool $bFromSlave Whether to check the slave database instead of the master
1996 public function isBlockedFrom( $title, $bFromSlave = false ) {
1997 global $wgBlockAllowsUTEdit;
1999 $blocked = $this->isBlocked( $bFromSlave );
2000 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
2001 // If a user's name is suppressed, they cannot make edits anywhere
2002 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName()
2003 && $title->getNamespace() == NS_USER_TALK
) {
2005 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
2008 Hooks
::run( 'UserIsBlockedFrom', [ $this, $title, &$blocked, &$allowUsertalk ] );
2014 * If user is blocked, return the name of the user who placed the block
2015 * @return string Name of blocker
2017 public function blockedBy() {
2018 $this->getBlockedStatus();
2019 return $this->mBlockedby
;
2023 * If user is blocked, return the specified reason for the block
2024 * @return string Blocking reason
2026 public function blockedFor() {
2027 $this->getBlockedStatus();
2028 return $this->mBlockreason
;
2032 * If user is blocked, return the ID for the block
2033 * @return int Block ID
2035 public function getBlockId() {
2036 $this->getBlockedStatus();
2037 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
2041 * Check if user is blocked on all wikis.
2042 * Do not use for actual edit permission checks!
2043 * This is intended for quick UI checks.
2045 * @param string $ip IP address, uses current client if none given
2046 * @return bool True if blocked, false otherwise
2048 public function isBlockedGlobally( $ip = '' ) {
2049 return $this->getGlobalBlock( $ip ) instanceof Block
;
2053 * Check if user is blocked on all wikis.
2054 * Do not use for actual edit permission checks!
2055 * This is intended for quick UI checks.
2057 * @param string $ip IP address, uses current client if none given
2058 * @return Block|null Block object if blocked, null otherwise
2059 * @throws FatalError
2060 * @throws MWException
2062 public function getGlobalBlock( $ip = '' ) {
2063 if ( $this->mGlobalBlock
!== null ) {
2064 return $this->mGlobalBlock ?
: null;
2066 // User is already an IP?
2067 if ( IP
::isIPAddress( $this->getName() ) ) {
2068 $ip = $this->getName();
2070 $ip = $this->getRequest()->getIP();
2074 Hooks
::run( 'UserIsBlockedGlobally', [ &$this, $ip, &$blocked, &$block ] );
2076 if ( $blocked && $block === null ) {
2077 // back-compat: UserIsBlockedGlobally didn't have $block param first
2079 $block->setTarget( $ip );
2082 $this->mGlobalBlock
= $blocked ?
$block : false;
2083 return $this->mGlobalBlock ?
: null;
2087 * Check if user account is locked
2089 * @return bool True if locked, false otherwise
2091 public function isLocked() {
2092 if ( $this->mLocked
!== null ) {
2093 return $this->mLocked
;
2095 $authUser = AuthManager
::callLegacyAuthPlugin( 'getUserInstance', [ &$this ], null );
2096 $this->mLocked
= $authUser && $authUser->isLocked();
2097 Hooks
::run( 'UserIsLocked', [ $this, &$this->mLocked
] );
2098 return $this->mLocked
;
2102 * Check if user account is hidden
2104 * @return bool True if hidden, false otherwise
2106 public function isHidden() {
2107 if ( $this->mHideName
!== null ) {
2108 return $this->mHideName
;
2110 $this->getBlockedStatus();
2111 if ( !$this->mHideName
) {
2112 $authUser = AuthManager
::callLegacyAuthPlugin( 'getUserInstance', [ &$this ], null );
2113 $this->mHideName
= $authUser && $authUser->isHidden();
2114 Hooks
::run( 'UserIsHidden', [ $this, &$this->mHideName
] );
2116 return $this->mHideName
;
2120 * Get the user's ID.
2121 * @return int The user's ID; 0 if the user is anonymous or nonexistent
2123 public function getId() {
2124 if ( $this->mId
=== null && $this->mName
!== null && User
::isIP( $this->mName
) ) {
2125 // Special case, we know the user is anonymous
2127 } elseif ( !$this->isItemLoaded( 'id' ) ) {
2128 // Don't load if this was initialized from an ID
2132 return (int)$this->mId
;
2136 * Set the user and reload all fields according to a given ID
2137 * @param int $v User ID to reload
2139 public function setId( $v ) {
2141 $this->clearInstanceCache( 'id' );
2145 * Get the user name, or the IP of an anonymous user
2146 * @return string User's name or IP address
2148 public function getName() {
2149 if ( $this->isItemLoaded( 'name', 'only' ) ) {
2150 // Special case optimisation
2151 return $this->mName
;
2154 if ( $this->mName
=== false ) {
2156 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
2158 return $this->mName
;
2163 * Set the user name.
2165 * This does not reload fields from the database according to the given
2166 * name. Rather, it is used to create a temporary "nonexistent user" for
2167 * later addition to the database. It can also be used to set the IP
2168 * address for an anonymous user to something other than the current
2171 * @note User::newFromName() has roughly the same function, when the named user
2173 * @param string $str New user name to set
2175 public function setName( $str ) {
2177 $this->mName
= $str;
2181 * Get the user's name escaped by underscores.
2182 * @return string Username escaped by underscores.
2184 public function getTitleKey() {
2185 return str_replace( ' ', '_', $this->getName() );
2189 * Check if the user has new messages.
2190 * @return bool True if the user has new messages
2192 public function getNewtalk() {
2195 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2196 if ( $this->mNewtalk
=== -1 ) {
2197 $this->mNewtalk
= false; # reset talk page status
2199 // Check memcached separately for anons, who have no
2200 // entire User object stored in there.
2201 if ( !$this->mId
) {
2202 global $wgDisableAnonTalk;
2203 if ( $wgDisableAnonTalk ) {
2204 // Anon newtalk disabled by configuration.
2205 $this->mNewtalk
= false;
2207 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
2210 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2214 return (bool)$this->mNewtalk
;
2218 * Return the data needed to construct links for new talk page message
2219 * alerts. If there are new messages, this will return an associative array
2220 * with the following data:
2221 * wiki: The database name of the wiki
2222 * link: Root-relative link to the user's talk page
2223 * rev: The last talk page revision that the user has seen or null. This
2224 * is useful for building diff links.
2225 * If there are no new messages, it returns an empty array.
2226 * @note This function was designed to accomodate multiple talk pages, but
2227 * currently only returns a single link and revision.
2230 public function getNewMessageLinks() {
2232 if ( !Hooks
::run( 'UserRetrieveNewTalks', [ &$this, &$talks ] ) ) {
2234 } elseif ( !$this->getNewtalk() ) {
2237 $utp = $this->getTalkPage();
2238 $dbr = wfGetDB( DB_SLAVE
);
2239 // Get the "last viewed rev" timestamp from the oldest message notification
2240 $timestamp = $dbr->selectField( 'user_newtalk',
2241 'MIN(user_last_timestamp)',
2242 $this->isAnon() ?
[ 'user_ip' => $this->getName() ] : [ 'user_id' => $this->getId() ],
2244 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2245 return [ [ 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ] ];
2249 * Get the revision ID for the last talk page revision viewed by the talk
2251 * @return int|null Revision ID or null
2253 public function getNewMessageRevisionId() {
2254 $newMessageRevisionId = null;
2255 $newMessageLinks = $this->getNewMessageLinks();
2256 if ( $newMessageLinks ) {
2257 // Note: getNewMessageLinks() never returns more than a single link
2258 // and it is always for the same wiki, but we double-check here in
2259 // case that changes some time in the future.
2260 if ( count( $newMessageLinks ) === 1
2261 && $newMessageLinks[0]['wiki'] === wfWikiID()
2262 && $newMessageLinks[0]['rev']
2264 /** @var Revision $newMessageRevision */
2265 $newMessageRevision = $newMessageLinks[0]['rev'];
2266 $newMessageRevisionId = $newMessageRevision->getId();
2269 return $newMessageRevisionId;
2273 * Internal uncached check for new messages
2276 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2277 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2278 * @return bool True if the user has new messages
2280 protected function checkNewtalk( $field, $id ) {
2281 $dbr = wfGetDB( DB_SLAVE
);
2283 $ok = $dbr->selectField( 'user_newtalk', $field, [ $field => $id ], __METHOD__
);
2285 return $ok !== false;
2289 * Add or update the new messages flag
2290 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2291 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2292 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2293 * @return bool True if successful, false otherwise
2295 protected function updateNewtalk( $field, $id, $curRev = null ) {
2296 // Get timestamp of the talk page revision prior to the current one
2297 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2298 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2299 // Mark the user as having new messages since this revision
2300 $dbw = wfGetDB( DB_MASTER
);
2301 $dbw->insert( 'user_newtalk',
2302 [ $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ],
2305 if ( $dbw->affectedRows() ) {
2306 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2309 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2315 * Clear the new messages flag for the given user
2316 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2317 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2318 * @return bool True if successful, false otherwise
2320 protected function deleteNewtalk( $field, $id ) {
2321 $dbw = wfGetDB( DB_MASTER
);
2322 $dbw->delete( 'user_newtalk',
2325 if ( $dbw->affectedRows() ) {
2326 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2329 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2335 * Update the 'You have new messages!' status.
2336 * @param bool $val Whether the user has new messages
2337 * @param Revision $curRev New, as yet unseen revision of the user talk
2338 * page. Ignored if null or !$val.
2340 public function setNewtalk( $val, $curRev = null ) {
2341 if ( wfReadOnly() ) {
2346 $this->mNewtalk
= $val;
2348 if ( $this->isAnon() ) {
2350 $id = $this->getName();
2353 $id = $this->getId();
2357 $changed = $this->updateNewtalk( $field, $id, $curRev );
2359 $changed = $this->deleteNewtalk( $field, $id );
2363 $this->invalidateCache();
2368 * Generate a current or new-future timestamp to be stored in the
2369 * user_touched field when we update things.
2370 * @return string Timestamp in TS_MW format
2372 private function newTouchedTimestamp() {
2373 global $wgClockSkewFudge;
2375 $time = wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2376 if ( $this->mTouched
&& $time <= $this->mTouched
) {
2377 $time = wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $this->mTouched
) +
1 );
2384 * Clear user data from memcached
2386 * Use after applying updates to the database; caller's
2387 * responsibility to update user_touched if appropriate.
2389 * Called implicitly from invalidateCache() and saveSettings().
2391 * @param string $mode Use 'refresh' to clear now; otherwise before DB commit
2393 public function clearSharedCache( $mode = 'changed' ) {
2394 if ( !$this->getId() ) {
2398 $cache = ObjectCache
::getMainWANInstance();
2399 $processCache = self
::getInProcessCache();
2400 $key = $this->getCacheKey( $cache );
2401 if ( $mode === 'refresh' ) {
2402 $cache->delete( $key, 1 );
2403 $processCache->delete( $key );
2405 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle(
2406 function() use ( $cache, $processCache, $key ) {
2407 $cache->delete( $key );
2408 $processCache->delete( $key );
2415 * Immediately touch the user data cache for this account
2417 * Calls touch() and removes account data from memcached
2419 public function invalidateCache() {
2421 $this->clearSharedCache();
2425 * Update the "touched" timestamp for the user
2427 * This is useful on various login/logout events when making sure that
2428 * a browser or proxy that has multiple tenants does not suffer cache
2429 * pollution where the new user sees the old users content. The value
2430 * of getTouched() is checked when determining 304 vs 200 responses.
2431 * Unlike invalidateCache(), this preserves the User object cache and
2432 * avoids database writes.
2436 public function touch() {
2437 $id = $this->getId();
2439 $key = wfMemcKey( 'user-quicktouched', 'id', $id );
2440 ObjectCache
::getMainWANInstance()->touchCheckKey( $key );
2441 $this->mQuickTouched
= null;
2446 * Validate the cache for this account.
2447 * @param string $timestamp A timestamp in TS_MW format
2450 public function validateCache( $timestamp ) {
2451 return ( $timestamp >= $this->getTouched() );
2455 * Get the user touched timestamp
2457 * Use this value only to validate caches via inequalities
2458 * such as in the case of HTTP If-Modified-Since response logic
2460 * @return string TS_MW Timestamp
2462 public function getTouched() {
2466 if ( $this->mQuickTouched
=== null ) {
2467 $key = wfMemcKey( 'user-quicktouched', 'id', $this->mId
);
2468 $cache = ObjectCache
::getMainWANInstance();
2470 $this->mQuickTouched
= wfTimestamp( TS_MW
, $cache->getCheckKeyTime( $key ) );
2473 return max( $this->mTouched
, $this->mQuickTouched
);
2476 return $this->mTouched
;
2480 * Get the user_touched timestamp field (time of last DB updates)
2481 * @return string TS_MW Timestamp
2484 public function getDBTouched() {
2487 return $this->mTouched
;
2491 * @deprecated Removed in 1.27.
2495 public function getPassword() {
2496 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2500 * @deprecated Removed in 1.27.
2504 public function getTemporaryPassword() {
2505 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2509 * Set the password and reset the random token.
2510 * Calls through to authentication plugin if necessary;
2511 * will have no effect if the auth plugin refuses to
2512 * pass the change through or if the legal password
2515 * As a special case, setting the password to null
2516 * wipes it, so the account cannot be logged in until
2517 * a new password is set, for instance via e-mail.
2519 * @deprecated since 1.27, use AuthManager instead
2520 * @param string $str New password to set
2521 * @throws PasswordError On failure
2524 public function setPassword( $str ) {
2525 global $wgAuth, $wgDisableAuthManager;
2527 if ( !$wgDisableAuthManager ) {
2528 return $this->setPasswordInternal( $str );
2531 if ( $str !== null ) {
2532 if ( !$wgAuth->allowPasswordChange() ) {
2533 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2536 $status = $this->checkPasswordValidity( $str );
2537 if ( !$status->isGood() ) {
2538 throw new PasswordError( $status->getMessage()->text() );
2542 if ( !$wgAuth->setPassword( $this, $str ) ) {
2543 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2546 $this->setOption( 'watchlisttoken', false );
2547 $this->setPasswordInternal( $str );
2553 * Set the password and reset the random token unconditionally.
2555 * @deprecated since 1.27, use AuthManager instead
2556 * @param string|null $str New password to set or null to set an invalid
2557 * password hash meaning that the user will not be able to log in
2558 * through the web interface.
2560 public function setInternalPassword( $str ) {
2561 global $wgAuth, $wgDisableAuthManager;
2563 if ( !$wgDisableAuthManager ) {
2564 $this->setPasswordInternal( $str );
2567 if ( $wgAuth->allowSetLocalPassword() ) {
2568 $this->setOption( 'watchlisttoken', false );
2569 $this->setPasswordInternal( $str );
2574 * Actually set the password and such
2575 * @since 1.27 cannot set a password for a user not in the database
2576 * @param string|null $str New password to set or null to set an invalid
2577 * password hash meaning that the user will not be able to log in
2578 * through the web interface.
2579 * @return bool Success
2581 private function setPasswordInternal( $str ) {
2582 global $wgDisableAuthManager;
2584 if ( $wgDisableAuthManager ) {
2585 $id = self
::idFromName( $this->getName(), self
::READ_LATEST
);
2587 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2590 $passwordFactory = new PasswordFactory();
2591 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
2592 $dbw = wfGetDB( DB_MASTER
);
2596 'user_password' => $passwordFactory->newFromPlaintext( $str )->toString(),
2597 'user_newpassword' => PasswordFactory
::newInvalidPassword()->toString(),
2598 'user_newpass_time' => $dbw->timestampOrNull( null ),
2606 // When the main password is changed, invalidate all bot passwords too
2607 BotPassword
::invalidateAllPasswordsForUser( $this->getName() );
2609 $manager = AuthManager
::singleton();
2611 // If the user doesn't exist yet, fail
2612 if ( !$manager->userExists( $this->getName() ) ) {
2613 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2617 'username' => $this->getName(),
2621 $reqs = $manager->getAuthenticationRequests( AuthManager
::ACTION_CHANGE
, $this );
2622 $reqs = AuthenticationRequest
::loadRequestsFromSubmission( $reqs, $data );
2623 foreach ( $reqs as $req ) {
2624 $status = $manager->allowsAuthenticationDataChange( $req );
2625 if ( !$status->isOk() ) {
2626 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
2627 ->info( __METHOD__
. ': Password change rejected: ' . $status->getWikiText() );
2631 foreach ( $reqs as $req ) {
2632 $manager->changeAuthenticationData( $req );
2635 $this->setOption( 'watchlisttoken', false );
2638 SessionManager
::singleton()->invalidateSessionsForUser( $this );
2644 * Get the user's current token.
2645 * @param bool $forceCreation Force the generation of a new token if the
2646 * user doesn't have one (default=true for backwards compatibility).
2647 * @return string|null Token
2649 public function getToken( $forceCreation = true ) {
2650 global $wgAuthenticationTokenVersion;
2653 if ( !$this->mToken
&& $forceCreation ) {
2657 if ( !$this->mToken
) {
2658 // The user doesn't have a token, return null to indicate that.
2660 } elseif ( $this->mToken
=== self
::INVALID_TOKEN
) {
2661 // We return a random value here so existing token checks are very
2663 return MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2664 } elseif ( $wgAuthenticationTokenVersion === null ) {
2665 // $wgAuthenticationTokenVersion not in use, so return the raw secret
2666 return $this->mToken
;
2668 // $wgAuthenticationTokenVersion in use, so hmac it.
2669 $ret = MWCryptHash
::hmac( $wgAuthenticationTokenVersion, $this->mToken
, false );
2671 // The raw hash can be overly long. Shorten it up.
2672 $len = max( 32, self
::TOKEN_LENGTH
);
2673 if ( strlen( $ret ) < $len ) {
2674 // Should never happen, even md5 is 128 bits
2675 throw new \
UnexpectedValueException( 'Hmac returned less than 128 bits' );
2677 return substr( $ret, -$len );
2682 * Set the random token (used for persistent authentication)
2683 * Called from loadDefaults() among other places.
2685 * @param string|bool $token If specified, set the token to this value
2687 public function setToken( $token = false ) {
2689 if ( $this->mToken
=== self
::INVALID_TOKEN
) {
2690 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
2691 ->debug( __METHOD__
. ": Ignoring attempt to set token for system user \"$this\"" );
2692 } elseif ( !$token ) {
2693 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2695 $this->mToken
= $token;
2700 * Set the password for a password reminder or new account email
2702 * @deprecated Removed in 1.27. Use PasswordReset instead.
2703 * @param string $str New password to set or null to set an invalid
2704 * password hash meaning that the user will not be able to use it
2705 * @param bool $throttle If true, reset the throttle timestamp to the present
2707 public function setNewpassword( $str, $throttle = true ) {
2708 global $wgDisableAuthManager;
2710 if ( $wgDisableAuthManager ) {
2711 $id = $this->getId();
2713 throw new LogicException( 'Cannot set new password for a user that is not in the database.' );
2716 $dbw = wfGetDB( DB_MASTER
);
2718 $passwordFactory = new PasswordFactory();
2719 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
2721 'user_newpassword' => $passwordFactory->newFromPlaintext( $str )->toString(),
2724 if ( $str === null ) {
2725 $update['user_newpass_time'] = null;
2726 } elseif ( $throttle ) {
2727 $update['user_newpass_time'] = $dbw->timestamp();
2730 $dbw->update( 'user', $update, [ 'user_id' => $id ], __METHOD__
);
2732 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2737 * Has password reminder email been sent within the last
2738 * $wgPasswordReminderResendTime hours?
2739 * @deprecated Removed in 1.27. See above.
2742 public function isPasswordReminderThrottled() {
2743 global $wgPasswordReminderResendTime, $wgDisableAuthManager;
2745 if ( $wgDisableAuthManager ) {
2746 if ( !$wgPasswordReminderResendTime ) {
2752 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
2753 ?
wfGetDB( DB_MASTER
)
2754 : wfGetDB( DB_SLAVE
);
2755 $newpassTime = $db->selectField(
2757 'user_newpass_time',
2758 [ 'user_id' => $this->getId() ],
2762 if ( $newpassTime === null ) {
2765 $expiry = wfTimestamp( TS_UNIX
, $newpassTime ) +
$wgPasswordReminderResendTime * 3600;
2766 return time() < $expiry;
2768 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2773 * Get the user's e-mail address
2774 * @return string User's email address
2776 public function getEmail() {
2778 Hooks
::run( 'UserGetEmail', [ $this, &$this->mEmail
] );
2779 return $this->mEmail
;
2783 * Get the timestamp of the user's e-mail authentication
2784 * @return string TS_MW timestamp
2786 public function getEmailAuthenticationTimestamp() {
2788 Hooks
::run( 'UserGetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
2789 return $this->mEmailAuthenticated
;
2793 * Set the user's e-mail address
2794 * @param string $str New e-mail address
2796 public function setEmail( $str ) {
2798 if ( $str == $this->mEmail
) {
2801 $this->invalidateEmail();
2802 $this->mEmail
= $str;
2803 Hooks
::run( 'UserSetEmail', [ $this, &$this->mEmail
] );
2807 * Set the user's e-mail address and a confirmation mail if needed.
2810 * @param string $str New e-mail address
2813 public function setEmailWithConfirmation( $str ) {
2814 global $wgEnableEmail, $wgEmailAuthentication;
2816 if ( !$wgEnableEmail ) {
2817 return Status
::newFatal( 'emaildisabled' );
2820 $oldaddr = $this->getEmail();
2821 if ( $str === $oldaddr ) {
2822 return Status
::newGood( true );
2825 $type = $oldaddr != '' ?
'changed' : 'set';
2826 $notificationResult = null;
2828 if ( $wgEmailAuthentication ) {
2829 // Send the user an email notifying the user of the change in registered
2830 // email address on their previous email address
2831 if ( $type == 'changed' ) {
2832 $change = $str != '' ?
'changed' : 'removed';
2833 $notificationResult = $this->sendMail(
2834 wfMessage( 'notificationemail_subject_' . $change )->text(),
2835 wfMessage( 'notificationemail_body_' . $change,
2836 $this->getRequest()->getIP(),
2843 $this->setEmail( $str );
2845 if ( $str !== '' && $wgEmailAuthentication ) {
2846 // Send a confirmation request to the new address if needed
2847 $result = $this->sendConfirmationMail( $type );
2849 if ( $notificationResult !== null ) {
2850 $result->merge( $notificationResult );
2853 if ( $result->isGood() ) {
2854 // Say to the caller that a confirmation and notification mail has been sent
2855 $result->value
= 'eauth';
2858 $result = Status
::newGood( true );
2865 * Get the user's real name
2866 * @return string User's real name
2868 public function getRealName() {
2869 if ( !$this->isItemLoaded( 'realname' ) ) {
2873 return $this->mRealName
;
2877 * Set the user's real name
2878 * @param string $str New real name
2880 public function setRealName( $str ) {
2882 $this->mRealName
= $str;
2886 * Get the user's current setting for a given option.
2888 * @param string $oname The option to check
2889 * @param string $defaultOverride A default value returned if the option does not exist
2890 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2891 * @return string User's current value for the option
2892 * @see getBoolOption()
2893 * @see getIntOption()
2895 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2896 global $wgHiddenPrefs;
2897 $this->loadOptions();
2899 # We want 'disabled' preferences to always behave as the default value for
2900 # users, even if they have set the option explicitly in their settings (ie they
2901 # set it, and then it was disabled removing their ability to change it). But
2902 # we don't want to erase the preferences in the database in case the preference
2903 # is re-enabled again. So don't touch $mOptions, just override the returned value
2904 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2905 return self
::getDefaultOption( $oname );
2908 if ( array_key_exists( $oname, $this->mOptions
) ) {
2909 return $this->mOptions
[$oname];
2911 return $defaultOverride;
2916 * Get all user's options
2918 * @param int $flags Bitwise combination of:
2919 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2920 * to the default value. (Since 1.25)
2923 public function getOptions( $flags = 0 ) {
2924 global $wgHiddenPrefs;
2925 $this->loadOptions();
2926 $options = $this->mOptions
;
2928 # We want 'disabled' preferences to always behave as the default value for
2929 # users, even if they have set the option explicitly in their settings (ie they
2930 # set it, and then it was disabled removing their ability to change it). But
2931 # we don't want to erase the preferences in the database in case the preference
2932 # is re-enabled again. So don't touch $mOptions, just override the returned value
2933 foreach ( $wgHiddenPrefs as $pref ) {
2934 $default = self
::getDefaultOption( $pref );
2935 if ( $default !== null ) {
2936 $options[$pref] = $default;
2940 if ( $flags & self
::GETOPTIONS_EXCLUDE_DEFAULTS
) {
2941 $options = array_diff_assoc( $options, self
::getDefaultOptions() );
2948 * Get the user's current setting for a given option, as a boolean value.
2950 * @param string $oname The option to check
2951 * @return bool User's current value for the option
2954 public function getBoolOption( $oname ) {
2955 return (bool)$this->getOption( $oname );
2959 * Get the user's current setting for a given option, as an integer value.
2961 * @param string $oname The option to check
2962 * @param int $defaultOverride A default value returned if the option does not exist
2963 * @return int User's current value for the option
2966 public function getIntOption( $oname, $defaultOverride = 0 ) {
2967 $val = $this->getOption( $oname );
2969 $val = $defaultOverride;
2971 return intval( $val );
2975 * Set the given option for a user.
2977 * You need to call saveSettings() to actually write to the database.
2979 * @param string $oname The option to set
2980 * @param mixed $val New value to set
2982 public function setOption( $oname, $val ) {
2983 $this->loadOptions();
2985 // Explicitly NULL values should refer to defaults
2986 if ( is_null( $val ) ) {
2987 $val = self
::getDefaultOption( $oname );
2990 $this->mOptions
[$oname] = $val;
2994 * Get a token stored in the preferences (like the watchlist one),
2995 * resetting it if it's empty (and saving changes).
2997 * @param string $oname The option name to retrieve the token from
2998 * @return string|bool User's current value for the option, or false if this option is disabled.
2999 * @see resetTokenFromOption()
3001 * @deprecated 1.26 Applications should use the OAuth extension
3003 public function getTokenFromOption( $oname ) {
3004 global $wgHiddenPrefs;
3006 $id = $this->getId();
3007 if ( !$id ||
in_array( $oname, $wgHiddenPrefs ) ) {
3011 $token = $this->getOption( $oname );
3013 // Default to a value based on the user token to avoid space
3014 // wasted on storing tokens for all users. When this option
3015 // is set manually by the user, only then is it stored.
3016 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
3023 * Reset a token stored in the preferences (like the watchlist one).
3024 * *Does not* save user's preferences (similarly to setOption()).
3026 * @param string $oname The option name to reset the token in
3027 * @return string|bool New token value, or false if this option is disabled.
3028 * @see getTokenFromOption()
3031 public function resetTokenFromOption( $oname ) {
3032 global $wgHiddenPrefs;
3033 if ( in_array( $oname, $wgHiddenPrefs ) ) {
3037 $token = MWCryptRand
::generateHex( 40 );
3038 $this->setOption( $oname, $token );
3043 * Return a list of the types of user options currently returned by
3044 * User::getOptionKinds().
3046 * Currently, the option kinds are:
3047 * - 'registered' - preferences which are registered in core MediaWiki or
3048 * by extensions using the UserGetDefaultOptions hook.
3049 * - 'registered-multiselect' - as above, using the 'multiselect' type.
3050 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
3051 * - 'userjs' - preferences with names starting with 'userjs-', intended to
3052 * be used by user scripts.
3053 * - 'special' - "preferences" that are not accessible via User::getOptions
3054 * or User::setOptions.
3055 * - 'unused' - preferences about which MediaWiki doesn't know anything.
3056 * These are usually legacy options, removed in newer versions.
3058 * The API (and possibly others) use this function to determine the possible
3059 * option types for validation purposes, so make sure to update this when a
3060 * new option kind is added.
3062 * @see User::getOptionKinds
3063 * @return array Option kinds
3065 public static function listOptionKinds() {
3068 'registered-multiselect',
3069 'registered-checkmatrix',
3077 * Return an associative array mapping preferences keys to the kind of a preference they're
3078 * used for. Different kinds are handled differently when setting or reading preferences.
3080 * See User::listOptionKinds for the list of valid option types that can be provided.
3082 * @see User::listOptionKinds
3083 * @param IContextSource $context
3084 * @param array $options Assoc. array with options keys to check as keys.
3085 * Defaults to $this->mOptions.
3086 * @return array The key => kind mapping data
3088 public function getOptionKinds( IContextSource
$context, $options = null ) {
3089 $this->loadOptions();
3090 if ( $options === null ) {
3091 $options = $this->mOptions
;
3094 $prefs = Preferences
::getPreferences( $this, $context );
3097 // Pull out the "special" options, so they don't get converted as
3098 // multiselect or checkmatrix.
3099 $specialOptions = array_fill_keys( Preferences
::getSaveBlacklist(), true );
3100 foreach ( $specialOptions as $name => $value ) {
3101 unset( $prefs[$name] );
3104 // Multiselect and checkmatrix options are stored in the database with
3105 // one key per option, each having a boolean value. Extract those keys.
3106 $multiselectOptions = [];
3107 foreach ( $prefs as $name => $info ) {
3108 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
3109 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
3110 $opts = HTMLFormField
::flattenOptions( $info['options'] );
3111 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
3113 foreach ( $opts as $value ) {
3114 $multiselectOptions["$prefix$value"] = true;
3117 unset( $prefs[$name] );
3120 $checkmatrixOptions = [];
3121 foreach ( $prefs as $name => $info ) {
3122 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
3123 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
3124 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
3125 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
3126 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
3128 foreach ( $columns as $column ) {
3129 foreach ( $rows as $row ) {
3130 $checkmatrixOptions["$prefix$column-$row"] = true;
3134 unset( $prefs[$name] );
3138 // $value is ignored
3139 foreach ( $options as $key => $value ) {
3140 if ( isset( $prefs[$key] ) ) {
3141 $mapping[$key] = 'registered';
3142 } elseif ( isset( $multiselectOptions[$key] ) ) {
3143 $mapping[$key] = 'registered-multiselect';
3144 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
3145 $mapping[$key] = 'registered-checkmatrix';
3146 } elseif ( isset( $specialOptions[$key] ) ) {
3147 $mapping[$key] = 'special';
3148 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
3149 $mapping[$key] = 'userjs';
3151 $mapping[$key] = 'unused';
3159 * Reset certain (or all) options to the site defaults
3161 * The optional parameter determines which kinds of preferences will be reset.
3162 * Supported values are everything that can be reported by getOptionKinds()
3163 * and 'all', which forces a reset of *all* preferences and overrides everything else.
3165 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
3166 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
3167 * for backwards-compatibility.
3168 * @param IContextSource|null $context Context source used when $resetKinds
3169 * does not contain 'all', passed to getOptionKinds().
3170 * Defaults to RequestContext::getMain() when null.
3172 public function resetOptions(
3173 $resetKinds = [ 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ],
3174 IContextSource
$context = null
3177 $defaultOptions = self
::getDefaultOptions();
3179 if ( !is_array( $resetKinds ) ) {
3180 $resetKinds = [ $resetKinds ];
3183 if ( in_array( 'all', $resetKinds ) ) {
3184 $newOptions = $defaultOptions;
3186 if ( $context === null ) {
3187 $context = RequestContext
::getMain();
3190 $optionKinds = $this->getOptionKinds( $context );
3191 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
3194 // Use default values for the options that should be deleted, and
3195 // copy old values for the ones that shouldn't.
3196 foreach ( $this->mOptions
as $key => $value ) {
3197 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
3198 if ( array_key_exists( $key, $defaultOptions ) ) {
3199 $newOptions[$key] = $defaultOptions[$key];
3202 $newOptions[$key] = $value;
3207 Hooks
::run( 'UserResetAllOptions', [ $this, &$newOptions, $this->mOptions
, $resetKinds ] );
3209 $this->mOptions
= $newOptions;
3210 $this->mOptionsLoaded
= true;
3214 * Get the user's preferred date format.
3215 * @return string User's preferred date format
3217 public function getDatePreference() {
3218 // Important migration for old data rows
3219 if ( is_null( $this->mDatePreference
) ) {
3221 $value = $this->getOption( 'date' );
3222 $map = $wgLang->getDatePreferenceMigrationMap();
3223 if ( isset( $map[$value] ) ) {
3224 $value = $map[$value];
3226 $this->mDatePreference
= $value;
3228 return $this->mDatePreference
;
3232 * Determine based on the wiki configuration and the user's options,
3233 * whether this user must be over HTTPS no matter what.
3237 public function requiresHTTPS() {
3238 global $wgSecureLogin;
3239 if ( !$wgSecureLogin ) {
3242 $https = $this->getBoolOption( 'prefershttps' );
3243 Hooks
::run( 'UserRequiresHTTPS', [ $this, &$https ] );
3245 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
3252 * Get the user preferred stub threshold
3256 public function getStubThreshold() {
3257 global $wgMaxArticleSize; # Maximum article size, in Kb
3258 $threshold = $this->getIntOption( 'stubthreshold' );
3259 if ( $threshold > $wgMaxArticleSize * 1024 ) {
3260 // If they have set an impossible value, disable the preference
3261 // so we can use the parser cache again.
3268 * Get the permissions this user has.
3269 * @return array Array of String permission names
3271 public function getRights() {
3272 if ( is_null( $this->mRights
) ) {
3273 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
3275 // Deny any rights denied by the user's session, unless this
3276 // endpoint has no sessions.
3277 if ( !defined( 'MW_NO_SESSION' ) ) {
3278 $allowedRights = $this->getRequest()->getSession()->getAllowedUserRights();
3279 if ( $allowedRights !== null ) {
3280 $this->mRights
= array_intersect( $this->mRights
, $allowedRights );
3284 Hooks
::run( 'UserGetRights', [ $this, &$this->mRights
] );
3285 // Force reindexation of rights when a hook has unset one of them
3286 $this->mRights
= array_values( array_unique( $this->mRights
) );
3288 return $this->mRights
;
3292 * Get the list of explicit group memberships this user has.
3293 * The implicit * and user groups are not included.
3294 * @return array Array of String internal group names
3296 public function getGroups() {
3298 $this->loadGroups();
3299 return $this->mGroups
;
3303 * Get the list of implicit group memberships this user has.
3304 * This includes all explicit groups, plus 'user' if logged in,
3305 * '*' for all accounts, and autopromoted groups
3306 * @param bool $recache Whether to avoid the cache
3307 * @return array Array of String internal group names
3309 public function getEffectiveGroups( $recache = false ) {
3310 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
3311 $this->mEffectiveGroups
= array_unique( array_merge(
3312 $this->getGroups(), // explicit groups
3313 $this->getAutomaticGroups( $recache ) // implicit groups
3315 // Hook for additional groups
3316 Hooks
::run( 'UserEffectiveGroups', [ &$this, &$this->mEffectiveGroups
] );
3317 // Force reindexation of groups when a hook has unset one of them
3318 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
3320 return $this->mEffectiveGroups
;
3324 * Get the list of implicit group memberships this user has.
3325 * This includes 'user' if logged in, '*' for all accounts,
3326 * and autopromoted groups
3327 * @param bool $recache Whether to avoid the cache
3328 * @return array Array of String internal group names
3330 public function getAutomaticGroups( $recache = false ) {
3331 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
3332 $this->mImplicitGroups
= [ '*' ];
3333 if ( $this->getId() ) {
3334 $this->mImplicitGroups
[] = 'user';
3336 $this->mImplicitGroups
= array_unique( array_merge(
3337 $this->mImplicitGroups
,
3338 Autopromote
::getAutopromoteGroups( $this )
3342 // Assure data consistency with rights/groups,
3343 // as getEffectiveGroups() depends on this function
3344 $this->mEffectiveGroups
= null;
3347 return $this->mImplicitGroups
;
3351 * Returns the groups the user has belonged to.
3353 * The user may still belong to the returned groups. Compare with getGroups().
3355 * The function will not return groups the user had belonged to before MW 1.17
3357 * @return array Names of the groups the user has belonged to.
3359 public function getFormerGroups() {
3362 if ( is_null( $this->mFormerGroups
) ) {
3363 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3364 ?
wfGetDB( DB_MASTER
)
3365 : wfGetDB( DB_SLAVE
);
3366 $res = $db->select( 'user_former_groups',
3368 [ 'ufg_user' => $this->mId
],
3370 $this->mFormerGroups
= [];
3371 foreach ( $res as $row ) {
3372 $this->mFormerGroups
[] = $row->ufg_group
;
3376 return $this->mFormerGroups
;
3380 * Get the user's edit count.
3381 * @return int|null Null for anonymous users
3383 public function getEditCount() {
3384 if ( !$this->getId() ) {
3388 if ( $this->mEditCount
=== null ) {
3389 /* Populate the count, if it has not been populated yet */
3390 $dbr = wfGetDB( DB_SLAVE
);
3391 // check if the user_editcount field has been initialized
3392 $count = $dbr->selectField(
3393 'user', 'user_editcount',
3394 [ 'user_id' => $this->mId
],
3398 if ( $count === null ) {
3399 // it has not been initialized. do so.
3400 $count = $this->initEditCount();
3402 $this->mEditCount
= $count;
3404 return (int)$this->mEditCount
;
3408 * Add the user to the given group.
3409 * This takes immediate effect.
3410 * @param string $group Name of the group to add
3413 public function addGroup( $group ) {
3416 if ( !Hooks
::run( 'UserAddGroup', [ $this, &$group ] ) ) {
3420 $dbw = wfGetDB( DB_MASTER
);
3421 if ( $this->getId() ) {
3422 $dbw->insert( 'user_groups',
3424 'ug_user' => $this->getId(),
3425 'ug_group' => $group,
3431 $this->loadGroups();
3432 $this->mGroups
[] = $group;
3433 // In case loadGroups was not called before, we now have the right twice.
3434 // Get rid of the duplicate.
3435 $this->mGroups
= array_unique( $this->mGroups
);
3437 // Refresh the groups caches, and clear the rights cache so it will be
3438 // refreshed on the next call to $this->getRights().
3439 $this->getEffectiveGroups( true );
3440 $this->mRights
= null;
3442 $this->invalidateCache();
3448 * Remove the user from the given group.
3449 * This takes immediate effect.
3450 * @param string $group Name of the group to remove
3453 public function removeGroup( $group ) {
3455 if ( !Hooks
::run( 'UserRemoveGroup', [ $this, &$group ] ) ) {
3459 $dbw = wfGetDB( DB_MASTER
);
3460 $dbw->delete( 'user_groups',
3462 'ug_user' => $this->getId(),
3463 'ug_group' => $group,
3466 // Remember that the user was in this group
3467 $dbw->insert( 'user_former_groups',
3469 'ufg_user' => $this->getId(),
3470 'ufg_group' => $group,
3476 $this->loadGroups();
3477 $this->mGroups
= array_diff( $this->mGroups
, [ $group ] );
3479 // Refresh the groups caches, and clear the rights cache so it will be
3480 // refreshed on the next call to $this->getRights().
3481 $this->getEffectiveGroups( true );
3482 $this->mRights
= null;
3484 $this->invalidateCache();
3490 * Get whether the user is logged in
3493 public function isLoggedIn() {
3494 return $this->getId() != 0;
3498 * Get whether the user is anonymous
3501 public function isAnon() {
3502 return !$this->isLoggedIn();
3506 * @return bool Whether this user is flagged as being a bot role account
3509 public function isBot() {
3510 if ( in_array( 'bot', $this->getGroups() ) && $this->isAllowed( 'bot' ) ) {
3515 Hooks
::run( "UserIsBot", [ $this, &$isBot ] );
3521 * Check if user is allowed to access a feature / make an action
3523 * @param string ... Permissions to test
3524 * @return bool True if user is allowed to perform *any* of the given actions
3526 public function isAllowedAny() {
3527 $permissions = func_get_args();
3528 foreach ( $permissions as $permission ) {
3529 if ( $this->isAllowed( $permission ) ) {
3538 * @param string ... Permissions to test
3539 * @return bool True if the user is allowed to perform *all* of the given actions
3541 public function isAllowedAll() {
3542 $permissions = func_get_args();
3543 foreach ( $permissions as $permission ) {
3544 if ( !$this->isAllowed( $permission ) ) {
3552 * Internal mechanics of testing a permission
3553 * @param string $action
3556 public function isAllowed( $action = '' ) {
3557 if ( $action === '' ) {
3558 return true; // In the spirit of DWIM
3560 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3561 // by misconfiguration: 0 == 'foo'
3562 return in_array( $action, $this->getRights(), true );
3566 * Check whether to enable recent changes patrol features for this user
3567 * @return bool True or false
3569 public function useRCPatrol() {
3570 global $wgUseRCPatrol;
3571 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3575 * Check whether to enable new pages patrol features for this user
3576 * @return bool True or false
3578 public function useNPPatrol() {
3579 global $wgUseRCPatrol, $wgUseNPPatrol;
3581 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3582 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3587 * Check whether to enable new files patrol features for this user
3588 * @return bool True or false
3590 public function useFilePatrol() {
3591 global $wgUseRCPatrol, $wgUseFilePatrol;
3593 ( $wgUseRCPatrol ||
$wgUseFilePatrol )
3594 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3599 * Get the WebRequest object to use with this object
3601 * @return WebRequest
3603 public function getRequest() {
3604 if ( $this->mRequest
) {
3605 return $this->mRequest
;
3613 * Check the watched status of an article.
3614 * @since 1.22 $checkRights parameter added
3615 * @param Title $title Title of the article to look at
3616 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3617 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3620 public function isWatched( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3621 if ( $title->isWatchable() && ( !$checkRights ||
$this->isAllowed( 'viewmywatchlist' ) ) ) {
3622 return MediaWikiServices
::getInstance()->getWatchedItemStore()->isWatched( $this, $title );
3629 * @since 1.22 $checkRights parameter added
3630 * @param Title $title Title of the article to look at
3631 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3632 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3634 public function addWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3635 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3636 MediaWikiServices
::getInstance()->getWatchedItemStore()->addWatchBatchForUser(
3638 [ $title->getSubjectPage(), $title->getTalkPage() ]
3641 $this->invalidateCache();
3645 * Stop watching an article.
3646 * @since 1.22 $checkRights parameter added
3647 * @param Title $title Title of the article to look at
3648 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3649 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3651 public function removeWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3652 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3653 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
3654 $store->removeWatch( $this, $title->getSubjectPage() );
3655 $store->removeWatch( $this, $title->getTalkPage() );
3657 $this->invalidateCache();
3661 * Clear the user's notification timestamp for the given title.
3662 * If e-notif e-mails are on, they will receive notification mails on
3663 * the next change of the page if it's watched etc.
3664 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3665 * @param Title $title Title of the article to look at
3666 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3668 public function clearNotification( &$title, $oldid = 0 ) {
3669 global $wgUseEnotif, $wgShowUpdatedMarker;
3671 // Do nothing if the database is locked to writes
3672 if ( wfReadOnly() ) {
3676 // Do nothing if not allowed to edit the watchlist
3677 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3681 // If we're working on user's talk page, we should update the talk page message indicator
3682 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3683 if ( !Hooks
::run( 'UserClearNewTalkNotification', [ &$this, $oldid ] ) ) {
3687 // Try to update the DB post-send and only if needed...
3688 DeferredUpdates
::addCallableUpdate( function() use ( $title, $oldid ) {
3689 if ( !$this->getNewtalk() ) {
3690 return; // no notifications to clear
3693 // Delete the last notifications (they stack up)
3694 $this->setNewtalk( false );
3696 // If there is a new, unseen, revision, use its timestamp
3698 ?
$title->getNextRevisionID( $oldid, Title
::GAID_FOR_UPDATE
)
3701 $this->setNewtalk( true, Revision
::newFromId( $nextid ) );
3706 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3710 if ( $this->isAnon() ) {
3711 // Nothing else to do...
3715 // Only update the timestamp if the page is being watched.
3716 // The query to find out if it is watched is cached both in memcached and per-invocation,
3717 // and when it does have to be executed, it can be on a slave
3718 // If this is the user's newtalk page, we always update the timestamp
3720 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3724 MediaWikiServices
::getInstance()->getWatchedItemStore()
3725 ->resetNotificationTimestamp( $this, $title, $force, $oldid );
3729 * Resets all of the given user's page-change notification timestamps.
3730 * If e-notif e-mails are on, they will receive notification mails on
3731 * the next change of any watched page.
3732 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3734 public function clearAllNotifications() {
3735 if ( wfReadOnly() ) {
3739 // Do nothing if not allowed to edit the watchlist
3740 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3744 global $wgUseEnotif, $wgShowUpdatedMarker;
3745 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3746 $this->setNewtalk( false );
3749 $id = $this->getId();
3751 $dbw = wfGetDB( DB_MASTER
);
3752 $dbw->update( 'watchlist',
3753 [ /* SET */ 'wl_notificationtimestamp' => null ],
3754 [ /* WHERE */ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ],
3757 // We also need to clear here the "you have new message" notification for the own user_talk page;
3758 // it's cleared one page view later in WikiPage::doViewUpdates().
3763 * Set a cookie on the user's client. Wrapper for
3764 * WebResponse::setCookie
3765 * @deprecated since 1.27
3766 * @param string $name Name of the cookie to set
3767 * @param string $value Value to set
3768 * @param int $exp Expiration time, as a UNIX time value;
3769 * if 0 or not specified, use the default $wgCookieExpiration
3770 * @param bool $secure
3771 * true: Force setting the secure attribute when setting the cookie
3772 * false: Force NOT setting the secure attribute when setting the cookie
3773 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3774 * @param array $params Array of options sent passed to WebResponse::setcookie()
3775 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3778 protected function setCookie(
3779 $name, $value, $exp = 0, $secure = null, $params = [], $request = null
3781 wfDeprecated( __METHOD__
, '1.27' );
3782 if ( $request === null ) {
3783 $request = $this->getRequest();
3785 $params['secure'] = $secure;
3786 $request->response()->setCookie( $name, $value, $exp, $params );
3790 * Clear a cookie on the user's client
3791 * @deprecated since 1.27
3792 * @param string $name Name of the cookie to clear
3793 * @param bool $secure
3794 * true: Force setting the secure attribute when setting the cookie
3795 * false: Force NOT setting the secure attribute when setting the cookie
3796 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3797 * @param array $params Array of options sent passed to WebResponse::setcookie()
3799 protected function clearCookie( $name, $secure = null, $params = [] ) {
3800 wfDeprecated( __METHOD__
, '1.27' );
3801 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3805 * Set an extended login cookie on the user's client. The expiry of the cookie
3806 * is controlled by the $wgExtendedLoginCookieExpiration configuration
3809 * @see User::setCookie
3811 * @deprecated since 1.27
3812 * @param string $name Name of the cookie to set
3813 * @param string $value Value to set
3814 * @param bool $secure
3815 * true: Force setting the secure attribute when setting the cookie
3816 * false: Force NOT setting the secure attribute when setting the cookie
3817 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3819 protected function setExtendedLoginCookie( $name, $value, $secure ) {
3820 global $wgExtendedLoginCookieExpiration, $wgCookieExpiration;
3822 wfDeprecated( __METHOD__
, '1.27' );
3825 $exp +
= $wgExtendedLoginCookieExpiration !== null
3826 ?
$wgExtendedLoginCookieExpiration
3827 : $wgCookieExpiration;
3829 $this->setCookie( $name, $value, $exp, $secure );
3833 * Persist this user's session (e.g. set cookies)
3835 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3837 * @param bool $secure Whether to force secure/insecure cookies or use default
3838 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3840 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3842 if ( 0 == $this->mId
) {
3846 $session = $this->getRequest()->getSession();
3847 if ( $request && $session->getRequest() !== $request ) {
3848 $session = $session->sessionWithRequest( $request );
3850 $delay = $session->delaySave();
3852 if ( !$session->getUser()->equals( $this ) ) {
3853 if ( !$session->canSetUser() ) {
3854 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3855 ->warning( __METHOD__
.
3856 ": Cannot save user \"$this\" to a user \"{$session->getUser()}\"'s immutable session"
3860 $session->setUser( $this );
3863 $session->setRememberUser( $rememberMe );
3864 if ( $secure !== null ) {
3865 $session->setForceHTTPS( $secure );
3868 $session->persist();
3870 ScopedCallback
::consume( $delay );
3874 * Log this user out.
3876 public function logout() {
3877 if ( Hooks
::run( 'UserLogout', [ &$this ] ) ) {
3883 * Clear the user's session, and reset the instance cache.
3886 public function doLogout() {
3887 $session = $this->getRequest()->getSession();
3888 if ( !$session->canSetUser() ) {
3889 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3890 ->warning( __METHOD__
. ": Cannot log out of an immutable session" );
3891 $error = 'immutable';
3892 } elseif ( !$session->getUser()->equals( $this ) ) {
3893 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3894 ->warning( __METHOD__
.
3895 ": Cannot log user \"$this\" out of a user \"{$session->getUser()}\"'s session"
3897 // But we still may as well make this user object anon
3898 $this->clearInstanceCache( 'defaults' );
3899 $error = 'wronguser';
3901 $this->clearInstanceCache( 'defaults' );
3902 $delay = $session->delaySave();
3903 $session->unpersist(); // Clear cookies (T127436)
3904 $session->setLoggedOutTimestamp( time() );
3905 $session->setUser( new User
);
3906 $session->set( 'wsUserID', 0 ); // Other code expects this
3907 ScopedCallback
::consume( $delay );
3910 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authmanager' )->info( 'Logout', [
3911 'event' => 'logout',
3912 'successful' => $error === false,
3913 'status' => $error ?
: 'success',
3918 * Save this user's settings into the database.
3919 * @todo Only rarely do all these fields need to be set!
3921 public function saveSettings() {
3922 if ( wfReadOnly() ) {
3923 // @TODO: caller should deal with this instead!
3924 // This should really just be an exception.
3925 MWExceptionHandler
::logException( new DBExpectedError(
3927 "Could not update user with ID '{$this->mId}'; DB is read-only."
3933 if ( 0 == $this->mId
) {
3937 // Get a new user_touched that is higher than the old one.
3938 // This will be used for a CAS check as a last-resort safety
3939 // check against race conditions and slave lag.
3940 $newTouched = $this->newTouchedTimestamp();
3942 $dbw = wfGetDB( DB_MASTER
);
3943 $dbw->update( 'user',
3945 'user_name' => $this->mName
,
3946 'user_real_name' => $this->mRealName
,
3947 'user_email' => $this->mEmail
,
3948 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3949 'user_touched' => $dbw->timestamp( $newTouched ),
3950 'user_token' => strval( $this->mToken
),
3951 'user_email_token' => $this->mEmailToken
,
3952 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
3953 ], $this->makeUpdateConditions( $dbw, [ /* WHERE */
3954 'user_id' => $this->mId
,
3958 if ( !$dbw->affectedRows() ) {
3959 // Maybe the problem was a missed cache update; clear it to be safe
3960 $this->clearSharedCache( 'refresh' );
3961 // User was changed in the meantime or loaded with stale data
3962 $from = ( $this->queryFlagsUsed
& self
::READ_LATEST
) ?
'master' : 'slave';
3963 throw new MWException(
3964 "CAS update failed on user_touched for user ID '{$this->mId}' (read from $from);" .
3965 " the version of the user to be saved is older than the current version."
3969 $this->mTouched
= $newTouched;
3970 $this->saveOptions();
3972 Hooks
::run( 'UserSaveSettings', [ $this ] );
3973 $this->clearSharedCache();
3974 $this->getUserPage()->invalidateCache();
3978 * If only this user's username is known, and it exists, return the user ID.
3980 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
3983 public function idForName( $flags = 0 ) {
3984 $s = trim( $this->getName() );
3989 $db = ( ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
)
3990 ?
wfGetDB( DB_MASTER
)
3991 : wfGetDB( DB_SLAVE
);
3993 $options = ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
)
3994 ?
[ 'LOCK IN SHARE MODE' ]
3997 $id = $db->selectField( 'user',
3998 'user_id', [ 'user_name' => $s ], __METHOD__
, $options );
4004 * Add a user to the database, return the user object
4006 * @param string $name Username to add
4007 * @param array $params Array of Strings Non-default parameters to save to
4008 * the database as user_* fields:
4009 * - email: The user's email address.
4010 * - email_authenticated: The email authentication timestamp.
4011 * - real_name: The user's real name.
4012 * - options: An associative array of non-default options.
4013 * - token: Random authentication token. Do not set.
4014 * - registration: Registration timestamp. Do not set.
4016 * @return User|null User object, or null if the username already exists.
4018 public static function createNew( $name, $params = [] ) {
4019 foreach ( [ 'password', 'newpassword', 'newpass_time', 'password_expires' ] as $field ) {
4020 if ( isset( $params[$field] ) ) {
4021 wfDeprecated( __METHOD__
. " with param '$field'", '1.27' );
4022 unset( $params[$field] );
4028 $user->setToken(); // init token
4029 if ( isset( $params['options'] ) ) {
4030 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
4031 unset( $params['options'] );
4033 $dbw = wfGetDB( DB_MASTER
);
4034 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
4036 $noPass = PasswordFactory
::newInvalidPassword()->toString();
4039 'user_id' => $seqVal,
4040 'user_name' => $name,
4041 'user_password' => $noPass,
4042 'user_newpassword' => $noPass,
4043 'user_email' => $user->mEmail
,
4044 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
4045 'user_real_name' => $user->mRealName
,
4046 'user_token' => strval( $user->mToken
),
4047 'user_registration' => $dbw->timestamp( $user->mRegistration
),
4048 'user_editcount' => 0,
4049 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
4051 foreach ( $params as $name => $value ) {
4052 $fields["user_$name"] = $value;
4054 $dbw->insert( 'user', $fields, __METHOD__
, [ 'IGNORE' ] );
4055 if ( $dbw->affectedRows() ) {
4056 $newUser = User
::newFromId( $dbw->insertId() );
4064 * Add this existing user object to the database. If the user already
4065 * exists, a fatal status object is returned, and the user object is
4066 * initialised with the data from the database.
4068 * Previously, this function generated a DB error due to a key conflict
4069 * if the user already existed. Many extension callers use this function
4070 * in code along the lines of:
4072 * $user = User::newFromName( $name );
4073 * if ( !$user->isLoggedIn() ) {
4074 * $user->addToDatabase();
4076 * // do something with $user...
4078 * However, this was vulnerable to a race condition (bug 16020). By
4079 * initialising the user object if the user exists, we aim to support this
4080 * calling sequence as far as possible.
4082 * Note that if the user exists, this function will acquire a write lock,
4083 * so it is still advisable to make the call conditional on isLoggedIn(),
4084 * and to commit the transaction after calling.
4086 * @throws MWException
4089 public function addToDatabase() {
4091 if ( !$this->mToken
) {
4092 $this->setToken(); // init token
4095 $this->mTouched
= $this->newTouchedTimestamp();
4097 $noPass = PasswordFactory
::newInvalidPassword()->toString();
4099 $dbw = wfGetDB( DB_MASTER
);
4100 $inWrite = $dbw->writesOrCallbacksPending();
4101 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
4102 $dbw->insert( 'user',
4104 'user_id' => $seqVal,
4105 'user_name' => $this->mName
,
4106 'user_password' => $noPass,
4107 'user_newpassword' => $noPass,
4108 'user_email' => $this->mEmail
,
4109 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
4110 'user_real_name' => $this->mRealName
,
4111 'user_token' => strval( $this->mToken
),
4112 'user_registration' => $dbw->timestamp( $this->mRegistration
),
4113 'user_editcount' => 0,
4114 'user_touched' => $dbw->timestamp( $this->mTouched
),
4118 if ( !$dbw->affectedRows() ) {
4119 // The queries below cannot happen in the same REPEATABLE-READ snapshot.
4120 // Handle this by COMMIT, if possible, or by LOCK IN SHARE MODE otherwise.
4122 // Can't commit due to pending writes that may need atomicity.
4123 // This may cause some lock contention unlike the case below.
4124 $options = [ 'LOCK IN SHARE MODE' ];
4125 $flags = self
::READ_LOCKING
;
4127 // Often, this case happens early in views before any writes when
4128 // using CentralAuth. It's should be OK to commit and break the snapshot.
4129 $dbw->commit( __METHOD__
, 'flush' );
4131 $flags = self
::READ_LATEST
;
4133 $this->mId
= $dbw->selectField( 'user', 'user_id',
4134 [ 'user_name' => $this->mName
], __METHOD__
, $options );
4137 if ( $this->loadFromDatabase( $flags ) ) {
4142 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
4143 "to insert user '{$this->mName}' row, but it was not present in select!" );
4145 return Status
::newFatal( 'userexists' );
4147 $this->mId
= $dbw->insertId();
4148 self
::$idCacheByName[$this->mName
] = $this->mId
;
4150 // Clear instance cache other than user table data, which is already accurate
4151 $this->clearInstanceCache();
4153 $this->saveOptions();
4154 return Status
::newGood();
4158 * If this user is logged-in and blocked,
4159 * block any IP address they've successfully logged in from.
4160 * @return bool A block was spread
4162 public function spreadAnyEditBlock() {
4163 if ( $this->isLoggedIn() && $this->isBlocked() ) {
4164 return $this->spreadBlock();
4171 * If this (non-anonymous) user is blocked,
4172 * block the IP address they've successfully logged in from.
4173 * @return bool A block was spread
4175 protected function spreadBlock() {
4176 wfDebug( __METHOD__
. "()\n" );
4178 if ( $this->mId
== 0 ) {
4182 $userblock = Block
::newFromTarget( $this->getName() );
4183 if ( !$userblock ) {
4187 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
4191 * Get whether the user is explicitly blocked from account creation.
4192 * @return bool|Block
4194 public function isBlockedFromCreateAccount() {
4195 $this->getBlockedStatus();
4196 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
4197 return $this->mBlock
;
4200 # bug 13611: if the IP address the user is trying to create an account from is
4201 # blocked with createaccount disabled, prevent new account creation there even
4202 # when the user is logged in
4203 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
4204 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
4206 return $this->mBlockedFromCreateAccount
instanceof Block
4207 && $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
4208 ?
$this->mBlockedFromCreateAccount
4213 * Get whether the user is blocked from using Special:Emailuser.
4216 public function isBlockedFromEmailuser() {
4217 $this->getBlockedStatus();
4218 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
4222 * Get whether the user is allowed to create an account.
4225 public function isAllowedToCreateAccount() {
4226 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
4230 * Get this user's personal page title.
4232 * @return Title User's personal page title
4234 public function getUserPage() {
4235 return Title
::makeTitle( NS_USER
, $this->getName() );
4239 * Get this user's talk page title.
4241 * @return Title User's talk page title
4243 public function getTalkPage() {
4244 $title = $this->getUserPage();
4245 return $title->getTalkPage();
4249 * Determine whether the user is a newbie. Newbies are either
4250 * anonymous IPs, or the most recently created accounts.
4253 public function isNewbie() {
4254 return !$this->isAllowed( 'autoconfirmed' );
4258 * Check to see if the given clear-text password is one of the accepted passwords
4259 * @deprecated since 1.27, use AuthManager instead
4260 * @param string $password User password
4261 * @return bool True if the given password is correct, otherwise False
4263 public function checkPassword( $password ) {
4264 global $wgAuth, $wgLegacyEncoding, $wgDisableAuthManager;
4266 if ( $wgDisableAuthManager ) {
4269 // Some passwords will give a fatal Status, which means there is
4270 // some sort of technical or security reason for this password to
4271 // be completely invalid and should never be checked (e.g., T64685)
4272 if ( !$this->checkPasswordValidity( $password )->isOK() ) {
4276 // Certain authentication plugins do NOT want to save
4277 // domain passwords in a mysql database, so we should
4278 // check this (in case $wgAuth->strict() is false).
4279 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
4281 } elseif ( $wgAuth->strict() ) {
4282 // Auth plugin doesn't allow local authentication
4284 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
4285 // Auth plugin doesn't allow local authentication for this user name
4289 $passwordFactory = new PasswordFactory();
4290 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4291 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
4292 ?
wfGetDB( DB_MASTER
)
4293 : wfGetDB( DB_SLAVE
);
4296 $mPassword = $passwordFactory->newFromCiphertext( $db->selectField(
4297 'user', 'user_password', [ 'user_id' => $this->getId() ], __METHOD__
4299 } catch ( PasswordError
$e ) {
4300 wfDebug( 'Invalid password hash found in database.' );
4301 $mPassword = PasswordFactory
::newInvalidPassword();
4304 if ( !$mPassword->equals( $password ) ) {
4305 if ( $wgLegacyEncoding ) {
4306 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
4307 // Check for this with iconv
4308 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
4309 if ( $cp1252Password === $password ||
!$mPassword->equals( $cp1252Password ) ) {
4317 if ( $passwordFactory->needsUpdate( $mPassword ) && !wfReadOnly() ) {
4318 $this->setPasswordInternal( $password );
4323 $manager = AuthManager
::singleton();
4324 $reqs = AuthenticationRequest
::loadRequestsFromSubmission(
4325 $manager->getAuthenticationRequests( AuthManager
::ACTION_LOGIN
),
4327 'username' => $this->getName(),
4328 'password' => $password,
4331 $res = AuthManager
::singleton()->beginAuthentication( $reqs, 'null:' );
4332 switch ( $res->status
) {
4333 case AuthenticationResponse
::PASS
:
4335 case AuthenticationResponse
::FAIL
:
4336 // Hope it's not a PreAuthenticationProvider that failed...
4337 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
4338 ->info( __METHOD__
. ': Authentication failed: ' . $res->message
->plain() );
4341 throw new BadMethodCallException(
4342 'AuthManager returned a response unsupported by ' . __METHOD__
4349 * Check if the given clear-text password matches the temporary password
4350 * sent by e-mail for password reset operations.
4352 * @deprecated since 1.27, use AuthManager instead
4353 * @param string $plaintext
4354 * @return bool True if matches, false otherwise
4356 public function checkTemporaryPassword( $plaintext ) {
4357 global $wgNewPasswordExpiry, $wgDisableAuthManager;
4359 if ( $wgDisableAuthManager ) {
4362 $passwordFactory = new PasswordFactory();
4363 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4364 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
4365 ?
wfGetDB( DB_MASTER
)
4366 : wfGetDB( DB_SLAVE
);
4368 $row = $db->selectRow(
4370 [ 'user_newpassword', 'user_newpass_time' ],
4371 [ 'user_id' => $this->getId() ],
4375 $newPassword = $passwordFactory->newFromCiphertext( $row->user_newpassword
);
4376 } catch ( PasswordError
$e ) {
4377 wfDebug( 'Invalid password hash found in database.' );
4378 $newPassword = PasswordFactory
::newInvalidPassword();
4381 if ( $newPassword->equals( $plaintext ) ) {
4382 if ( is_null( $row->user_newpass_time
) ) {
4385 $expiry = wfTimestamp( TS_UNIX
, $row->user_newpass_time
) +
$wgNewPasswordExpiry;
4386 return ( time() < $expiry );
4391 // Can't check the temporary password individually.
4392 return $this->checkPassword( $plaintext );
4397 * Initialize (if necessary) and return a session token value
4398 * which can be used in edit forms to show that the user's
4399 * login credentials aren't being hijacked with a foreign form
4403 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4404 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4405 * @return MediaWiki\Session\Token The new edit token
4407 public function getEditTokenObject( $salt = '', $request = null ) {
4408 if ( $this->isAnon() ) {
4409 return new LoggedOutEditToken();
4413 $request = $this->getRequest();
4415 return $request->getSession()->getToken( $salt );
4419 * Initialize (if necessary) and return a session token value
4420 * which can be used in edit forms to show that the user's
4421 * login credentials aren't being hijacked with a foreign form
4425 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4426 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4427 * @return string The new edit token
4429 public function getEditToken( $salt = '', $request = null ) {
4430 return $this->getEditTokenObject( $salt, $request )->toString();
4434 * Get the embedded timestamp from a token.
4435 * @deprecated since 1.27, use \MediaWiki\Session\Token::getTimestamp instead.
4436 * @param string $val Input token
4439 public static function getEditTokenTimestamp( $val ) {
4440 wfDeprecated( __METHOD__
, '1.27' );
4441 return MediaWiki\Session\Token
::getTimestamp( $val );
4445 * Check given value against the token value stored in the session.
4446 * A match should confirm that the form was submitted from the
4447 * user's own login session, not a form submission from a third-party
4450 * @param string $val Input value to compare
4451 * @param string $salt Optional function-specific data for hashing
4452 * @param WebRequest|null $request Object to use or null to use $wgRequest
4453 * @param int $maxage Fail tokens older than this, in seconds
4454 * @return bool Whether the token matches
4456 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4457 return $this->getEditTokenObject( $salt, $request )->match( $val, $maxage );
4461 * Check given value against the token value stored in the session,
4462 * ignoring the suffix.
4464 * @param string $val Input value to compare
4465 * @param string $salt Optional function-specific data for hashing
4466 * @param WebRequest|null $request Object to use or null to use $wgRequest
4467 * @param int $maxage Fail tokens older than this, in seconds
4468 * @return bool Whether the token matches
4470 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4471 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . Token
::SUFFIX
;
4472 return $this->matchEditToken( $val, $salt, $request, $maxage );
4476 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4477 * mail to the user's given address.
4479 * @param string $type Message to send, either "created", "changed" or "set"
4482 public function sendConfirmationMail( $type = 'created' ) {
4484 $expiration = null; // gets passed-by-ref and defined in next line.
4485 $token = $this->confirmationToken( $expiration );
4486 $url = $this->confirmationTokenUrl( $token );
4487 $invalidateURL = $this->invalidationTokenUrl( $token );
4488 $this->saveSettings();
4490 if ( $type == 'created' ||
$type === false ) {
4491 $message = 'confirmemail_body';
4492 } elseif ( $type === true ) {
4493 $message = 'confirmemail_body_changed';
4495 // Messages: confirmemail_body_changed, confirmemail_body_set
4496 $message = 'confirmemail_body_' . $type;
4499 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4500 wfMessage( $message,
4501 $this->getRequest()->getIP(),
4504 $wgLang->userTimeAndDate( $expiration, $this ),
4506 $wgLang->userDate( $expiration, $this ),
4507 $wgLang->userTime( $expiration, $this ) )->text() );
4511 * Send an e-mail to this user's account. Does not check for
4512 * confirmed status or validity.
4514 * @param string $subject Message subject
4515 * @param string $body Message body
4516 * @param User|null $from Optional sending user; if unspecified, default
4517 * $wgPasswordSender will be used.
4518 * @param string $replyto Reply-To address
4521 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4522 global $wgPasswordSender;
4524 if ( $from instanceof User
) {
4525 $sender = MailAddress
::newFromUser( $from );
4527 $sender = new MailAddress( $wgPasswordSender,
4528 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4530 $to = MailAddress
::newFromUser( $this );
4532 return UserMailer
::send( $to, $sender, $subject, $body, [
4533 'replyTo' => $replyto,
4538 * Generate, store, and return a new e-mail confirmation code.
4539 * A hash (unsalted, since it's used as a key) is stored.
4541 * @note Call saveSettings() after calling this function to commit
4542 * this change to the database.
4544 * @param string &$expiration Accepts the expiration time
4545 * @return string New token
4547 protected function confirmationToken( &$expiration ) {
4548 global $wgUserEmailConfirmationTokenExpiry;
4550 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4551 $expiration = wfTimestamp( TS_MW
, $expires );
4553 $token = MWCryptRand
::generateHex( 32 );
4554 $hash = md5( $token );
4555 $this->mEmailToken
= $hash;
4556 $this->mEmailTokenExpires
= $expiration;
4561 * Return a URL the user can use to confirm their email address.
4562 * @param string $token Accepts the email confirmation token
4563 * @return string New token URL
4565 protected function confirmationTokenUrl( $token ) {
4566 return $this->getTokenUrl( 'ConfirmEmail', $token );
4570 * Return a URL the user can use to invalidate their email address.
4571 * @param string $token Accepts the email confirmation token
4572 * @return string New token URL
4574 protected function invalidationTokenUrl( $token ) {
4575 return $this->getTokenUrl( 'InvalidateEmail', $token );
4579 * Internal function to format the e-mail validation/invalidation URLs.
4580 * This uses a quickie hack to use the
4581 * hardcoded English names of the Special: pages, for ASCII safety.
4583 * @note Since these URLs get dropped directly into emails, using the
4584 * short English names avoids insanely long URL-encoded links, which
4585 * also sometimes can get corrupted in some browsers/mailers
4586 * (bug 6957 with Gmail and Internet Explorer).
4588 * @param string $page Special page
4589 * @param string $token Token
4590 * @return string Formatted URL
4592 protected function getTokenUrl( $page, $token ) {
4593 // Hack to bypass localization of 'Special:'
4594 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4595 return $title->getCanonicalURL();
4599 * Mark the e-mail address confirmed.
4601 * @note Call saveSettings() after calling this function to commit the change.
4605 public function confirmEmail() {
4606 // Check if it's already confirmed, so we don't touch the database
4607 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4608 if ( !$this->isEmailConfirmed() ) {
4609 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4610 Hooks
::run( 'ConfirmEmailComplete', [ $this ] );
4616 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4617 * address if it was already confirmed.
4619 * @note Call saveSettings() after calling this function to commit the change.
4620 * @return bool Returns true
4622 public function invalidateEmail() {
4624 $this->mEmailToken
= null;
4625 $this->mEmailTokenExpires
= null;
4626 $this->setEmailAuthenticationTimestamp( null );
4628 Hooks
::run( 'InvalidateEmailComplete', [ $this ] );
4633 * Set the e-mail authentication timestamp.
4634 * @param string $timestamp TS_MW timestamp
4636 public function setEmailAuthenticationTimestamp( $timestamp ) {
4638 $this->mEmailAuthenticated
= $timestamp;
4639 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
4643 * Is this user allowed to send e-mails within limits of current
4644 * site configuration?
4647 public function canSendEmail() {
4648 global $wgEnableEmail, $wgEnableUserEmail;
4649 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4652 $canSend = $this->isEmailConfirmed();
4653 Hooks
::run( 'UserCanSendEmail', [ &$this, &$canSend ] );
4658 * Is this user allowed to receive e-mails within limits of current
4659 * site configuration?
4662 public function canReceiveEmail() {
4663 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4667 * Is this user's e-mail address valid-looking and confirmed within
4668 * limits of the current site configuration?
4670 * @note If $wgEmailAuthentication is on, this may require the user to have
4671 * confirmed their address by returning a code or using a password
4672 * sent to the address from the wiki.
4676 public function isEmailConfirmed() {
4677 global $wgEmailAuthentication;
4680 if ( Hooks
::run( 'EmailConfirmed', [ &$this, &$confirmed ] ) ) {
4681 if ( $this->isAnon() ) {
4684 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4687 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4697 * Check whether there is an outstanding request for e-mail confirmation.
4700 public function isEmailConfirmationPending() {
4701 global $wgEmailAuthentication;
4702 return $wgEmailAuthentication &&
4703 !$this->isEmailConfirmed() &&
4704 $this->mEmailToken
&&
4705 $this->mEmailTokenExpires
> wfTimestamp();
4709 * Get the timestamp of account creation.
4711 * @return string|bool|null Timestamp of account creation, false for
4712 * non-existent/anonymous user accounts, or null if existing account
4713 * but information is not in database.
4715 public function getRegistration() {
4716 if ( $this->isAnon() ) {
4720 return $this->mRegistration
;
4724 * Get the timestamp of the first edit
4726 * @return string|bool Timestamp of first edit, or false for
4727 * non-existent/anonymous user accounts.
4729 public function getFirstEditTimestamp() {
4730 if ( $this->getId() == 0 ) {
4731 return false; // anons
4733 $dbr = wfGetDB( DB_SLAVE
);
4734 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4735 [ 'rev_user' => $this->getId() ],
4737 [ 'ORDER BY' => 'rev_timestamp ASC' ]
4740 return false; // no edits
4742 return wfTimestamp( TS_MW
, $time );
4746 * Get the permissions associated with a given list of groups
4748 * @param array $groups Array of Strings List of internal group names
4749 * @return array Array of Strings List of permission key names for given groups combined
4751 public static function getGroupPermissions( $groups ) {
4752 global $wgGroupPermissions, $wgRevokePermissions;
4754 // grant every granted permission first
4755 foreach ( $groups as $group ) {
4756 if ( isset( $wgGroupPermissions[$group] ) ) {
4757 $rights = array_merge( $rights,
4758 // array_filter removes empty items
4759 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4762 // now revoke the revoked permissions
4763 foreach ( $groups as $group ) {
4764 if ( isset( $wgRevokePermissions[$group] ) ) {
4765 $rights = array_diff( $rights,
4766 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4769 return array_unique( $rights );
4773 * Get all the groups who have a given permission
4775 * @param string $role Role to check
4776 * @return array Array of Strings List of internal group names with the given permission
4778 public static function getGroupsWithPermission( $role ) {
4779 global $wgGroupPermissions;
4780 $allowedGroups = [];
4781 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4782 if ( self
::groupHasPermission( $group, $role ) ) {
4783 $allowedGroups[] = $group;
4786 return $allowedGroups;
4790 * Check, if the given group has the given permission
4792 * If you're wanting to check whether all users have a permission, use
4793 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4797 * @param string $group Group to check
4798 * @param string $role Role to check
4801 public static function groupHasPermission( $group, $role ) {
4802 global $wgGroupPermissions, $wgRevokePermissions;
4803 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4804 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4808 * Check if all users may be assumed to have the given permission
4810 * We generally assume so if the right is granted to '*' and isn't revoked
4811 * on any group. It doesn't attempt to take grants or other extension
4812 * limitations on rights into account in the general case, though, as that
4813 * would require it to always return false and defeat the purpose.
4814 * Specifically, session-based rights restrictions (such as OAuth or bot
4815 * passwords) are applied based on the current session.
4818 * @param string $right Right to check
4821 public static function isEveryoneAllowed( $right ) {
4822 global $wgGroupPermissions, $wgRevokePermissions;
4825 // Use the cached results, except in unit tests which rely on
4826 // being able change the permission mid-request
4827 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4828 return $cache[$right];
4831 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4832 $cache[$right] = false;
4836 // If it's revoked anywhere, then everyone doesn't have it
4837 foreach ( $wgRevokePermissions as $rights ) {
4838 if ( isset( $rights[$right] ) && $rights[$right] ) {
4839 $cache[$right] = false;
4844 // Remove any rights that aren't allowed to the global-session user,
4845 // unless there are no sessions for this endpoint.
4846 if ( !defined( 'MW_NO_SESSION' ) ) {
4847 $allowedRights = SessionManager
::getGlobalSession()->getAllowedUserRights();
4848 if ( $allowedRights !== null && !in_array( $right, $allowedRights, true ) ) {
4849 $cache[$right] = false;
4854 // Allow extensions to say false
4855 if ( !Hooks
::run( 'UserIsEveryoneAllowed', [ $right ] ) ) {
4856 $cache[$right] = false;
4860 $cache[$right] = true;
4865 * Get the localized descriptive name for a group, if it exists
4867 * @param string $group Internal group name
4868 * @return string Localized descriptive group name
4870 public static function getGroupName( $group ) {
4871 $msg = wfMessage( "group-$group" );
4872 return $msg->isBlank() ?
$group : $msg->text();
4876 * Get the localized descriptive name for a member of a group, if it exists
4878 * @param string $group Internal group name
4879 * @param string $username Username for gender (since 1.19)
4880 * @return string Localized name for group member
4882 public static function getGroupMember( $group, $username = '#' ) {
4883 $msg = wfMessage( "group-$group-member", $username );
4884 return $msg->isBlank() ?
$group : $msg->text();
4888 * Return the set of defined explicit groups.
4889 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4890 * are not included, as they are defined automatically, not in the database.
4891 * @return array Array of internal group names
4893 public static function getAllGroups() {
4894 global $wgGroupPermissions, $wgRevokePermissions;
4896 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4897 self
::getImplicitGroups()
4902 * Get a list of all available permissions.
4903 * @return string[] Array of permission names
4905 public static function getAllRights() {
4906 if ( self
::$mAllRights === false ) {
4907 global $wgAvailableRights;
4908 if ( count( $wgAvailableRights ) ) {
4909 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
4911 self
::$mAllRights = self
::$mCoreRights;
4913 Hooks
::run( 'UserGetAllRights', [ &self
::$mAllRights ] );
4915 return self
::$mAllRights;
4919 * Get a list of implicit groups
4920 * @return array Array of Strings Array of internal group names
4922 public static function getImplicitGroups() {
4923 global $wgImplicitGroups;
4925 $groups = $wgImplicitGroups;
4926 # Deprecated, use $wgImplicitGroups instead
4927 Hooks
::run( 'UserGetImplicitGroups', [ &$groups ], '1.25' );
4933 * Get the title of a page describing a particular group
4935 * @param string $group Internal group name
4936 * @return Title|bool Title of the page if it exists, false otherwise
4938 public static function getGroupPage( $group ) {
4939 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4940 if ( $msg->exists() ) {
4941 $title = Title
::newFromText( $msg->text() );
4942 if ( is_object( $title ) ) {
4950 * Create a link to the group in HTML, if available;
4951 * else return the group name.
4953 * @param string $group Internal name of the group
4954 * @param string $text The text of the link
4955 * @return string HTML link to the group
4957 public static function makeGroupLinkHTML( $group, $text = '' ) {
4958 if ( $text == '' ) {
4959 $text = self
::getGroupName( $group );
4961 $title = self
::getGroupPage( $group );
4963 return Linker
::link( $title, htmlspecialchars( $text ) );
4965 return htmlspecialchars( $text );
4970 * Create a link to the group in Wikitext, if available;
4971 * else return the group name.
4973 * @param string $group Internal name of the group
4974 * @param string $text The text of the link
4975 * @return string Wikilink to the group
4977 public static function makeGroupLinkWiki( $group, $text = '' ) {
4978 if ( $text == '' ) {
4979 $text = self
::getGroupName( $group );
4981 $title = self
::getGroupPage( $group );
4983 $page = $title->getFullText();
4984 return "[[$page|$text]]";
4991 * Returns an array of the groups that a particular group can add/remove.
4993 * @param string $group The group to check for whether it can add/remove
4994 * @return array Array( 'add' => array( addablegroups ),
4995 * 'remove' => array( removablegroups ),
4996 * 'add-self' => array( addablegroups to self),
4997 * 'remove-self' => array( removable groups from self) )
4999 public static function changeableByGroup( $group ) {
5000 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
5009 if ( empty( $wgAddGroups[$group] ) ) {
5010 // Don't add anything to $groups
5011 } elseif ( $wgAddGroups[$group] === true ) {
5012 // You get everything
5013 $groups['add'] = self
::getAllGroups();
5014 } elseif ( is_array( $wgAddGroups[$group] ) ) {
5015 $groups['add'] = $wgAddGroups[$group];
5018 // Same thing for remove
5019 if ( empty( $wgRemoveGroups[$group] ) ) {
5021 } elseif ( $wgRemoveGroups[$group] === true ) {
5022 $groups['remove'] = self
::getAllGroups();
5023 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
5024 $groups['remove'] = $wgRemoveGroups[$group];
5027 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
5028 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
5029 foreach ( $wgGroupsAddToSelf as $key => $value ) {
5030 if ( is_int( $key ) ) {
5031 $wgGroupsAddToSelf['user'][] = $value;
5036 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
5037 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
5038 if ( is_int( $key ) ) {
5039 $wgGroupsRemoveFromSelf['user'][] = $value;
5044 // Now figure out what groups the user can add to him/herself
5045 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
5047 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
5048 // No idea WHY this would be used, but it's there
5049 $groups['add-self'] = User
::getAllGroups();
5050 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
5051 $groups['add-self'] = $wgGroupsAddToSelf[$group];
5054 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
5056 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
5057 $groups['remove-self'] = User
::getAllGroups();
5058 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
5059 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
5066 * Returns an array of groups that this user can add and remove
5067 * @return array Array( 'add' => array( addablegroups ),
5068 * 'remove' => array( removablegroups ),
5069 * 'add-self' => array( addablegroups to self),
5070 * 'remove-self' => array( removable groups from self) )
5072 public function changeableGroups() {
5073 if ( $this->isAllowed( 'userrights' ) ) {
5074 // This group gives the right to modify everything (reverse-
5075 // compatibility with old "userrights lets you change
5077 // Using array_merge to make the groups reindexed
5078 $all = array_merge( User
::getAllGroups() );
5087 // Okay, it's not so simple, we will have to go through the arrays
5094 $addergroups = $this->getEffectiveGroups();
5096 foreach ( $addergroups as $addergroup ) {
5097 $groups = array_merge_recursive(
5098 $groups, $this->changeableByGroup( $addergroup )
5100 $groups['add'] = array_unique( $groups['add'] );
5101 $groups['remove'] = array_unique( $groups['remove'] );
5102 $groups['add-self'] = array_unique( $groups['add-self'] );
5103 $groups['remove-self'] = array_unique( $groups['remove-self'] );
5109 * Deferred version of incEditCountImmediate()
5111 public function incEditCount() {
5112 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle( function() {
5113 $this->incEditCountImmediate();
5118 * Increment the user's edit-count field.
5119 * Will have no effect for anonymous users.
5122 public function incEditCountImmediate() {
5123 if ( $this->isAnon() ) {
5127 $dbw = wfGetDB( DB_MASTER
);
5128 // No rows will be "affected" if user_editcount is NULL
5131 [ 'user_editcount=user_editcount+1' ],
5132 [ 'user_id' => $this->getId(), 'user_editcount IS NOT NULL' ],
5135 // Lazy initialization check...
5136 if ( $dbw->affectedRows() == 0 ) {
5137 // Now here's a goddamn hack...
5138 $dbr = wfGetDB( DB_SLAVE
);
5139 if ( $dbr !== $dbw ) {
5140 // If we actually have a slave server, the count is
5141 // at least one behind because the current transaction
5142 // has not been committed and replicated.
5143 $this->initEditCount( 1 );
5145 // But if DB_SLAVE is selecting the master, then the
5146 // count we just read includes the revision that was
5147 // just added in the working transaction.
5148 $this->initEditCount();
5151 // Edit count in user cache too
5152 $this->invalidateCache();
5156 * Initialize user_editcount from data out of the revision table
5158 * @param int $add Edits to add to the count from the revision table
5159 * @return int Number of edits
5161 protected function initEditCount( $add = 0 ) {
5162 // Pull from a slave to be less cruel to servers
5163 // Accuracy isn't the point anyway here
5164 $dbr = wfGetDB( DB_SLAVE
);
5165 $count = (int)$dbr->selectField(
5168 [ 'rev_user' => $this->getId() ],
5171 $count = $count +
$add;
5173 $dbw = wfGetDB( DB_MASTER
);
5176 [ 'user_editcount' => $count ],
5177 [ 'user_id' => $this->getId() ],
5185 * Get the description of a given right
5187 * @param string $right Right to query
5188 * @return string Localized description of the right
5190 public static function getRightDescription( $right ) {
5191 $key = "right-$right";
5192 $msg = wfMessage( $key );
5193 return $msg->isBlank() ?
$right : $msg->text();
5197 * Make a new-style password hash
5199 * @param string $password Plain-text password
5200 * @param bool|string $salt Optional salt, may be random or the user ID.
5201 * If unspecified or false, will generate one automatically
5202 * @return string Password hash
5203 * @deprecated since 1.24, use Password class
5205 public static function crypt( $password, $salt = false ) {
5206 wfDeprecated( __METHOD__
, '1.24' );
5207 $passwordFactory = new PasswordFactory();
5208 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
5209 $hash = $passwordFactory->newFromPlaintext( $password );
5210 return $hash->toString();
5214 * Compare a password hash with a plain-text password. Requires the user
5215 * ID if there's a chance that the hash is an old-style hash.
5217 * @param string $hash Password hash
5218 * @param string $password Plain-text password to compare
5219 * @param string|bool $userId User ID for old-style password salt
5222 * @deprecated since 1.24, use Password class
5224 public static function comparePasswords( $hash, $password, $userId = false ) {
5225 wfDeprecated( __METHOD__
, '1.24' );
5227 // Check for *really* old password hashes that don't even have a type
5228 // The old hash format was just an md5 hex hash, with no type information
5229 if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) {
5230 global $wgPasswordSalt;
5231 if ( $wgPasswordSalt ) {
5232 $password = ":B:{$userId}:{$hash}";
5234 $password = ":A:{$hash}";
5238 $passwordFactory = new PasswordFactory();
5239 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
5240 $hash = $passwordFactory->newFromCiphertext( $hash );
5241 return $hash->equals( $password );
5245 * Add a newuser log entry for this user.
5246 * Before 1.19 the return value was always true.
5248 * @deprecated since 1.27, AuthManager handles logging
5249 * @param string|bool $action Account creation type.
5250 * - String, one of the following values:
5251 * - 'create' for an anonymous user creating an account for himself.
5252 * This will force the action's performer to be the created user itself,
5253 * no matter the value of $wgUser
5254 * - 'create2' for a logged in user creating an account for someone else
5255 * - 'byemail' when the created user will receive its password by e-mail
5256 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
5257 * - Boolean means whether the account was created by e-mail (deprecated):
5258 * - true will be converted to 'byemail'
5259 * - false will be converted to 'create' if this object is the same as
5260 * $wgUser and to 'create2' otherwise
5261 * @param string $reason User supplied reason
5262 * @return int|bool True if not $wgNewUserLog or not $wgDisableAuthManager;
5263 * otherwise ID of log item or 0 on failure
5265 public function addNewUserLogEntry( $action = false, $reason = '' ) {
5266 global $wgUser, $wgNewUserLog, $wgDisableAuthManager;
5267 if ( !$wgDisableAuthManager ||
empty( $wgNewUserLog ) ) {
5268 return true; // disabled
5271 if ( $action === true ) {
5272 $action = 'byemail';
5273 } elseif ( $action === false ) {
5274 if ( $this->equals( $wgUser ) ) {
5277 $action = 'create2';
5281 if ( $action === 'create' ||
$action === 'autocreate' ) {
5284 $performer = $wgUser;
5287 $logEntry = new ManualLogEntry( 'newusers', $action );
5288 $logEntry->setPerformer( $performer );
5289 $logEntry->setTarget( $this->getUserPage() );
5290 $logEntry->setComment( $reason );
5291 $logEntry->setParameters( [
5292 '4::userid' => $this->getId(),
5294 $logid = $logEntry->insert();
5296 if ( $action !== 'autocreate' ) {
5297 $logEntry->publish( $logid );
5304 * Add an autocreate newuser log entry for this user
5305 * Used by things like CentralAuth and perhaps other authplugins.
5306 * Consider calling addNewUserLogEntry() directly instead.
5308 * @deprecated since 1.27, AuthManager handles logging
5311 public function addNewUserLogEntryAutoCreate() {
5312 $this->addNewUserLogEntry( 'autocreate' );
5318 * Load the user options either from cache, the database or an array
5320 * @param array $data Rows for the current user out of the user_properties table
5322 protected function loadOptions( $data = null ) {
5327 if ( $this->mOptionsLoaded
) {
5331 $this->mOptions
= self
::getDefaultOptions();
5333 if ( !$this->getId() ) {
5334 // For unlogged-in users, load language/variant options from request.
5335 // There's no need to do it for logged-in users: they can set preferences,
5336 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5337 // so don't override user's choice (especially when the user chooses site default).
5338 $variant = $wgContLang->getDefaultVariant();
5339 $this->mOptions
['variant'] = $variant;
5340 $this->mOptions
['language'] = $variant;
5341 $this->mOptionsLoaded
= true;
5345 // Maybe load from the object
5346 if ( !is_null( $this->mOptionOverrides
) ) {
5347 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5348 foreach ( $this->mOptionOverrides
as $key => $value ) {
5349 $this->mOptions
[$key] = $value;
5352 if ( !is_array( $data ) ) {
5353 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5354 // Load from database
5355 $dbr = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
5356 ?
wfGetDB( DB_MASTER
)
5357 : wfGetDB( DB_SLAVE
);
5359 $res = $dbr->select(
5361 [ 'up_property', 'up_value' ],
5362 [ 'up_user' => $this->getId() ],
5366 $this->mOptionOverrides
= [];
5368 foreach ( $res as $row ) {
5369 $data[$row->up_property
] = $row->up_value
;
5372 foreach ( $data as $property => $value ) {
5373 $this->mOptionOverrides
[$property] = $value;
5374 $this->mOptions
[$property] = $value;
5378 $this->mOptionsLoaded
= true;
5380 Hooks
::run( 'UserLoadOptions', [ $this, &$this->mOptions
] );
5384 * Saves the non-default options for this user, as previously set e.g. via
5385 * setOption(), in the database's "user_properties" (preferences) table.
5386 * Usually used via saveSettings().
5388 protected function saveOptions() {
5389 $this->loadOptions();
5391 // Not using getOptions(), to keep hidden preferences in database
5392 $saveOptions = $this->mOptions
;
5394 // Allow hooks to abort, for instance to save to a global profile.
5395 // Reset options to default state before saving.
5396 if ( !Hooks
::run( 'UserSaveOptions', [ $this, &$saveOptions ] ) ) {
5400 $userId = $this->getId();
5402 $insert_rows = []; // all the new preference rows
5403 foreach ( $saveOptions as $key => $value ) {
5404 // Don't bother storing default values
5405 $defaultOption = self
::getDefaultOption( $key );
5406 if ( ( $defaultOption === null && $value !== false && $value !== null )
5407 ||
$value != $defaultOption
5410 'up_user' => $userId,
5411 'up_property' => $key,
5412 'up_value' => $value,
5417 $dbw = wfGetDB( DB_MASTER
);
5419 $res = $dbw->select( 'user_properties',
5420 [ 'up_property', 'up_value' ], [ 'up_user' => $userId ], __METHOD__
);
5422 // Find prior rows that need to be removed or updated. These rows will
5423 // all be deleted (the later so that INSERT IGNORE applies the new values).
5425 foreach ( $res as $row ) {
5426 if ( !isset( $saveOptions[$row->up_property
] )
5427 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
5429 $keysDelete[] = $row->up_property
;
5433 if ( count( $keysDelete ) ) {
5434 // Do the DELETE by PRIMARY KEY for prior rows.
5435 // In the past a very large portion of calls to this function are for setting
5436 // 'rememberpassword' for new accounts (a preference that has since been removed).
5437 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5438 // caused gap locks on [max user ID,+infinity) which caused high contention since
5439 // updates would pile up on each other as they are for higher (newer) user IDs.
5440 // It might not be necessary these days, but it shouldn't hurt either.
5441 $dbw->delete( 'user_properties',
5442 [ 'up_user' => $userId, 'up_property' => $keysDelete ], __METHOD__
);
5444 // Insert the new preference rows
5445 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, [ 'IGNORE' ] );
5449 * Lazily instantiate and return a factory object for making passwords
5451 * @deprecated since 1.27, create a PasswordFactory directly instead
5452 * @return PasswordFactory
5454 public static function getPasswordFactory() {
5455 wfDeprecated( __METHOD__
, '1.27' );
5456 $ret = new PasswordFactory();
5457 $ret->init( RequestContext
::getMain()->getConfig() );
5462 * Provide an array of HTML5 attributes to put on an input element
5463 * intended for the user to enter a new password. This may include
5464 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
5466 * Do *not* use this when asking the user to enter his current password!
5467 * Regardless of configuration, users may have invalid passwords for whatever
5468 * reason (e.g., they were set before requirements were tightened up).
5469 * Only use it when asking for a new password, like on account creation or
5472 * Obviously, you still need to do server-side checking.
5474 * NOTE: A combination of bugs in various browsers means that this function
5475 * actually just returns array() unconditionally at the moment. May as
5476 * well keep it around for when the browser bugs get fixed, though.
5478 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
5480 * @deprecated since 1.27
5481 * @return array Array of HTML attributes suitable for feeding to
5482 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
5483 * That will get confused by the boolean attribute syntax used.)
5485 public static function passwordChangeInputAttribs() {
5486 global $wgMinimalPasswordLength;
5488 if ( $wgMinimalPasswordLength == 0 ) {
5492 # Note that the pattern requirement will always be satisfied if the
5493 # input is empty, so we need required in all cases.
5495 # @todo FIXME: Bug 23769: This needs to not claim the password is required
5496 # if e-mail confirmation is being used. Since HTML5 input validation
5497 # is b0rked anyway in some browsers, just return nothing. When it's
5498 # re-enabled, fix this code to not output required for e-mail
5500 # $ret = array( 'required' );
5503 # We can't actually do this right now, because Opera 9.6 will print out
5504 # the entered password visibly in its error message! When other
5505 # browsers add support for this attribute, or Opera fixes its support,
5506 # we can add support with a version check to avoid doing this on Opera
5507 # versions where it will be a problem. Reported to Opera as
5508 # DSK-262266, but they don't have a public bug tracker for us to follow.
5510 if ( $wgMinimalPasswordLength > 1 ) {
5511 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
5512 $ret['title'] = wfMessage( 'passwordtooshort' )
5513 ->numParams( $wgMinimalPasswordLength )->text();
5521 * Return the list of user fields that should be selected to create
5522 * a new user object.
5525 public static function selectFields() {
5533 'user_email_authenticated',
5535 'user_email_token_expires',
5536 'user_registration',
5542 * Factory function for fatal permission-denied errors
5545 * @param string $permission User right required
5548 static function newFatalPermissionDeniedStatus( $permission ) {
5551 $groups = array_map(
5552 [ 'User', 'makeGroupLinkWiki' ],
5553 User
::getGroupsWithPermission( $permission )
5557 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5559 return Status
::newFatal( 'badaccess-group0' );
5564 * Get a new instance of this user that was loaded from the master via a locking read
5566 * Use this instead of the main context User when updating that user. This avoids races
5567 * where that user was loaded from a slave or even the master but without proper locks.
5569 * @return User|null Returns null if the user was not found in the DB
5572 public function getInstanceForUpdate() {
5573 if ( !$this->getId() ) {
5574 return null; // anon
5577 $user = self
::newFromId( $this->getId() );
5578 if ( !$user->loadFromId( self
::READ_EXCLUSIVE
) ) {
5586 * Checks if two user objects point to the same user.
5592 public function equals( User
$user ) {
5593 return $this->getName() === $user->getName();