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 * @param string $name Username
678 * @param array $options Options are:
679 * - validate: As for User::getCanonicalName(), default 'valid'
680 * - create: Whether to create the user if it doesn't already exist, default true
681 * - steal: Whether to reset the account's password and email if it
682 * already exists, default false
686 public static function newSystemUser( $name, $options = [] ) {
687 global $wgDisableAuthManager;
690 'validate' => 'valid',
695 $name = self
::getCanonicalName( $name, $options['validate'] );
696 if ( $name === false ) {
700 $fields = self
::selectFields();
701 if ( $wgDisableAuthManager ) {
702 $fields = array_merge( $fields, [ 'user_password', 'user_newpassword' ] );
705 $dbw = wfGetDB( DB_MASTER
);
706 $row = $dbw->selectRow(
709 [ 'user_name' => $name ],
713 // No user. Create it?
714 return $options['create'] ? self
::createNew( $name ) : null;
716 $user = self
::newFromRow( $row );
718 // A user is considered to exist as a non-system user if it has a
719 // password set, or a temporary password set, or an email set, or a
720 // non-invalid token.
721 if ( !$user->mEmail
&& $user->mToken
=== self
::INVALID_TOKEN
) {
722 if ( $wgDisableAuthManager ) {
723 $passwordFactory = new PasswordFactory();
724 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
726 $password = $passwordFactory->newFromCiphertext( $row->user_password
);
727 } catch ( PasswordError
$e ) {
728 wfDebug( 'Invalid password hash found in database.' );
729 $password = PasswordFactory
::newInvalidPassword();
732 $newpassword = $passwordFactory->newFromCiphertext( $row->user_newpassword
);
733 } catch ( PasswordError
$e ) {
734 wfDebug( 'Invalid password hash found in database.' );
735 $newpassword = PasswordFactory
::newInvalidPassword();
737 $canAuthenticate = !$password instanceof InvalidPassword ||
738 !$newpassword instanceof InvalidPassword
;
740 $canAuthenticate = AuthManager
::singleton()->userCanAuthenticate( $name );
743 if ( $user->mEmail ||
$user->mToken
!== self
::INVALID_TOKEN ||
$canAuthenticate ) {
744 // User exists. Steal it?
745 if ( !$options['steal'] ) {
749 if ( $wgDisableAuthManager ) {
750 $nopass = PasswordFactory
::newInvalidPassword()->toString();
754 'user_password' => $nopass,
755 'user_newpassword' => $nopass,
756 'user_newpass_time' => null,
758 [ 'user_id' => $user->getId() ],
762 AuthManager
::singleton()->revokeAccessForUser( $name );
765 $user->invalidateEmail();
766 $user->mToken
= self
::INVALID_TOKEN
;
767 $user->saveSettings();
768 SessionManager
::singleton()->preventSessionsForUser( $user->getName() );
777 * Get the username corresponding to a given user ID
778 * @param int $id User ID
779 * @return string|bool The corresponding username
781 public static function whoIs( $id ) {
782 return UserCache
::singleton()->getProp( $id, 'name' );
786 * Get the real name of a user given their user ID
788 * @param int $id User ID
789 * @return string|bool The corresponding user's real name
791 public static function whoIsReal( $id ) {
792 return UserCache
::singleton()->getProp( $id, 'real_name' );
796 * Get database id given a user name
797 * @param string $name Username
798 * @param integer $flags User::READ_* constant bitfield
799 * @return int|null The corresponding user's ID, or null if user is nonexistent
801 public static function idFromName( $name, $flags = self
::READ_NORMAL
) {
802 $nt = Title
::makeTitleSafe( NS_USER
, $name );
803 if ( is_null( $nt ) ) {
808 if ( !( $flags & self
::READ_LATEST
) && isset( self
::$idCacheByName[$name] ) ) {
809 return self
::$idCacheByName[$name];
812 $db = ( $flags & self
::READ_LATEST
)
813 ?
wfGetDB( DB_MASTER
)
814 : wfGetDB( DB_SLAVE
);
819 [ 'user_name' => $nt->getText() ],
823 if ( $s === false ) {
826 $result = $s->user_id
;
829 self
::$idCacheByName[$name] = $result;
831 if ( count( self
::$idCacheByName ) > 1000 ) {
832 self
::$idCacheByName = [];
839 * Reset the cache used in idFromName(). For use in tests.
841 public static function resetIdByNameCache() {
842 self
::$idCacheByName = [];
846 * Does the string match an anonymous IPv4 address?
848 * This function exists for username validation, in order to reject
849 * usernames which are similar in form to IP addresses. Strings such
850 * as 300.300.300.300 will return true because it looks like an IP
851 * address, despite not being strictly valid.
853 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
854 * address because the usemod software would "cloak" anonymous IP
855 * addresses like this, if we allowed accounts like this to be created
856 * new users could get the old edits of these anonymous users.
858 * @param string $name Name to match
861 public static function isIP( $name ) {
862 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
863 || IP
::isIPv6( $name );
867 * Is the input a valid username?
869 * Checks if the input is a valid username, we don't want an empty string,
870 * an IP address, anything that contains slashes (would mess up subpages),
871 * is longer than the maximum allowed username size or doesn't begin with
874 * @param string $name Name to match
877 public static function isValidUserName( $name ) {
878 global $wgContLang, $wgMaxNameChars;
881 || User
::isIP( $name )
882 ||
strpos( $name, '/' ) !== false
883 ||
strlen( $name ) > $wgMaxNameChars
884 ||
$name != $wgContLang->ucfirst( $name )
889 // Ensure that the name can't be misresolved as a different title,
890 // such as with extra namespace keys at the start.
891 $parsed = Title
::newFromText( $name );
892 if ( is_null( $parsed )
893 ||
$parsed->getNamespace()
894 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
898 // Check an additional blacklist of troublemaker characters.
899 // Should these be merged into the title char list?
900 $unicodeBlacklist = '/[' .
901 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
902 '\x{00a0}' . # non-breaking space
903 '\x{2000}-\x{200f}' . # various whitespace
904 '\x{2028}-\x{202f}' . # breaks and control chars
905 '\x{3000}' . # ideographic space
906 '\x{e000}-\x{f8ff}' . # private use
908 if ( preg_match( $unicodeBlacklist, $name ) ) {
916 * Usernames which fail to pass this function will be blocked
917 * from user login and new account registrations, but may be used
918 * internally by batch processes.
920 * If an account already exists in this form, login will be blocked
921 * by a failure to pass this function.
923 * @param string $name Name to match
926 public static function isUsableName( $name ) {
927 global $wgReservedUsernames;
928 // Must be a valid username, obviously ;)
929 if ( !self
::isValidUserName( $name ) ) {
933 static $reservedUsernames = false;
934 if ( !$reservedUsernames ) {
935 $reservedUsernames = $wgReservedUsernames;
936 Hooks
::run( 'UserGetReservedNames', [ &$reservedUsernames ] );
939 // Certain names may be reserved for batch processes.
940 foreach ( $reservedUsernames as $reserved ) {
941 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
942 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
944 if ( $reserved == $name ) {
952 * Usernames which fail to pass this function will be blocked
953 * from new account registrations, but may be used internally
954 * either by batch processes or by user accounts which have
955 * already been created.
957 * Additional blacklisting may be added here rather than in
958 * isValidUserName() to avoid disrupting existing accounts.
960 * @param string $name String to match
963 public static function isCreatableName( $name ) {
964 global $wgInvalidUsernameCharacters;
966 // Ensure that the username isn't longer than 235 bytes, so that
967 // (at least for the builtin skins) user javascript and css files
968 // will work. (bug 23080)
969 if ( strlen( $name ) > 235 ) {
970 wfDebugLog( 'username', __METHOD__
.
971 ": '$name' invalid due to length" );
975 // Preg yells if you try to give it an empty string
976 if ( $wgInvalidUsernameCharacters !== '' ) {
977 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
978 wfDebugLog( 'username', __METHOD__
.
979 ": '$name' invalid due to wgInvalidUsernameCharacters" );
984 return self
::isUsableName( $name );
988 * Is the input a valid password for this user?
990 * @param string $password Desired password
993 public function isValidPassword( $password ) {
994 // simple boolean wrapper for getPasswordValidity
995 return $this->getPasswordValidity( $password ) === true;
999 * Given unvalidated password input, return error message on failure.
1001 * @param string $password Desired password
1002 * @return bool|string|array True on success, string or array of error message on failure
1004 public function getPasswordValidity( $password ) {
1005 $result = $this->checkPasswordValidity( $password );
1006 if ( $result->isGood() ) {
1010 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
1011 $messages[] = $error['message'];
1013 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
1014 $messages[] = $warning['message'];
1016 if ( count( $messages ) === 1 ) {
1017 return $messages[0];
1024 * Check if this is a valid password for this user
1026 * Create a Status object based on the password's validity.
1027 * The Status should be set to fatal if the user should not
1028 * be allowed to log in, and should have any errors that
1029 * would block changing the password.
1031 * If the return value of this is not OK, the password
1032 * should not be checked. If the return value is not Good,
1033 * the password can be checked, but the user should not be
1034 * able to set their password to this.
1036 * @param string $password Desired password
1037 * @param string $purpose one of 'login', 'create', 'reset'
1041 public function checkPasswordValidity( $password, $purpose = 'login' ) {
1042 global $wgPasswordPolicy;
1044 $upp = new UserPasswordPolicy(
1045 $wgPasswordPolicy['policies'],
1046 $wgPasswordPolicy['checks']
1049 $status = Status
::newGood();
1050 $result = false; // init $result to false for the internal checks
1052 if ( !Hooks
::run( 'isValidPassword', [ $password, &$result, $this ] ) ) {
1053 $status->error( $result );
1057 if ( $result === false ) {
1058 $status->merge( $upp->checkUserPassword( $this, $password, $purpose ) );
1060 } elseif ( $result === true ) {
1063 $status->error( $result );
1064 return $status; // the isValidPassword hook set a string $result and returned true
1069 * Given unvalidated user input, return a canonical username, or false if
1070 * the username is invalid.
1071 * @param string $name User input
1072 * @param string|bool $validate Type of validation to use:
1073 * - false No validation
1074 * - 'valid' Valid for batch processes
1075 * - 'usable' Valid for batch processes and login
1076 * - 'creatable' Valid for batch processes, login and account creation
1078 * @throws InvalidArgumentException
1079 * @return bool|string
1081 public static function getCanonicalName( $name, $validate = 'valid' ) {
1082 // Force usernames to capital
1084 $name = $wgContLang->ucfirst( $name );
1086 # Reject names containing '#'; these will be cleaned up
1087 # with title normalisation, but then it's too late to
1089 if ( strpos( $name, '#' ) !== false ) {
1093 // Clean up name according to title rules,
1094 // but only when validation is requested (bug 12654)
1095 $t = ( $validate !== false ) ?
1096 Title
::newFromText( $name, NS_USER
) : Title
::makeTitle( NS_USER
, $name );
1097 // Check for invalid titles
1098 if ( is_null( $t ) ||
$t->getNamespace() !== NS_USER ||
$t->isExternal() ) {
1102 // Reject various classes of invalid names
1103 $name = AuthManager
::callLegacyAuthPlugin(
1104 'getCanonicalName', [ $t->getText() ], $t->getText()
1107 switch ( $validate ) {
1111 if ( !User
::isValidUserName( $name ) ) {
1116 if ( !User
::isUsableName( $name ) ) {
1121 if ( !User
::isCreatableName( $name ) ) {
1126 throw new InvalidArgumentException(
1127 'Invalid parameter value for $validate in ' . __METHOD__
);
1133 * Count the number of edits of a user
1135 * @param int $uid User ID to check
1136 * @return int The user's edit count
1138 * @deprecated since 1.21 in favour of User::getEditCount
1140 public static function edits( $uid ) {
1141 wfDeprecated( __METHOD__
, '1.21' );
1142 $user = self
::newFromId( $uid );
1143 return $user->getEditCount();
1147 * Return a random password.
1149 * @deprecated since 1.27, use PasswordFactory::generateRandomPasswordString()
1150 * @return string New random password
1152 public static function randomPassword() {
1153 global $wgMinimalPasswordLength;
1154 return PasswordFactory
::generateRandomPasswordString( $wgMinimalPasswordLength );
1158 * Set cached properties to default.
1160 * @note This no longer clears uncached lazy-initialised properties;
1161 * the constructor does that instead.
1163 * @param string|bool $name
1165 public function loadDefaults( $name = false ) {
1167 $this->mName
= $name;
1168 $this->mRealName
= '';
1170 $this->mOptionOverrides
= null;
1171 $this->mOptionsLoaded
= false;
1173 $loggedOut = $this->mRequest
&& !defined( 'MW_NO_SESSION' )
1174 ?
$this->mRequest
->getSession()->getLoggedOutTimestamp() : 0;
1175 if ( $loggedOut !== 0 ) {
1176 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1178 $this->mTouched
= '1'; # Allow any pages to be cached
1181 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1182 $this->mEmailAuthenticated
= null;
1183 $this->mEmailToken
= '';
1184 $this->mEmailTokenExpires
= null;
1185 $this->mRegistration
= wfTimestamp( TS_MW
);
1186 $this->mGroups
= [];
1188 Hooks
::run( 'UserLoadDefaults', [ $this, $name ] );
1192 * Return whether an item has been loaded.
1194 * @param string $item Item to check. Current possibilities:
1198 * @param string $all 'all' to check if the whole object has been loaded
1199 * or any other string to check if only the item is available (e.g.
1203 public function isItemLoaded( $item, $all = 'all' ) {
1204 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1205 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1209 * Set that an item has been loaded
1211 * @param string $item
1213 protected function setItemLoaded( $item ) {
1214 if ( is_array( $this->mLoadedItems
) ) {
1215 $this->mLoadedItems
[$item] = true;
1220 * Load user data from the session.
1222 * @return bool True if the user is logged in, false otherwise.
1224 private function loadFromSession() {
1227 Hooks
::run( 'UserLoadFromSession', [ $this, &$result ], '1.27' );
1228 if ( $result !== null ) {
1232 // MediaWiki\Session\Session already did the necessary authentication of the user
1233 // returned here, so just use it if applicable.
1234 $session = $this->getRequest()->getSession();
1235 $user = $session->getUser();
1236 if ( $user->isLoggedIn() ) {
1237 $this->loadFromUserObject( $user );
1238 // Other code expects these to be set in the session, so set them.
1239 $session->set( 'wsUserID', $this->getId() );
1240 $session->set( 'wsUserName', $this->getName() );
1241 $session->set( 'wsToken', $this->getToken() );
1249 * Load user and user_group data from the database.
1250 * $this->mId must be set, this is how the user is identified.
1252 * @param integer $flags User::READ_* constant bitfield
1253 * @return bool True if the user exists, false if the user is anonymous
1255 public function loadFromDatabase( $flags = self
::READ_LATEST
) {
1257 $this->mId
= intval( $this->mId
);
1260 if ( !$this->mId
) {
1261 $this->loadDefaults();
1265 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
1266 $db = wfGetDB( $index );
1268 $s = $db->selectRow(
1270 self
::selectFields(),
1271 [ 'user_id' => $this->mId
],
1276 $this->queryFlagsUsed
= $flags;
1277 Hooks
::run( 'UserLoadFromDatabase', [ $this, &$s ] );
1279 if ( $s !== false ) {
1280 // Initialise user table data
1281 $this->loadFromRow( $s );
1282 $this->mGroups
= null; // deferred
1283 $this->getEditCount(); // revalidation for nulls
1288 $this->loadDefaults();
1294 * Initialize this object from a row from the user table.
1296 * @param stdClass $row Row from the user table to load.
1297 * @param array $data Further user data to load into the object
1299 * user_groups Array with groups out of the user_groups table
1300 * user_properties Array with properties out of the user_properties table
1302 protected function loadFromRow( $row, $data = null ) {
1305 $this->mGroups
= null; // deferred
1307 if ( isset( $row->user_name
) ) {
1308 $this->mName
= $row->user_name
;
1309 $this->mFrom
= 'name';
1310 $this->setItemLoaded( 'name' );
1315 if ( isset( $row->user_real_name
) ) {
1316 $this->mRealName
= $row->user_real_name
;
1317 $this->setItemLoaded( 'realname' );
1322 if ( isset( $row->user_id
) ) {
1323 $this->mId
= intval( $row->user_id
);
1324 $this->mFrom
= 'id';
1325 $this->setItemLoaded( 'id' );
1330 if ( isset( $row->user_id
) && isset( $row->user_name
) ) {
1331 self
::$idCacheByName[$row->user_name
] = $row->user_id
;
1334 if ( isset( $row->user_editcount
) ) {
1335 $this->mEditCount
= $row->user_editcount
;
1340 if ( isset( $row->user_touched
) ) {
1341 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1346 if ( isset( $row->user_token
) ) {
1347 // The definition for the column is binary(32), so trim the NULs
1348 // that appends. The previous definition was char(32), so trim
1350 $this->mToken
= rtrim( $row->user_token
, " \0" );
1351 if ( $this->mToken
=== '' ) {
1352 $this->mToken
= null;
1358 if ( isset( $row->user_email
) ) {
1359 $this->mEmail
= $row->user_email
;
1360 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1361 $this->mEmailToken
= $row->user_email_token
;
1362 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1363 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1369 $this->mLoadedItems
= true;
1372 if ( is_array( $data ) ) {
1373 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1374 $this->mGroups
= $data['user_groups'];
1376 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1377 $this->loadOptions( $data['user_properties'] );
1383 * Load the data for this user object from another user object.
1387 protected function loadFromUserObject( $user ) {
1389 $user->loadGroups();
1390 $user->loadOptions();
1391 foreach ( self
::$mCacheVars as $var ) {
1392 $this->$var = $user->$var;
1397 * Load the groups from the database if they aren't already loaded.
1399 private function loadGroups() {
1400 if ( is_null( $this->mGroups
) ) {
1401 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
1402 ?
wfGetDB( DB_MASTER
)
1403 : wfGetDB( DB_SLAVE
);
1404 $res = $db->select( 'user_groups',
1406 [ 'ug_user' => $this->mId
],
1408 $this->mGroups
= [];
1409 foreach ( $res as $row ) {
1410 $this->mGroups
[] = $row->ug_group
;
1416 * Add the user to the group if he/she meets given criteria.
1418 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1419 * possible to remove manually via Special:UserRights. In such case it
1420 * will not be re-added automatically. The user will also not lose the
1421 * group if they no longer meet the criteria.
1423 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1425 * @return array Array of groups the user has been promoted to.
1427 * @see $wgAutopromoteOnce
1429 public function addAutopromoteOnceGroups( $event ) {
1430 global $wgAutopromoteOnceLogInRC;
1432 if ( wfReadOnly() ||
!$this->getId() ) {
1436 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1437 if ( !count( $toPromote ) ) {
1441 if ( !$this->checkAndSetTouched() ) {
1442 return []; // raced out (bug T48834)
1445 $oldGroups = $this->getGroups(); // previous groups
1446 foreach ( $toPromote as $group ) {
1447 $this->addGroup( $group );
1449 // update groups in external authentication database
1450 Hooks
::run( 'UserGroupsChanged', [ $this, $toPromote, [], false, false ] );
1451 AuthManager
::callLegacyAuthPlugin( 'updateExternalDBGroups', [ $this, $toPromote ] );
1453 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1455 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1456 $logEntry->setPerformer( $this );
1457 $logEntry->setTarget( $this->getUserPage() );
1458 $logEntry->setParameters( [
1459 '4::oldgroups' => $oldGroups,
1460 '5::newgroups' => $newGroups,
1462 $logid = $logEntry->insert();
1463 if ( $wgAutopromoteOnceLogInRC ) {
1464 $logEntry->publish( $logid );
1471 * Builds update conditions. Additional conditions may be added to $conditions to
1472 * protected against race conditions using a compare-and-set (CAS) mechanism
1473 * based on comparing $this->mTouched with the user_touched field.
1475 * @param DatabaseBase $db
1476 * @param array $conditions WHERE conditions for use with DatabaseBase::update
1477 * @return array WHERE conditions for use with DatabaseBase::update
1479 protected function makeUpdateConditions( DatabaseBase
$db, array $conditions ) {
1480 if ( $this->mTouched
) {
1481 // CAS check: only update if the row wasn't changed sicne it was loaded.
1482 $conditions['user_touched'] = $db->timestamp( $this->mTouched
);
1489 * Bump user_touched if it didn't change since this object was loaded
1491 * On success, the mTouched field is updated.
1492 * The user serialization cache is always cleared.
1494 * @return bool Whether user_touched was actually updated
1497 protected function checkAndSetTouched() {
1500 if ( !$this->mId
) {
1501 return false; // anon
1504 // Get a new user_touched that is higher than the old one
1505 $newTouched = $this->newTouchedTimestamp();
1507 $dbw = wfGetDB( DB_MASTER
);
1508 $dbw->update( 'user',
1509 [ 'user_touched' => $dbw->timestamp( $newTouched ) ],
1510 $this->makeUpdateConditions( $dbw, [
1511 'user_id' => $this->mId
,
1515 $success = ( $dbw->affectedRows() > 0 );
1518 $this->mTouched
= $newTouched;
1519 $this->clearSharedCache();
1521 // Clears on failure too since that is desired if the cache is stale
1522 $this->clearSharedCache( 'refresh' );
1529 * Clear various cached data stored in this object. The cache of the user table
1530 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1532 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1533 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1535 public function clearInstanceCache( $reloadFrom = false ) {
1536 $this->mNewtalk
= -1;
1537 $this->mDatePreference
= null;
1538 $this->mBlockedby
= -1; # Unset
1539 $this->mHash
= false;
1540 $this->mRights
= null;
1541 $this->mEffectiveGroups
= null;
1542 $this->mImplicitGroups
= null;
1543 $this->mGroups
= null;
1544 $this->mOptions
= null;
1545 $this->mOptionsLoaded
= false;
1546 $this->mEditCount
= null;
1548 if ( $reloadFrom ) {
1549 $this->mLoadedItems
= [];
1550 $this->mFrom
= $reloadFrom;
1555 * Combine the language default options with any site-specific options
1556 * and add the default language variants.
1558 * @return array Array of String options
1560 public static function getDefaultOptions() {
1561 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1563 static $defOpt = null;
1564 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1565 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1566 // mid-request and see that change reflected in the return value of this function.
1567 // Which is insane and would never happen during normal MW operation
1571 $defOpt = $wgDefaultUserOptions;
1572 // Default language setting
1573 $defOpt['language'] = $wgContLang->getCode();
1574 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1575 $defOpt[$langCode == $wgContLang->getCode() ?
'variant' : "variant-$langCode"] = $langCode;
1577 $namespaces = MediaWikiServices
::getInstance()->getSearchEngineConfig()->searchableNamespaces();
1578 foreach ( $namespaces as $nsnum => $nsname ) {
1579 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1581 $defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1583 Hooks
::run( 'UserGetDefaultOptions', [ &$defOpt ] );
1589 * Get a given default option value.
1591 * @param string $opt Name of option to retrieve
1592 * @return string Default option value
1594 public static function getDefaultOption( $opt ) {
1595 $defOpts = self
::getDefaultOptions();
1596 if ( isset( $defOpts[$opt] ) ) {
1597 return $defOpts[$opt];
1604 * Get blocking information
1605 * @param bool $bFromSlave Whether to check the slave database first.
1606 * To improve performance, non-critical checks are done against slaves.
1607 * Check when actually saving should be done against master.
1609 private function getBlockedStatus( $bFromSlave = true ) {
1610 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1612 if ( -1 != $this->mBlockedby
) {
1616 wfDebug( __METHOD__
. ": checking...\n" );
1618 // Initialize data...
1619 // Otherwise something ends up stomping on $this->mBlockedby when
1620 // things get lazy-loaded later, causing false positive block hits
1621 // due to -1 !== 0. Probably session-related... Nothing should be
1622 // overwriting mBlockedby, surely?
1625 # We only need to worry about passing the IP address to the Block generator if the
1626 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1627 # know which IP address they're actually coming from
1629 if ( !$this->isAllowed( 'ipblock-exempt' ) ) {
1630 // $wgUser->getName() only works after the end of Setup.php. Until
1631 // then, assume it's a logged-out user.
1632 $globalUserName = $wgUser->isSafeToLoad()
1633 ?
$wgUser->getName()
1634 : IP
::sanitizeIP( $wgUser->getRequest()->getIP() );
1635 if ( $this->getName() === $globalUserName ) {
1636 $ip = $this->getRequest()->getIP();
1641 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1644 if ( !$block instanceof Block
&& $ip !== null && !in_array( $ip, $wgProxyWhitelist ) ) {
1646 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1648 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1649 $block->mReason
= wfMessage( 'proxyblockreason' )->text();
1650 $block->setTarget( $ip );
1651 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1653 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1654 $block->mReason
= wfMessage( 'sorbsreason' )->text();
1655 $block->setTarget( $ip );
1659 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1660 if ( !$block instanceof Block
1661 && $wgApplyIpBlocksToXff
1663 && !in_array( $ip, $wgProxyWhitelist )
1665 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1666 $xff = array_map( 'trim', explode( ',', $xff ) );
1667 $xff = array_diff( $xff, [ $ip ] );
1668 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1669 $block = Block
::chooseBlock( $xffblocks, $xff );
1670 if ( $block instanceof Block
) {
1671 # Mangle the reason to alert the user that the block
1672 # originated from matching the X-Forwarded-For header.
1673 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->text();
1677 if ( $block instanceof Block
) {
1678 wfDebug( __METHOD__
. ": Found block.\n" );
1679 $this->mBlock
= $block;
1680 $this->mBlockedby
= $block->getByName();
1681 $this->mBlockreason
= $block->mReason
;
1682 $this->mHideName
= $block->mHideName
;
1683 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1685 $this->mBlockedby
= '';
1686 $this->mHideName
= 0;
1687 $this->mAllowUsertalk
= false;
1691 Hooks
::run( 'GetBlockedStatus', [ &$this ] );
1696 * Whether the given IP is in a DNS blacklist.
1698 * @param string $ip IP to check
1699 * @param bool $checkWhitelist Whether to check the whitelist first
1700 * @return bool True if blacklisted.
1702 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1703 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1705 if ( !$wgEnableDnsBlacklist ) {
1709 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1713 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1717 * Whether the given IP is in a given DNS blacklist.
1719 * @param string $ip IP to check
1720 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1721 * @return bool True if blacklisted.
1723 public function inDnsBlacklist( $ip, $bases ) {
1726 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1727 if ( IP
::isIPv4( $ip ) ) {
1728 // Reverse IP, bug 21255
1729 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1731 foreach ( (array)$bases as $base ) {
1733 // If we have an access key, use that too (ProjectHoneypot, etc.)
1735 if ( is_array( $base ) ) {
1736 if ( count( $base ) >= 2 ) {
1737 // Access key is 1, base URL is 0
1738 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1740 $host = "$ipReversed.{$base[0]}";
1742 $basename = $base[0];
1744 $host = "$ipReversed.$base";
1748 $ipList = gethostbynamel( $host );
1751 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
1755 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
1764 * Check if an IP address is in the local proxy list
1770 public static function isLocallyBlockedProxy( $ip ) {
1771 global $wgProxyList;
1773 if ( !$wgProxyList ) {
1777 if ( !is_array( $wgProxyList ) ) {
1778 // Load from the specified file
1779 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1782 if ( !is_array( $wgProxyList ) ) {
1784 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1786 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1787 // Old-style flipped proxy list
1796 * Is this user subject to rate limiting?
1798 * @return bool True if rate limited
1800 public function isPingLimitable() {
1801 global $wgRateLimitsExcludedIPs;
1802 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1803 // No other good way currently to disable rate limits
1804 // for specific IPs. :P
1805 // But this is a crappy hack and should die.
1808 return !$this->isAllowed( 'noratelimit' );
1812 * Primitive rate limits: enforce maximum actions per time period
1813 * to put a brake on flooding.
1815 * The method generates both a generic profiling point and a per action one
1816 * (suffix being "-$action".
1818 * @note When using a shared cache like memcached, IP-address
1819 * last-hit counters will be shared across wikis.
1821 * @param string $action Action to enforce; 'edit' if unspecified
1822 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1823 * @return bool True if a rate limiter was tripped
1825 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1826 // Call the 'PingLimiter' hook
1828 if ( !Hooks
::run( 'PingLimiter', [ &$this, $action, &$result, $incrBy ] ) ) {
1832 global $wgRateLimits;
1833 if ( !isset( $wgRateLimits[$action] ) ) {
1837 // Some groups shouldn't trigger the ping limiter, ever
1838 if ( !$this->isPingLimitable() ) {
1842 $limits = $wgRateLimits[$action];
1844 $id = $this->getId();
1846 $isNewbie = $this->isNewbie();
1850 if ( isset( $limits['anon'] ) ) {
1851 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1854 // limits for logged-in users
1855 if ( isset( $limits['user'] ) ) {
1856 $userLimit = $limits['user'];
1858 // limits for newbie logged-in users
1859 if ( $isNewbie && isset( $limits['newbie'] ) ) {
1860 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1864 // limits for anons and for newbie logged-in users
1867 if ( isset( $limits['ip'] ) ) {
1868 $ip = $this->getRequest()->getIP();
1869 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1871 // subnet-based limits
1872 if ( isset( $limits['subnet'] ) ) {
1873 $ip = $this->getRequest()->getIP();
1874 $subnet = IP
::getSubnet( $ip );
1875 if ( $subnet !== false ) {
1876 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1881 // Check for group-specific permissions
1882 // If more than one group applies, use the group with the highest limit ratio (max/period)
1883 foreach ( $this->getGroups() as $group ) {
1884 if ( isset( $limits[$group] ) ) {
1885 if ( $userLimit === false
1886 ||
$limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1888 $userLimit = $limits[$group];
1893 // Set the user limit key
1894 if ( $userLimit !== false ) {
1895 list( $max, $period ) = $userLimit;
1896 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
1897 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1900 // ip-based limits for all ping-limitable users
1901 if ( isset( $limits['ip-all'] ) ) {
1902 $ip = $this->getRequest()->getIP();
1903 // ignore if user limit is more permissive
1904 if ( $isNewbie ||
$userLimit === false
1905 ||
$limits['ip-all'][0] / $limits['ip-all'][1] > $userLimit[0] / $userLimit[1] ) {
1906 $keys["mediawiki:limiter:$action:ip-all:$ip"] = $limits['ip-all'];
1910 // subnet-based limits for all ping-limitable users
1911 if ( isset( $limits['subnet-all'] ) ) {
1912 $ip = $this->getRequest()->getIP();
1913 $subnet = IP
::getSubnet( $ip );
1914 if ( $subnet !== false ) {
1915 // ignore if user limit is more permissive
1916 if ( $isNewbie ||
$userLimit === false
1917 ||
$limits['ip-all'][0] / $limits['ip-all'][1]
1918 > $userLimit[0] / $userLimit[1] ) {
1919 $keys["mediawiki:limiter:$action:subnet-all:$subnet"] = $limits['subnet-all'];
1924 $cache = ObjectCache
::getLocalClusterInstance();
1927 foreach ( $keys as $key => $limit ) {
1928 list( $max, $period ) = $limit;
1929 $summary = "(limit $max in {$period}s)";
1930 $count = $cache->get( $key );
1933 if ( $count >= $max ) {
1934 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1935 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1938 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1941 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1942 if ( $incrBy > 0 ) {
1943 $cache->add( $key, 0, intval( $period ) ); // first ping
1946 if ( $incrBy > 0 ) {
1947 $cache->incr( $key, $incrBy );
1955 * Check if user is blocked
1957 * @param bool $bFromSlave Whether to check the slave database instead of
1958 * the master. Hacked from false due to horrible probs on site.
1959 * @return bool True if blocked, false otherwise
1961 public function isBlocked( $bFromSlave = true ) {
1962 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
1966 * Get the block affecting the user, or null if the user is not blocked
1968 * @param bool $bFromSlave Whether to check the slave database instead of the master
1969 * @return Block|null
1971 public function getBlock( $bFromSlave = true ) {
1972 $this->getBlockedStatus( $bFromSlave );
1973 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
1977 * Check if user is blocked from editing a particular article
1979 * @param Title $title Title to check
1980 * @param bool $bFromSlave Whether to check the slave database instead of the master
1983 public function isBlockedFrom( $title, $bFromSlave = false ) {
1984 global $wgBlockAllowsUTEdit;
1986 $blocked = $this->isBlocked( $bFromSlave );
1987 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
1988 // If a user's name is suppressed, they cannot make edits anywhere
1989 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName()
1990 && $title->getNamespace() == NS_USER_TALK
) {
1992 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
1995 Hooks
::run( 'UserIsBlockedFrom', [ $this, $title, &$blocked, &$allowUsertalk ] );
2001 * If user is blocked, return the name of the user who placed the block
2002 * @return string Name of blocker
2004 public function blockedBy() {
2005 $this->getBlockedStatus();
2006 return $this->mBlockedby
;
2010 * If user is blocked, return the specified reason for the block
2011 * @return string Blocking reason
2013 public function blockedFor() {
2014 $this->getBlockedStatus();
2015 return $this->mBlockreason
;
2019 * If user is blocked, return the ID for the block
2020 * @return int Block ID
2022 public function getBlockId() {
2023 $this->getBlockedStatus();
2024 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
2028 * Check if user is blocked on all wikis.
2029 * Do not use for actual edit permission checks!
2030 * This is intended for quick UI checks.
2032 * @param string $ip IP address, uses current client if none given
2033 * @return bool True if blocked, false otherwise
2035 public function isBlockedGlobally( $ip = '' ) {
2036 return $this->getGlobalBlock( $ip ) instanceof Block
;
2040 * Check if user is blocked on all wikis.
2041 * Do not use for actual edit permission checks!
2042 * This is intended for quick UI checks.
2044 * @param string $ip IP address, uses current client if none given
2045 * @return Block|null Block object if blocked, null otherwise
2046 * @throws FatalError
2047 * @throws MWException
2049 public function getGlobalBlock( $ip = '' ) {
2050 if ( $this->mGlobalBlock
!== null ) {
2051 return $this->mGlobalBlock ?
: null;
2053 // User is already an IP?
2054 if ( IP
::isIPAddress( $this->getName() ) ) {
2055 $ip = $this->getName();
2057 $ip = $this->getRequest()->getIP();
2061 Hooks
::run( 'UserIsBlockedGlobally', [ &$this, $ip, &$blocked, &$block ] );
2063 if ( $blocked && $block === null ) {
2064 // back-compat: UserIsBlockedGlobally didn't have $block param first
2066 $block->setTarget( $ip );
2069 $this->mGlobalBlock
= $blocked ?
$block : false;
2070 return $this->mGlobalBlock ?
: null;
2074 * Check if user account is locked
2076 * @return bool True if locked, false otherwise
2078 public function isLocked() {
2079 if ( $this->mLocked
!== null ) {
2080 return $this->mLocked
;
2082 $authUser = AuthManager
::callLegacyAuthPlugin( 'getUserInstance', [ &$this ], null );
2083 $this->mLocked
= $authUser && $authUser->isLocked();
2084 Hooks
::run( 'UserIsLocked', [ $this, &$this->mLocked
] );
2085 return $this->mLocked
;
2089 * Check if user account is hidden
2091 * @return bool True if hidden, false otherwise
2093 public function isHidden() {
2094 if ( $this->mHideName
!== null ) {
2095 return $this->mHideName
;
2097 $this->getBlockedStatus();
2098 if ( !$this->mHideName
) {
2099 $authUser = AuthManager
::callLegacyAuthPlugin( 'getUserInstance', [ &$this ], null );
2100 $this->mHideName
= $authUser && $authUser->isHidden();
2101 Hooks
::run( 'UserIsHidden', [ $this, &$this->mHideName
] );
2103 return $this->mHideName
;
2107 * Get the user's ID.
2108 * @return int The user's ID; 0 if the user is anonymous or nonexistent
2110 public function getId() {
2111 if ( $this->mId
=== null && $this->mName
!== null && User
::isIP( $this->mName
) ) {
2112 // Special case, we know the user is anonymous
2114 } elseif ( !$this->isItemLoaded( 'id' ) ) {
2115 // Don't load if this was initialized from an ID
2119 return (int)$this->mId
;
2123 * Set the user and reload all fields according to a given ID
2124 * @param int $v User ID to reload
2126 public function setId( $v ) {
2128 $this->clearInstanceCache( 'id' );
2132 * Get the user name, or the IP of an anonymous user
2133 * @return string User's name or IP address
2135 public function getName() {
2136 if ( $this->isItemLoaded( 'name', 'only' ) ) {
2137 // Special case optimisation
2138 return $this->mName
;
2141 if ( $this->mName
=== false ) {
2143 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
2145 return $this->mName
;
2150 * Set the user name.
2152 * This does not reload fields from the database according to the given
2153 * name. Rather, it is used to create a temporary "nonexistent user" for
2154 * later addition to the database. It can also be used to set the IP
2155 * address for an anonymous user to something other than the current
2158 * @note User::newFromName() has roughly the same function, when the named user
2160 * @param string $str New user name to set
2162 public function setName( $str ) {
2164 $this->mName
= $str;
2168 * Get the user's name escaped by underscores.
2169 * @return string Username escaped by underscores.
2171 public function getTitleKey() {
2172 return str_replace( ' ', '_', $this->getName() );
2176 * Check if the user has new messages.
2177 * @return bool True if the user has new messages
2179 public function getNewtalk() {
2182 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2183 if ( $this->mNewtalk
=== -1 ) {
2184 $this->mNewtalk
= false; # reset talk page status
2186 // Check memcached separately for anons, who have no
2187 // entire User object stored in there.
2188 if ( !$this->mId
) {
2189 global $wgDisableAnonTalk;
2190 if ( $wgDisableAnonTalk ) {
2191 // Anon newtalk disabled by configuration.
2192 $this->mNewtalk
= false;
2194 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
2197 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2201 return (bool)$this->mNewtalk
;
2205 * Return the data needed to construct links for new talk page message
2206 * alerts. If there are new messages, this will return an associative array
2207 * with the following data:
2208 * wiki: The database name of the wiki
2209 * link: Root-relative link to the user's talk page
2210 * rev: The last talk page revision that the user has seen or null. This
2211 * is useful for building diff links.
2212 * If there are no new messages, it returns an empty array.
2213 * @note This function was designed to accomodate multiple talk pages, but
2214 * currently only returns a single link and revision.
2217 public function getNewMessageLinks() {
2219 if ( !Hooks
::run( 'UserRetrieveNewTalks', [ &$this, &$talks ] ) ) {
2221 } elseif ( !$this->getNewtalk() ) {
2224 $utp = $this->getTalkPage();
2225 $dbr = wfGetDB( DB_SLAVE
);
2226 // Get the "last viewed rev" timestamp from the oldest message notification
2227 $timestamp = $dbr->selectField( 'user_newtalk',
2228 'MIN(user_last_timestamp)',
2229 $this->isAnon() ?
[ 'user_ip' => $this->getName() ] : [ 'user_id' => $this->getId() ],
2231 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2232 return [ [ 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ] ];
2236 * Get the revision ID for the last talk page revision viewed by the talk
2238 * @return int|null Revision ID or null
2240 public function getNewMessageRevisionId() {
2241 $newMessageRevisionId = null;
2242 $newMessageLinks = $this->getNewMessageLinks();
2243 if ( $newMessageLinks ) {
2244 // Note: getNewMessageLinks() never returns more than a single link
2245 // and it is always for the same wiki, but we double-check here in
2246 // case that changes some time in the future.
2247 if ( count( $newMessageLinks ) === 1
2248 && $newMessageLinks[0]['wiki'] === wfWikiID()
2249 && $newMessageLinks[0]['rev']
2251 /** @var Revision $newMessageRevision */
2252 $newMessageRevision = $newMessageLinks[0]['rev'];
2253 $newMessageRevisionId = $newMessageRevision->getId();
2256 return $newMessageRevisionId;
2260 * Internal uncached check for new messages
2263 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2264 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2265 * @return bool True if the user has new messages
2267 protected function checkNewtalk( $field, $id ) {
2268 $dbr = wfGetDB( DB_SLAVE
);
2270 $ok = $dbr->selectField( 'user_newtalk', $field, [ $field => $id ], __METHOD__
);
2272 return $ok !== false;
2276 * Add or update the new messages flag
2277 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2278 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2279 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2280 * @return bool True if successful, false otherwise
2282 protected function updateNewtalk( $field, $id, $curRev = null ) {
2283 // Get timestamp of the talk page revision prior to the current one
2284 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2285 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2286 // Mark the user as having new messages since this revision
2287 $dbw = wfGetDB( DB_MASTER
);
2288 $dbw->insert( 'user_newtalk',
2289 [ $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ],
2292 if ( $dbw->affectedRows() ) {
2293 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2296 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2302 * Clear the new messages flag for the given user
2303 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2304 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2305 * @return bool True if successful, false otherwise
2307 protected function deleteNewtalk( $field, $id ) {
2308 $dbw = wfGetDB( DB_MASTER
);
2309 $dbw->delete( 'user_newtalk',
2312 if ( $dbw->affectedRows() ) {
2313 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2316 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2322 * Update the 'You have new messages!' status.
2323 * @param bool $val Whether the user has new messages
2324 * @param Revision $curRev New, as yet unseen revision of the user talk
2325 * page. Ignored if null or !$val.
2327 public function setNewtalk( $val, $curRev = null ) {
2328 if ( wfReadOnly() ) {
2333 $this->mNewtalk
= $val;
2335 if ( $this->isAnon() ) {
2337 $id = $this->getName();
2340 $id = $this->getId();
2344 $changed = $this->updateNewtalk( $field, $id, $curRev );
2346 $changed = $this->deleteNewtalk( $field, $id );
2350 $this->invalidateCache();
2355 * Generate a current or new-future timestamp to be stored in the
2356 * user_touched field when we update things.
2357 * @return string Timestamp in TS_MW format
2359 private function newTouchedTimestamp() {
2360 global $wgClockSkewFudge;
2362 $time = wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2363 if ( $this->mTouched
&& $time <= $this->mTouched
) {
2364 $time = wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $this->mTouched
) +
1 );
2371 * Clear user data from memcached
2373 * Use after applying updates to the database; caller's
2374 * responsibility to update user_touched if appropriate.
2376 * Called implicitly from invalidateCache() and saveSettings().
2378 * @param string $mode Use 'refresh' to clear now; otherwise before DB commit
2380 public function clearSharedCache( $mode = 'changed' ) {
2381 if ( !$this->getId() ) {
2385 $cache = ObjectCache
::getMainWANInstance();
2386 $processCache = self
::getInProcessCache();
2387 $key = $this->getCacheKey( $cache );
2388 if ( $mode === 'refresh' ) {
2389 $cache->delete( $key, 1 );
2390 $processCache->delete( $key );
2392 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle(
2393 function() use ( $cache, $processCache, $key ) {
2394 $cache->delete( $key );
2395 $processCache->delete( $key );
2402 * Immediately touch the user data cache for this account
2404 * Calls touch() and removes account data from memcached
2406 public function invalidateCache() {
2408 $this->clearSharedCache();
2412 * Update the "touched" timestamp for the user
2414 * This is useful on various login/logout events when making sure that
2415 * a browser or proxy that has multiple tenants does not suffer cache
2416 * pollution where the new user sees the old users content. The value
2417 * of getTouched() is checked when determining 304 vs 200 responses.
2418 * Unlike invalidateCache(), this preserves the User object cache and
2419 * avoids database writes.
2423 public function touch() {
2424 $id = $this->getId();
2426 $key = wfMemcKey( 'user-quicktouched', 'id', $id );
2427 ObjectCache
::getMainWANInstance()->touchCheckKey( $key );
2428 $this->mQuickTouched
= null;
2433 * Validate the cache for this account.
2434 * @param string $timestamp A timestamp in TS_MW format
2437 public function validateCache( $timestamp ) {
2438 return ( $timestamp >= $this->getTouched() );
2442 * Get the user touched timestamp
2444 * Use this value only to validate caches via inequalities
2445 * such as in the case of HTTP If-Modified-Since response logic
2447 * @return string TS_MW Timestamp
2449 public function getTouched() {
2453 if ( $this->mQuickTouched
=== null ) {
2454 $key = wfMemcKey( 'user-quicktouched', 'id', $this->mId
);
2455 $cache = ObjectCache
::getMainWANInstance();
2457 $this->mQuickTouched
= wfTimestamp( TS_MW
, $cache->getCheckKeyTime( $key ) );
2460 return max( $this->mTouched
, $this->mQuickTouched
);
2463 return $this->mTouched
;
2467 * Get the user_touched timestamp field (time of last DB updates)
2468 * @return string TS_MW Timestamp
2471 public function getDBTouched() {
2474 return $this->mTouched
;
2478 * @deprecated Removed in 1.27.
2482 public function getPassword() {
2483 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2487 * @deprecated Removed in 1.27.
2491 public function getTemporaryPassword() {
2492 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2496 * Set the password and reset the random token.
2497 * Calls through to authentication plugin if necessary;
2498 * will have no effect if the auth plugin refuses to
2499 * pass the change through or if the legal password
2502 * As a special case, setting the password to null
2503 * wipes it, so the account cannot be logged in until
2504 * a new password is set, for instance via e-mail.
2506 * @deprecated since 1.27, use AuthManager instead
2507 * @param string $str New password to set
2508 * @throws PasswordError On failure
2511 public function setPassword( $str ) {
2512 global $wgAuth, $wgDisableAuthManager;
2514 if ( !$wgDisableAuthManager ) {
2515 return $this->setPasswordInternal( $str );
2518 if ( $str !== null ) {
2519 if ( !$wgAuth->allowPasswordChange() ) {
2520 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2523 $status = $this->checkPasswordValidity( $str );
2524 if ( !$status->isGood() ) {
2525 throw new PasswordError( $status->getMessage()->text() );
2529 if ( !$wgAuth->setPassword( $this, $str ) ) {
2530 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2533 $this->setOption( 'watchlisttoken', false );
2534 $this->setPasswordInternal( $str );
2540 * Set the password and reset the random token unconditionally.
2542 * @deprecated since 1.27, use AuthManager instead
2543 * @param string|null $str New password to set or null to set an invalid
2544 * password hash meaning that the user will not be able to log in
2545 * through the web interface.
2547 public function setInternalPassword( $str ) {
2548 global $wgAuth, $wgDisableAuthManager;
2550 if ( !$wgDisableAuthManager ) {
2551 $this->setPasswordInternal( $str );
2554 if ( $wgAuth->allowSetLocalPassword() ) {
2555 $this->setOption( 'watchlisttoken', false );
2556 $this->setPasswordInternal( $str );
2561 * Actually set the password and such
2562 * @since 1.27 cannot set a password for a user not in the database
2563 * @param string|null $str New password to set or null to set an invalid
2564 * password hash meaning that the user will not be able to log in
2565 * through the web interface.
2566 * @return bool Success
2568 private function setPasswordInternal( $str ) {
2569 global $wgDisableAuthManager;
2571 if ( $wgDisableAuthManager ) {
2572 $id = self
::idFromName( $this->getName(), self
::READ_LATEST
);
2574 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2577 $passwordFactory = new PasswordFactory();
2578 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
2579 $dbw = wfGetDB( DB_MASTER
);
2583 'user_password' => $passwordFactory->newFromPlaintext( $str )->toString(),
2584 'user_newpassword' => PasswordFactory
::newInvalidPassword()->toString(),
2585 'user_newpass_time' => $dbw->timestampOrNull( null ),
2593 // When the main password is changed, invalidate all bot passwords too
2594 BotPassword
::invalidateAllPasswordsForUser( $this->getName() );
2596 $manager = AuthManager
::singleton();
2598 // If the user doesn't exist yet, fail
2599 if ( !$manager->userExists( $this->getName() ) ) {
2600 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2604 'username' => $this->getName(),
2608 $reqs = $manager->getAuthenticationRequests( AuthManager
::ACTION_CHANGE
, $this );
2609 $reqs = AuthenticationRequest
::loadRequestsFromSubmission( $reqs, $data );
2610 foreach ( $reqs as $req ) {
2611 $status = $manager->allowsAuthenticationDataChange( $req );
2612 if ( !$status->isOk() ) {
2613 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
2614 ->info( __METHOD__
. ': Password change rejected: ' . $status->getWikiText() );
2618 foreach ( $reqs as $req ) {
2619 $manager->changeAuthenticationData( $req );
2622 $this->setOption( 'watchlisttoken', false );
2625 SessionManager
::singleton()->invalidateSessionsForUser( $this );
2631 * Get the user's current token.
2632 * @param bool $forceCreation Force the generation of a new token if the
2633 * user doesn't have one (default=true for backwards compatibility).
2634 * @return string|null Token
2636 public function getToken( $forceCreation = true ) {
2637 global $wgAuthenticationTokenVersion;
2640 if ( !$this->mToken
&& $forceCreation ) {
2644 if ( !$this->mToken
) {
2645 // The user doesn't have a token, return null to indicate that.
2647 } elseif ( $this->mToken
=== self
::INVALID_TOKEN
) {
2648 // We return a random value here so existing token checks are very
2650 return MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2651 } elseif ( $wgAuthenticationTokenVersion === null ) {
2652 // $wgAuthenticationTokenVersion not in use, so return the raw secret
2653 return $this->mToken
;
2655 // $wgAuthenticationTokenVersion in use, so hmac it.
2656 $ret = MWCryptHash
::hmac( $wgAuthenticationTokenVersion, $this->mToken
, false );
2658 // The raw hash can be overly long. Shorten it up.
2659 $len = max( 32, self
::TOKEN_LENGTH
);
2660 if ( strlen( $ret ) < $len ) {
2661 // Should never happen, even md5 is 128 bits
2662 throw new \
UnexpectedValueException( 'Hmac returned less than 128 bits' );
2664 return substr( $ret, -$len );
2669 * Set the random token (used for persistent authentication)
2670 * Called from loadDefaults() among other places.
2672 * @param string|bool $token If specified, set the token to this value
2674 public function setToken( $token = false ) {
2676 if ( $this->mToken
=== self
::INVALID_TOKEN
) {
2677 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
2678 ->debug( __METHOD__
. ": Ignoring attempt to set token for system user \"$this\"" );
2679 } elseif ( !$token ) {
2680 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2682 $this->mToken
= $token;
2687 * Set the password for a password reminder or new account email
2689 * @deprecated Removed in 1.27. Use PasswordReset instead.
2690 * @param string $str New password to set or null to set an invalid
2691 * password hash meaning that the user will not be able to use it
2692 * @param bool $throttle If true, reset the throttle timestamp to the present
2694 public function setNewpassword( $str, $throttle = true ) {
2695 global $wgDisableAuthManager;
2697 if ( $wgDisableAuthManager ) {
2698 $id = $this->getId();
2700 throw new LogicException( 'Cannot set new password for a user that is not in the database.' );
2703 $dbw = wfGetDB( DB_MASTER
);
2705 $passwordFactory = new PasswordFactory();
2706 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
2708 'user_newpassword' => $passwordFactory->newFromPlaintext( $str )->toString(),
2711 if ( $str === null ) {
2712 $update['user_newpass_time'] = null;
2713 } elseif ( $throttle ) {
2714 $update['user_newpass_time'] = $dbw->timestamp();
2717 $dbw->update( 'user', $update, [ 'user_id' => $id ], __METHOD__
);
2719 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2724 * Has password reminder email been sent within the last
2725 * $wgPasswordReminderResendTime hours?
2726 * @deprecated Removed in 1.27. See above.
2729 public function isPasswordReminderThrottled() {
2730 global $wgPasswordReminderResendTime, $wgDisableAuthManager;
2732 if ( $wgDisableAuthManager ) {
2733 if ( !$wgPasswordReminderResendTime ) {
2739 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
2740 ?
wfGetDB( DB_MASTER
)
2741 : wfGetDB( DB_SLAVE
);
2742 $newpassTime = $db->selectField(
2744 'user_newpass_time',
2745 [ 'user_id' => $this->getId() ],
2749 if ( $newpassTime === null ) {
2752 $expiry = wfTimestamp( TS_UNIX
, $newpassTime ) +
$wgPasswordReminderResendTime * 3600;
2753 return time() < $expiry;
2755 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2760 * Get the user's e-mail address
2761 * @return string User's email address
2763 public function getEmail() {
2765 Hooks
::run( 'UserGetEmail', [ $this, &$this->mEmail
] );
2766 return $this->mEmail
;
2770 * Get the timestamp of the user's e-mail authentication
2771 * @return string TS_MW timestamp
2773 public function getEmailAuthenticationTimestamp() {
2775 Hooks
::run( 'UserGetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
2776 return $this->mEmailAuthenticated
;
2780 * Set the user's e-mail address
2781 * @param string $str New e-mail address
2783 public function setEmail( $str ) {
2785 if ( $str == $this->mEmail
) {
2788 $this->invalidateEmail();
2789 $this->mEmail
= $str;
2790 Hooks
::run( 'UserSetEmail', [ $this, &$this->mEmail
] );
2794 * Set the user's e-mail address and a confirmation mail if needed.
2797 * @param string $str New e-mail address
2800 public function setEmailWithConfirmation( $str ) {
2801 global $wgEnableEmail, $wgEmailAuthentication;
2803 if ( !$wgEnableEmail ) {
2804 return Status
::newFatal( 'emaildisabled' );
2807 $oldaddr = $this->getEmail();
2808 if ( $str === $oldaddr ) {
2809 return Status
::newGood( true );
2812 $type = $oldaddr != '' ?
'changed' : 'set';
2813 $notificationResult = null;
2815 if ( $wgEmailAuthentication ) {
2816 // Send the user an email notifying the user of the change in registered
2817 // email address on their previous email address
2818 if ( $type == 'changed' ) {
2819 $change = $str != '' ?
'changed' : 'removed';
2820 $notificationResult = $this->sendMail(
2821 wfMessage( 'notificationemail_subject_' . $change )->text(),
2822 wfMessage( 'notificationemail_body_' . $change,
2823 $this->getRequest()->getIP(),
2830 $this->setEmail( $str );
2832 if ( $str !== '' && $wgEmailAuthentication ) {
2833 // Send a confirmation request to the new address if needed
2834 $result = $this->sendConfirmationMail( $type );
2836 if ( $notificationResult !== null ) {
2837 $result->merge( $notificationResult );
2840 if ( $result->isGood() ) {
2841 // Say to the caller that a confirmation and notification mail has been sent
2842 $result->value
= 'eauth';
2845 $result = Status
::newGood( true );
2852 * Get the user's real name
2853 * @return string User's real name
2855 public function getRealName() {
2856 if ( !$this->isItemLoaded( 'realname' ) ) {
2860 return $this->mRealName
;
2864 * Set the user's real name
2865 * @param string $str New real name
2867 public function setRealName( $str ) {
2869 $this->mRealName
= $str;
2873 * Get the user's current setting for a given option.
2875 * @param string $oname The option to check
2876 * @param string $defaultOverride A default value returned if the option does not exist
2877 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2878 * @return string User's current value for the option
2879 * @see getBoolOption()
2880 * @see getIntOption()
2882 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2883 global $wgHiddenPrefs;
2884 $this->loadOptions();
2886 # We want 'disabled' preferences to always behave as the default value for
2887 # users, even if they have set the option explicitly in their settings (ie they
2888 # set it, and then it was disabled removing their ability to change it). But
2889 # we don't want to erase the preferences in the database in case the preference
2890 # is re-enabled again. So don't touch $mOptions, just override the returned value
2891 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2892 return self
::getDefaultOption( $oname );
2895 if ( array_key_exists( $oname, $this->mOptions
) ) {
2896 return $this->mOptions
[$oname];
2898 return $defaultOverride;
2903 * Get all user's options
2905 * @param int $flags Bitwise combination of:
2906 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2907 * to the default value. (Since 1.25)
2910 public function getOptions( $flags = 0 ) {
2911 global $wgHiddenPrefs;
2912 $this->loadOptions();
2913 $options = $this->mOptions
;
2915 # We want 'disabled' preferences to always behave as the default value for
2916 # users, even if they have set the option explicitly in their settings (ie they
2917 # set it, and then it was disabled removing their ability to change it). But
2918 # we don't want to erase the preferences in the database in case the preference
2919 # is re-enabled again. So don't touch $mOptions, just override the returned value
2920 foreach ( $wgHiddenPrefs as $pref ) {
2921 $default = self
::getDefaultOption( $pref );
2922 if ( $default !== null ) {
2923 $options[$pref] = $default;
2927 if ( $flags & self
::GETOPTIONS_EXCLUDE_DEFAULTS
) {
2928 $options = array_diff_assoc( $options, self
::getDefaultOptions() );
2935 * Get the user's current setting for a given option, as a boolean value.
2937 * @param string $oname The option to check
2938 * @return bool User's current value for the option
2941 public function getBoolOption( $oname ) {
2942 return (bool)$this->getOption( $oname );
2946 * Get the user's current setting for a given option, as an integer value.
2948 * @param string $oname The option to check
2949 * @param int $defaultOverride A default value returned if the option does not exist
2950 * @return int User's current value for the option
2953 public function getIntOption( $oname, $defaultOverride = 0 ) {
2954 $val = $this->getOption( $oname );
2956 $val = $defaultOverride;
2958 return intval( $val );
2962 * Set the given option for a user.
2964 * You need to call saveSettings() to actually write to the database.
2966 * @param string $oname The option to set
2967 * @param mixed $val New value to set
2969 public function setOption( $oname, $val ) {
2970 $this->loadOptions();
2972 // Explicitly NULL values should refer to defaults
2973 if ( is_null( $val ) ) {
2974 $val = self
::getDefaultOption( $oname );
2977 $this->mOptions
[$oname] = $val;
2981 * Get a token stored in the preferences (like the watchlist one),
2982 * resetting it if it's empty (and saving changes).
2984 * @param string $oname The option name to retrieve the token from
2985 * @return string|bool User's current value for the option, or false if this option is disabled.
2986 * @see resetTokenFromOption()
2988 * @deprecated 1.26 Applications should use the OAuth extension
2990 public function getTokenFromOption( $oname ) {
2991 global $wgHiddenPrefs;
2993 $id = $this->getId();
2994 if ( !$id ||
in_array( $oname, $wgHiddenPrefs ) ) {
2998 $token = $this->getOption( $oname );
3000 // Default to a value based on the user token to avoid space
3001 // wasted on storing tokens for all users. When this option
3002 // is set manually by the user, only then is it stored.
3003 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
3010 * Reset a token stored in the preferences (like the watchlist one).
3011 * *Does not* save user's preferences (similarly to setOption()).
3013 * @param string $oname The option name to reset the token in
3014 * @return string|bool New token value, or false if this option is disabled.
3015 * @see getTokenFromOption()
3018 public function resetTokenFromOption( $oname ) {
3019 global $wgHiddenPrefs;
3020 if ( in_array( $oname, $wgHiddenPrefs ) ) {
3024 $token = MWCryptRand
::generateHex( 40 );
3025 $this->setOption( $oname, $token );
3030 * Return a list of the types of user options currently returned by
3031 * User::getOptionKinds().
3033 * Currently, the option kinds are:
3034 * - 'registered' - preferences which are registered in core MediaWiki or
3035 * by extensions using the UserGetDefaultOptions hook.
3036 * - 'registered-multiselect' - as above, using the 'multiselect' type.
3037 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
3038 * - 'userjs' - preferences with names starting with 'userjs-', intended to
3039 * be used by user scripts.
3040 * - 'special' - "preferences" that are not accessible via User::getOptions
3041 * or User::setOptions.
3042 * - 'unused' - preferences about which MediaWiki doesn't know anything.
3043 * These are usually legacy options, removed in newer versions.
3045 * The API (and possibly others) use this function to determine the possible
3046 * option types for validation purposes, so make sure to update this when a
3047 * new option kind is added.
3049 * @see User::getOptionKinds
3050 * @return array Option kinds
3052 public static function listOptionKinds() {
3055 'registered-multiselect',
3056 'registered-checkmatrix',
3064 * Return an associative array mapping preferences keys to the kind of a preference they're
3065 * used for. Different kinds are handled differently when setting or reading preferences.
3067 * See User::listOptionKinds for the list of valid option types that can be provided.
3069 * @see User::listOptionKinds
3070 * @param IContextSource $context
3071 * @param array $options Assoc. array with options keys to check as keys.
3072 * Defaults to $this->mOptions.
3073 * @return array The key => kind mapping data
3075 public function getOptionKinds( IContextSource
$context, $options = null ) {
3076 $this->loadOptions();
3077 if ( $options === null ) {
3078 $options = $this->mOptions
;
3081 $prefs = Preferences
::getPreferences( $this, $context );
3084 // Pull out the "special" options, so they don't get converted as
3085 // multiselect or checkmatrix.
3086 $specialOptions = array_fill_keys( Preferences
::getSaveBlacklist(), true );
3087 foreach ( $specialOptions as $name => $value ) {
3088 unset( $prefs[$name] );
3091 // Multiselect and checkmatrix options are stored in the database with
3092 // one key per option, each having a boolean value. Extract those keys.
3093 $multiselectOptions = [];
3094 foreach ( $prefs as $name => $info ) {
3095 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
3096 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
3097 $opts = HTMLFormField
::flattenOptions( $info['options'] );
3098 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
3100 foreach ( $opts as $value ) {
3101 $multiselectOptions["$prefix$value"] = true;
3104 unset( $prefs[$name] );
3107 $checkmatrixOptions = [];
3108 foreach ( $prefs as $name => $info ) {
3109 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
3110 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
3111 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
3112 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
3113 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
3115 foreach ( $columns as $column ) {
3116 foreach ( $rows as $row ) {
3117 $checkmatrixOptions["$prefix$column-$row"] = true;
3121 unset( $prefs[$name] );
3125 // $value is ignored
3126 foreach ( $options as $key => $value ) {
3127 if ( isset( $prefs[$key] ) ) {
3128 $mapping[$key] = 'registered';
3129 } elseif ( isset( $multiselectOptions[$key] ) ) {
3130 $mapping[$key] = 'registered-multiselect';
3131 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
3132 $mapping[$key] = 'registered-checkmatrix';
3133 } elseif ( isset( $specialOptions[$key] ) ) {
3134 $mapping[$key] = 'special';
3135 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
3136 $mapping[$key] = 'userjs';
3138 $mapping[$key] = 'unused';
3146 * Reset certain (or all) options to the site defaults
3148 * The optional parameter determines which kinds of preferences will be reset.
3149 * Supported values are everything that can be reported by getOptionKinds()
3150 * and 'all', which forces a reset of *all* preferences and overrides everything else.
3152 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
3153 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
3154 * for backwards-compatibility.
3155 * @param IContextSource|null $context Context source used when $resetKinds
3156 * does not contain 'all', passed to getOptionKinds().
3157 * Defaults to RequestContext::getMain() when null.
3159 public function resetOptions(
3160 $resetKinds = [ 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ],
3161 IContextSource
$context = null
3164 $defaultOptions = self
::getDefaultOptions();
3166 if ( !is_array( $resetKinds ) ) {
3167 $resetKinds = [ $resetKinds ];
3170 if ( in_array( 'all', $resetKinds ) ) {
3171 $newOptions = $defaultOptions;
3173 if ( $context === null ) {
3174 $context = RequestContext
::getMain();
3177 $optionKinds = $this->getOptionKinds( $context );
3178 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
3181 // Use default values for the options that should be deleted, and
3182 // copy old values for the ones that shouldn't.
3183 foreach ( $this->mOptions
as $key => $value ) {
3184 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
3185 if ( array_key_exists( $key, $defaultOptions ) ) {
3186 $newOptions[$key] = $defaultOptions[$key];
3189 $newOptions[$key] = $value;
3194 Hooks
::run( 'UserResetAllOptions', [ $this, &$newOptions, $this->mOptions
, $resetKinds ] );
3196 $this->mOptions
= $newOptions;
3197 $this->mOptionsLoaded
= true;
3201 * Get the user's preferred date format.
3202 * @return string User's preferred date format
3204 public function getDatePreference() {
3205 // Important migration for old data rows
3206 if ( is_null( $this->mDatePreference
) ) {
3208 $value = $this->getOption( 'date' );
3209 $map = $wgLang->getDatePreferenceMigrationMap();
3210 if ( isset( $map[$value] ) ) {
3211 $value = $map[$value];
3213 $this->mDatePreference
= $value;
3215 return $this->mDatePreference
;
3219 * Determine based on the wiki configuration and the user's options,
3220 * whether this user must be over HTTPS no matter what.
3224 public function requiresHTTPS() {
3225 global $wgSecureLogin;
3226 if ( !$wgSecureLogin ) {
3229 $https = $this->getBoolOption( 'prefershttps' );
3230 Hooks
::run( 'UserRequiresHTTPS', [ $this, &$https ] );
3232 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
3239 * Get the user preferred stub threshold
3243 public function getStubThreshold() {
3244 global $wgMaxArticleSize; # Maximum article size, in Kb
3245 $threshold = $this->getIntOption( 'stubthreshold' );
3246 if ( $threshold > $wgMaxArticleSize * 1024 ) {
3247 // If they have set an impossible value, disable the preference
3248 // so we can use the parser cache again.
3255 * Get the permissions this user has.
3256 * @return array Array of String permission names
3258 public function getRights() {
3259 if ( is_null( $this->mRights
) ) {
3260 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
3262 // Deny any rights denied by the user's session, unless this
3263 // endpoint has no sessions.
3264 if ( !defined( 'MW_NO_SESSION' ) ) {
3265 $allowedRights = $this->getRequest()->getSession()->getAllowedUserRights();
3266 if ( $allowedRights !== null ) {
3267 $this->mRights
= array_intersect( $this->mRights
, $allowedRights );
3271 Hooks
::run( 'UserGetRights', [ $this, &$this->mRights
] );
3272 // Force reindexation of rights when a hook has unset one of them
3273 $this->mRights
= array_values( array_unique( $this->mRights
) );
3275 return $this->mRights
;
3279 * Get the list of explicit group memberships this user has.
3280 * The implicit * and user groups are not included.
3281 * @return array Array of String internal group names
3283 public function getGroups() {
3285 $this->loadGroups();
3286 return $this->mGroups
;
3290 * Get the list of implicit group memberships this user has.
3291 * This includes all explicit groups, plus 'user' if logged in,
3292 * '*' for all accounts, and autopromoted groups
3293 * @param bool $recache Whether to avoid the cache
3294 * @return array Array of String internal group names
3296 public function getEffectiveGroups( $recache = false ) {
3297 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
3298 $this->mEffectiveGroups
= array_unique( array_merge(
3299 $this->getGroups(), // explicit groups
3300 $this->getAutomaticGroups( $recache ) // implicit groups
3302 // Hook for additional groups
3303 Hooks
::run( 'UserEffectiveGroups', [ &$this, &$this->mEffectiveGroups
] );
3304 // Force reindexation of groups when a hook has unset one of them
3305 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
3307 return $this->mEffectiveGroups
;
3311 * Get the list of implicit group memberships this user has.
3312 * This includes 'user' if logged in, '*' for all accounts,
3313 * and autopromoted groups
3314 * @param bool $recache Whether to avoid the cache
3315 * @return array Array of String internal group names
3317 public function getAutomaticGroups( $recache = false ) {
3318 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
3319 $this->mImplicitGroups
= [ '*' ];
3320 if ( $this->getId() ) {
3321 $this->mImplicitGroups
[] = 'user';
3323 $this->mImplicitGroups
= array_unique( array_merge(
3324 $this->mImplicitGroups
,
3325 Autopromote
::getAutopromoteGroups( $this )
3329 // Assure data consistency with rights/groups,
3330 // as getEffectiveGroups() depends on this function
3331 $this->mEffectiveGroups
= null;
3334 return $this->mImplicitGroups
;
3338 * Returns the groups the user has belonged to.
3340 * The user may still belong to the returned groups. Compare with getGroups().
3342 * The function will not return groups the user had belonged to before MW 1.17
3344 * @return array Names of the groups the user has belonged to.
3346 public function getFormerGroups() {
3349 if ( is_null( $this->mFormerGroups
) ) {
3350 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3351 ?
wfGetDB( DB_MASTER
)
3352 : wfGetDB( DB_SLAVE
);
3353 $res = $db->select( 'user_former_groups',
3355 [ 'ufg_user' => $this->mId
],
3357 $this->mFormerGroups
= [];
3358 foreach ( $res as $row ) {
3359 $this->mFormerGroups
[] = $row->ufg_group
;
3363 return $this->mFormerGroups
;
3367 * Get the user's edit count.
3368 * @return int|null Null for anonymous users
3370 public function getEditCount() {
3371 if ( !$this->getId() ) {
3375 if ( $this->mEditCount
=== null ) {
3376 /* Populate the count, if it has not been populated yet */
3377 $dbr = wfGetDB( DB_SLAVE
);
3378 // check if the user_editcount field has been initialized
3379 $count = $dbr->selectField(
3380 'user', 'user_editcount',
3381 [ 'user_id' => $this->mId
],
3385 if ( $count === null ) {
3386 // it has not been initialized. do so.
3387 $count = $this->initEditCount();
3389 $this->mEditCount
= $count;
3391 return (int)$this->mEditCount
;
3395 * Add the user to the given group.
3396 * This takes immediate effect.
3397 * @param string $group Name of the group to add
3400 public function addGroup( $group ) {
3403 if ( !Hooks
::run( 'UserAddGroup', [ $this, &$group ] ) ) {
3407 $dbw = wfGetDB( DB_MASTER
);
3408 if ( $this->getId() ) {
3409 $dbw->insert( 'user_groups',
3411 'ug_user' => $this->getId(),
3412 'ug_group' => $group,
3418 $this->loadGroups();
3419 $this->mGroups
[] = $group;
3420 // In case loadGroups was not called before, we now have the right twice.
3421 // Get rid of the duplicate.
3422 $this->mGroups
= array_unique( $this->mGroups
);
3424 // Refresh the groups caches, and clear the rights cache so it will be
3425 // refreshed on the next call to $this->getRights().
3426 $this->getEffectiveGroups( true );
3427 $this->mRights
= null;
3429 $this->invalidateCache();
3435 * Remove the user from the given group.
3436 * This takes immediate effect.
3437 * @param string $group Name of the group to remove
3440 public function removeGroup( $group ) {
3442 if ( !Hooks
::run( 'UserRemoveGroup', [ $this, &$group ] ) ) {
3446 $dbw = wfGetDB( DB_MASTER
);
3447 $dbw->delete( 'user_groups',
3449 'ug_user' => $this->getId(),
3450 'ug_group' => $group,
3453 // Remember that the user was in this group
3454 $dbw->insert( 'user_former_groups',
3456 'ufg_user' => $this->getId(),
3457 'ufg_group' => $group,
3463 $this->loadGroups();
3464 $this->mGroups
= array_diff( $this->mGroups
, [ $group ] );
3466 // Refresh the groups caches, and clear the rights cache so it will be
3467 // refreshed on the next call to $this->getRights().
3468 $this->getEffectiveGroups( true );
3469 $this->mRights
= null;
3471 $this->invalidateCache();
3477 * Get whether the user is logged in
3480 public function isLoggedIn() {
3481 return $this->getId() != 0;
3485 * Get whether the user is anonymous
3488 public function isAnon() {
3489 return !$this->isLoggedIn();
3493 * @return bool Whether this user is flagged as being a bot role account
3496 public function isBot() {
3497 if ( in_array( 'bot', $this->getGroups() ) && $this->isAllowed( 'bot' ) ) {
3502 Hooks
::run( "UserIsBot", [ $this, &$isBot ] );
3508 * Check if user is allowed to access a feature / make an action
3510 * @param string ... Permissions to test
3511 * @return bool True if user is allowed to perform *any* of the given actions
3513 public function isAllowedAny() {
3514 $permissions = func_get_args();
3515 foreach ( $permissions as $permission ) {
3516 if ( $this->isAllowed( $permission ) ) {
3525 * @param string ... Permissions to test
3526 * @return bool True if the user is allowed to perform *all* of the given actions
3528 public function isAllowedAll() {
3529 $permissions = func_get_args();
3530 foreach ( $permissions as $permission ) {
3531 if ( !$this->isAllowed( $permission ) ) {
3539 * Internal mechanics of testing a permission
3540 * @param string $action
3543 public function isAllowed( $action = '' ) {
3544 if ( $action === '' ) {
3545 return true; // In the spirit of DWIM
3547 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3548 // by misconfiguration: 0 == 'foo'
3549 return in_array( $action, $this->getRights(), true );
3553 * Check whether to enable recent changes patrol features for this user
3554 * @return bool True or false
3556 public function useRCPatrol() {
3557 global $wgUseRCPatrol;
3558 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3562 * Check whether to enable new pages patrol features for this user
3563 * @return bool True or false
3565 public function useNPPatrol() {
3566 global $wgUseRCPatrol, $wgUseNPPatrol;
3568 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3569 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3574 * Check whether to enable new files patrol features for this user
3575 * @return bool True or false
3577 public function useFilePatrol() {
3578 global $wgUseRCPatrol, $wgUseFilePatrol;
3580 ( $wgUseRCPatrol ||
$wgUseFilePatrol )
3581 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3586 * Get the WebRequest object to use with this object
3588 * @return WebRequest
3590 public function getRequest() {
3591 if ( $this->mRequest
) {
3592 return $this->mRequest
;
3600 * Check the watched status of an article.
3601 * @since 1.22 $checkRights parameter added
3602 * @param Title $title Title of the article to look at
3603 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3604 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3607 public function isWatched( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3608 if ( $title->isWatchable() && ( !$checkRights ||
$this->isAllowed( 'viewmywatchlist' ) ) ) {
3609 return MediaWikiServices
::getInstance()->getWatchedItemStore()->isWatched( $this, $title );
3616 * @since 1.22 $checkRights parameter added
3617 * @param Title $title Title of the article to look at
3618 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3619 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3621 public function addWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3622 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3623 MediaWikiServices
::getInstance()->getWatchedItemStore()->addWatchBatchForUser(
3625 [ $title->getSubjectPage(), $title->getTalkPage() ]
3628 $this->invalidateCache();
3632 * Stop watching an article.
3633 * @since 1.22 $checkRights parameter added
3634 * @param Title $title Title of the article to look at
3635 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3636 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3638 public function removeWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3639 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3640 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
3641 $store->removeWatch( $this, $title->getSubjectPage() );
3642 $store->removeWatch( $this, $title->getTalkPage() );
3644 $this->invalidateCache();
3648 * Clear the user's notification timestamp for the given title.
3649 * If e-notif e-mails are on, they will receive notification mails on
3650 * the next change of the page if it's watched etc.
3651 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3652 * @param Title $title Title of the article to look at
3653 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3655 public function clearNotification( &$title, $oldid = 0 ) {
3656 global $wgUseEnotif, $wgShowUpdatedMarker;
3658 // Do nothing if the database is locked to writes
3659 if ( wfReadOnly() ) {
3663 // Do nothing if not allowed to edit the watchlist
3664 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3668 // If we're working on user's talk page, we should update the talk page message indicator
3669 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3670 if ( !Hooks
::run( 'UserClearNewTalkNotification', [ &$this, $oldid ] ) ) {
3674 // Try to update the DB post-send and only if needed...
3675 DeferredUpdates
::addCallableUpdate( function() use ( $title, $oldid ) {
3676 if ( !$this->getNewtalk() ) {
3677 return; // no notifications to clear
3680 // Delete the last notifications (they stack up)
3681 $this->setNewtalk( false );
3683 // If there is a new, unseen, revision, use its timestamp
3685 ?
$title->getNextRevisionID( $oldid, Title
::GAID_FOR_UPDATE
)
3688 $this->setNewtalk( true, Revision
::newFromId( $nextid ) );
3693 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3697 if ( $this->isAnon() ) {
3698 // Nothing else to do...
3702 // Only update the timestamp if the page is being watched.
3703 // The query to find out if it is watched is cached both in memcached and per-invocation,
3704 // and when it does have to be executed, it can be on a slave
3705 // If this is the user's newtalk page, we always update the timestamp
3707 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3711 MediaWikiServices
::getInstance()->getWatchedItemStore()
3712 ->resetNotificationTimestamp( $this, $title, $force, $oldid );
3716 * Resets all of the given user's page-change notification timestamps.
3717 * If e-notif e-mails are on, they will receive notification mails on
3718 * the next change of any watched page.
3719 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3721 public function clearAllNotifications() {
3722 if ( wfReadOnly() ) {
3726 // Do nothing if not allowed to edit the watchlist
3727 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3731 global $wgUseEnotif, $wgShowUpdatedMarker;
3732 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3733 $this->setNewtalk( false );
3736 $id = $this->getId();
3738 $dbw = wfGetDB( DB_MASTER
);
3739 $dbw->update( 'watchlist',
3740 [ /* SET */ 'wl_notificationtimestamp' => null ],
3741 [ /* WHERE */ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ],
3744 // We also need to clear here the "you have new message" notification for the own user_talk page;
3745 // it's cleared one page view later in WikiPage::doViewUpdates().
3750 * Set a cookie on the user's client. Wrapper for
3751 * WebResponse::setCookie
3752 * @deprecated since 1.27
3753 * @param string $name Name of the cookie to set
3754 * @param string $value Value to set
3755 * @param int $exp Expiration time, as a UNIX time value;
3756 * if 0 or not specified, use the default $wgCookieExpiration
3757 * @param bool $secure
3758 * true: Force setting the secure attribute when setting the cookie
3759 * false: Force NOT setting the secure attribute when setting the cookie
3760 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3761 * @param array $params Array of options sent passed to WebResponse::setcookie()
3762 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3765 protected function setCookie(
3766 $name, $value, $exp = 0, $secure = null, $params = [], $request = null
3768 wfDeprecated( __METHOD__
, '1.27' );
3769 if ( $request === null ) {
3770 $request = $this->getRequest();
3772 $params['secure'] = $secure;
3773 $request->response()->setCookie( $name, $value, $exp, $params );
3777 * Clear a cookie on the user's client
3778 * @deprecated since 1.27
3779 * @param string $name Name of the cookie to clear
3780 * @param bool $secure
3781 * true: Force setting the secure attribute when setting the cookie
3782 * false: Force NOT setting the secure attribute when setting the cookie
3783 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3784 * @param array $params Array of options sent passed to WebResponse::setcookie()
3786 protected function clearCookie( $name, $secure = null, $params = [] ) {
3787 wfDeprecated( __METHOD__
, '1.27' );
3788 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3792 * Set an extended login cookie on the user's client. The expiry of the cookie
3793 * is controlled by the $wgExtendedLoginCookieExpiration configuration
3796 * @see User::setCookie
3798 * @deprecated since 1.27
3799 * @param string $name Name of the cookie to set
3800 * @param string $value Value to set
3801 * @param bool $secure
3802 * true: Force setting the secure attribute when setting the cookie
3803 * false: Force NOT setting the secure attribute when setting the cookie
3804 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3806 protected function setExtendedLoginCookie( $name, $value, $secure ) {
3807 global $wgExtendedLoginCookieExpiration, $wgCookieExpiration;
3809 wfDeprecated( __METHOD__
, '1.27' );
3812 $exp +
= $wgExtendedLoginCookieExpiration !== null
3813 ?
$wgExtendedLoginCookieExpiration
3814 : $wgCookieExpiration;
3816 $this->setCookie( $name, $value, $exp, $secure );
3820 * Persist this user's session (e.g. set cookies)
3822 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3824 * @param bool $secure Whether to force secure/insecure cookies or use default
3825 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3827 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3829 if ( 0 == $this->mId
) {
3833 $session = $this->getRequest()->getSession();
3834 if ( $request && $session->getRequest() !== $request ) {
3835 $session = $session->sessionWithRequest( $request );
3837 $delay = $session->delaySave();
3839 if ( !$session->getUser()->equals( $this ) ) {
3840 if ( !$session->canSetUser() ) {
3841 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3842 ->warning( __METHOD__
.
3843 ": Cannot save user \"$this\" to a user \"{$session->getUser()}\"'s immutable session"
3847 $session->setUser( $this );
3850 $session->setRememberUser( $rememberMe );
3851 if ( $secure !== null ) {
3852 $session->setForceHTTPS( $secure );
3855 $session->persist();
3857 ScopedCallback
::consume( $delay );
3861 * Log this user out.
3863 public function logout() {
3864 if ( Hooks
::run( 'UserLogout', [ &$this ] ) ) {
3870 * Clear the user's session, and reset the instance cache.
3873 public function doLogout() {
3874 $session = $this->getRequest()->getSession();
3875 if ( !$session->canSetUser() ) {
3876 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3877 ->warning( __METHOD__
. ": Cannot log out of an immutable session" );
3878 $error = 'immutable';
3879 } elseif ( !$session->getUser()->equals( $this ) ) {
3880 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3881 ->warning( __METHOD__
.
3882 ": Cannot log user \"$this\" out of a user \"{$session->getUser()}\"'s session"
3884 // But we still may as well make this user object anon
3885 $this->clearInstanceCache( 'defaults' );
3886 $error = 'wronguser';
3888 $this->clearInstanceCache( 'defaults' );
3889 $delay = $session->delaySave();
3890 $session->unpersist(); // Clear cookies (T127436)
3891 $session->setLoggedOutTimestamp( time() );
3892 $session->setUser( new User
);
3893 $session->set( 'wsUserID', 0 ); // Other code expects this
3894 ScopedCallback
::consume( $delay );
3897 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authmanager' )->info( 'Logout', [
3898 'event' => 'logout',
3899 'successful' => $error === false,
3900 'status' => $error ?
: 'success',
3905 * Save this user's settings into the database.
3906 * @todo Only rarely do all these fields need to be set!
3908 public function saveSettings() {
3909 if ( wfReadOnly() ) {
3910 // @TODO: caller should deal with this instead!
3911 // This should really just be an exception.
3912 MWExceptionHandler
::logException( new DBExpectedError(
3914 "Could not update user with ID '{$this->mId}'; DB is read-only."
3920 if ( 0 == $this->mId
) {
3924 // Get a new user_touched that is higher than the old one.
3925 // This will be used for a CAS check as a last-resort safety
3926 // check against race conditions and slave lag.
3927 $newTouched = $this->newTouchedTimestamp();
3929 $dbw = wfGetDB( DB_MASTER
);
3930 $dbw->update( 'user',
3932 'user_name' => $this->mName
,
3933 'user_real_name' => $this->mRealName
,
3934 'user_email' => $this->mEmail
,
3935 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3936 'user_touched' => $dbw->timestamp( $newTouched ),
3937 'user_token' => strval( $this->mToken
),
3938 'user_email_token' => $this->mEmailToken
,
3939 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
3940 ], $this->makeUpdateConditions( $dbw, [ /* WHERE */
3941 'user_id' => $this->mId
,
3945 if ( !$dbw->affectedRows() ) {
3946 // Maybe the problem was a missed cache update; clear it to be safe
3947 $this->clearSharedCache( 'refresh' );
3948 // User was changed in the meantime or loaded with stale data
3949 $from = ( $this->queryFlagsUsed
& self
::READ_LATEST
) ?
'master' : 'slave';
3950 throw new MWException(
3951 "CAS update failed on user_touched for user ID '{$this->mId}' (read from $from);" .
3952 " the version of the user to be saved is older than the current version."
3956 $this->mTouched
= $newTouched;
3957 $this->saveOptions();
3959 Hooks
::run( 'UserSaveSettings', [ $this ] );
3960 $this->clearSharedCache();
3961 $this->getUserPage()->invalidateCache();
3965 * If only this user's username is known, and it exists, return the user ID.
3967 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
3970 public function idForName( $flags = 0 ) {
3971 $s = trim( $this->getName() );
3976 $db = ( ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
)
3977 ?
wfGetDB( DB_MASTER
)
3978 : wfGetDB( DB_SLAVE
);
3980 $options = ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
)
3981 ?
[ 'LOCK IN SHARE MODE' ]
3984 $id = $db->selectField( 'user',
3985 'user_id', [ 'user_name' => $s ], __METHOD__
, $options );
3991 * Add a user to the database, return the user object
3993 * @param string $name Username to add
3994 * @param array $params Array of Strings Non-default parameters to save to
3995 * the database as user_* fields:
3996 * - email: The user's email address.
3997 * - email_authenticated: The email authentication timestamp.
3998 * - real_name: The user's real name.
3999 * - options: An associative array of non-default options.
4000 * - token: Random authentication token. Do not set.
4001 * - registration: Registration timestamp. Do not set.
4003 * @return User|null User object, or null if the username already exists.
4005 public static function createNew( $name, $params = [] ) {
4006 foreach ( [ 'password', 'newpassword', 'newpass_time', 'password_expires' ] as $field ) {
4007 if ( isset( $params[$field] ) ) {
4008 wfDeprecated( __METHOD__
. " with param '$field'", '1.27' );
4009 unset( $params[$field] );
4015 $user->setToken(); // init token
4016 if ( isset( $params['options'] ) ) {
4017 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
4018 unset( $params['options'] );
4020 $dbw = wfGetDB( DB_MASTER
);
4021 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
4023 $noPass = PasswordFactory
::newInvalidPassword()->toString();
4026 'user_id' => $seqVal,
4027 'user_name' => $name,
4028 'user_password' => $noPass,
4029 'user_newpassword' => $noPass,
4030 'user_email' => $user->mEmail
,
4031 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
4032 'user_real_name' => $user->mRealName
,
4033 'user_token' => strval( $user->mToken
),
4034 'user_registration' => $dbw->timestamp( $user->mRegistration
),
4035 'user_editcount' => 0,
4036 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
4038 foreach ( $params as $name => $value ) {
4039 $fields["user_$name"] = $value;
4041 $dbw->insert( 'user', $fields, __METHOD__
, [ 'IGNORE' ] );
4042 if ( $dbw->affectedRows() ) {
4043 $newUser = User
::newFromId( $dbw->insertId() );
4051 * Add this existing user object to the database. If the user already
4052 * exists, a fatal status object is returned, and the user object is
4053 * initialised with the data from the database.
4055 * Previously, this function generated a DB error due to a key conflict
4056 * if the user already existed. Many extension callers use this function
4057 * in code along the lines of:
4059 * $user = User::newFromName( $name );
4060 * if ( !$user->isLoggedIn() ) {
4061 * $user->addToDatabase();
4063 * // do something with $user...
4065 * However, this was vulnerable to a race condition (bug 16020). By
4066 * initialising the user object if the user exists, we aim to support this
4067 * calling sequence as far as possible.
4069 * Note that if the user exists, this function will acquire a write lock,
4070 * so it is still advisable to make the call conditional on isLoggedIn(),
4071 * and to commit the transaction after calling.
4073 * @throws MWException
4076 public function addToDatabase() {
4078 if ( !$this->mToken
) {
4079 $this->setToken(); // init token
4082 $this->mTouched
= $this->newTouchedTimestamp();
4084 $noPass = PasswordFactory
::newInvalidPassword()->toString();
4086 $dbw = wfGetDB( DB_MASTER
);
4087 $inWrite = $dbw->writesOrCallbacksPending();
4088 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
4089 $dbw->insert( 'user',
4091 'user_id' => $seqVal,
4092 'user_name' => $this->mName
,
4093 'user_password' => $noPass,
4094 'user_newpassword' => $noPass,
4095 'user_email' => $this->mEmail
,
4096 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
4097 'user_real_name' => $this->mRealName
,
4098 'user_token' => strval( $this->mToken
),
4099 'user_registration' => $dbw->timestamp( $this->mRegistration
),
4100 'user_editcount' => 0,
4101 'user_touched' => $dbw->timestamp( $this->mTouched
),
4105 if ( !$dbw->affectedRows() ) {
4106 // The queries below cannot happen in the same REPEATABLE-READ snapshot.
4107 // Handle this by COMMIT, if possible, or by LOCK IN SHARE MODE otherwise.
4109 // Can't commit due to pending writes that may need atomicity.
4110 // This may cause some lock contention unlike the case below.
4111 $options = [ 'LOCK IN SHARE MODE' ];
4112 $flags = self
::READ_LOCKING
;
4114 // Often, this case happens early in views before any writes when
4115 // using CentralAuth. It's should be OK to commit and break the snapshot.
4116 $dbw->commit( __METHOD__
, 'flush' );
4118 $flags = self
::READ_LATEST
;
4120 $this->mId
= $dbw->selectField( 'user', 'user_id',
4121 [ 'user_name' => $this->mName
], __METHOD__
, $options );
4124 if ( $this->loadFromDatabase( $flags ) ) {
4129 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
4130 "to insert user '{$this->mName}' row, but it was not present in select!" );
4132 return Status
::newFatal( 'userexists' );
4134 $this->mId
= $dbw->insertId();
4135 self
::$idCacheByName[$this->mName
] = $this->mId
;
4137 // Clear instance cache other than user table data, which is already accurate
4138 $this->clearInstanceCache();
4140 $this->saveOptions();
4141 return Status
::newGood();
4145 * If this user is logged-in and blocked,
4146 * block any IP address they've successfully logged in from.
4147 * @return bool A block was spread
4149 public function spreadAnyEditBlock() {
4150 if ( $this->isLoggedIn() && $this->isBlocked() ) {
4151 return $this->spreadBlock();
4158 * If this (non-anonymous) user is blocked,
4159 * block the IP address they've successfully logged in from.
4160 * @return bool A block was spread
4162 protected function spreadBlock() {
4163 wfDebug( __METHOD__
. "()\n" );
4165 if ( $this->mId
== 0 ) {
4169 $userblock = Block
::newFromTarget( $this->getName() );
4170 if ( !$userblock ) {
4174 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
4178 * Get whether the user is explicitly blocked from account creation.
4179 * @return bool|Block
4181 public function isBlockedFromCreateAccount() {
4182 $this->getBlockedStatus();
4183 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
4184 return $this->mBlock
;
4187 # bug 13611: if the IP address the user is trying to create an account from is
4188 # blocked with createaccount disabled, prevent new account creation there even
4189 # when the user is logged in
4190 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
4191 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
4193 return $this->mBlockedFromCreateAccount
instanceof Block
4194 && $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
4195 ?
$this->mBlockedFromCreateAccount
4200 * Get whether the user is blocked from using Special:Emailuser.
4203 public function isBlockedFromEmailuser() {
4204 $this->getBlockedStatus();
4205 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
4209 * Get whether the user is allowed to create an account.
4212 public function isAllowedToCreateAccount() {
4213 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
4217 * Get this user's personal page title.
4219 * @return Title User's personal page title
4221 public function getUserPage() {
4222 return Title
::makeTitle( NS_USER
, $this->getName() );
4226 * Get this user's talk page title.
4228 * @return Title User's talk page title
4230 public function getTalkPage() {
4231 $title = $this->getUserPage();
4232 return $title->getTalkPage();
4236 * Determine whether the user is a newbie. Newbies are either
4237 * anonymous IPs, or the most recently created accounts.
4240 public function isNewbie() {
4241 return !$this->isAllowed( 'autoconfirmed' );
4245 * Check to see if the given clear-text password is one of the accepted passwords
4246 * @deprecated since 1.27, use AuthManager instead
4247 * @param string $password User password
4248 * @return bool True if the given password is correct, otherwise False
4250 public function checkPassword( $password ) {
4251 global $wgAuth, $wgLegacyEncoding, $wgDisableAuthManager;
4253 if ( $wgDisableAuthManager ) {
4256 // Some passwords will give a fatal Status, which means there is
4257 // some sort of technical or security reason for this password to
4258 // be completely invalid and should never be checked (e.g., T64685)
4259 if ( !$this->checkPasswordValidity( $password )->isOK() ) {
4263 // Certain authentication plugins do NOT want to save
4264 // domain passwords in a mysql database, so we should
4265 // check this (in case $wgAuth->strict() is false).
4266 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
4268 } elseif ( $wgAuth->strict() ) {
4269 // Auth plugin doesn't allow local authentication
4271 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
4272 // Auth plugin doesn't allow local authentication for this user name
4276 $passwordFactory = new PasswordFactory();
4277 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4278 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
4279 ?
wfGetDB( DB_MASTER
)
4280 : wfGetDB( DB_SLAVE
);
4283 $mPassword = $passwordFactory->newFromCiphertext( $db->selectField(
4284 'user', 'user_password', [ 'user_id' => $this->getId() ], __METHOD__
4286 } catch ( PasswordError
$e ) {
4287 wfDebug( 'Invalid password hash found in database.' );
4288 $mPassword = PasswordFactory
::newInvalidPassword();
4291 if ( !$mPassword->equals( $password ) ) {
4292 if ( $wgLegacyEncoding ) {
4293 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
4294 // Check for this with iconv
4295 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
4296 if ( $cp1252Password === $password ||
!$mPassword->equals( $cp1252Password ) ) {
4304 if ( $passwordFactory->needsUpdate( $mPassword ) && !wfReadOnly() ) {
4305 $this->setPasswordInternal( $password );
4310 $manager = AuthManager
::singleton();
4311 $reqs = AuthenticationRequest
::loadRequestsFromSubmission(
4312 $manager->getAuthenticationRequests( AuthManager
::ACTION_LOGIN
),
4314 'username' => $this->getName(),
4315 'password' => $password,
4318 $res = AuthManager
::singleton()->beginAuthentication( $reqs, 'null:' );
4319 switch ( $res->status
) {
4320 case AuthenticationResponse
::PASS
:
4322 case AuthenticationResponse
::FAIL
:
4323 // Hope it's not a PreAuthenticationProvider that failed...
4324 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
4325 ->info( __METHOD__
. ': Authentication failed: ' . $res->message
->plain() );
4328 throw new BadMethodCallException(
4329 'AuthManager returned a response unsupported by ' . __METHOD__
4336 * Check if the given clear-text password matches the temporary password
4337 * sent by e-mail for password reset operations.
4339 * @deprecated since 1.27, use AuthManager instead
4340 * @param string $plaintext
4341 * @return bool True if matches, false otherwise
4343 public function checkTemporaryPassword( $plaintext ) {
4344 global $wgNewPasswordExpiry, $wgDisableAuthManager;
4346 if ( $wgDisableAuthManager ) {
4349 $passwordFactory = new PasswordFactory();
4350 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4351 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
4352 ?
wfGetDB( DB_MASTER
)
4353 : wfGetDB( DB_SLAVE
);
4355 $row = $db->selectRow(
4357 [ 'user_newpassword', 'user_newpass_time' ],
4358 [ 'user_id' => $this->getId() ],
4362 $newPassword = $passwordFactory->newFromCiphertext( $row->user_newpassword
);
4363 } catch ( PasswordError
$e ) {
4364 wfDebug( 'Invalid password hash found in database.' );
4365 $newPassword = PasswordFactory
::newInvalidPassword();
4368 if ( $newPassword->equals( $plaintext ) ) {
4369 if ( is_null( $row->user_newpass_time
) ) {
4372 $expiry = wfTimestamp( TS_UNIX
, $row->user_newpass_time
) +
$wgNewPasswordExpiry;
4373 return ( time() < $expiry );
4378 // Can't check the temporary password individually.
4379 return $this->checkPassword( $plaintext );
4384 * Initialize (if necessary) and return a session token value
4385 * which can be used in edit forms to show that the user's
4386 * login credentials aren't being hijacked with a foreign form
4390 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4391 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4392 * @return MediaWiki\Session\Token The new edit token
4394 public function getEditTokenObject( $salt = '', $request = null ) {
4395 if ( $this->isAnon() ) {
4396 return new LoggedOutEditToken();
4400 $request = $this->getRequest();
4402 return $request->getSession()->getToken( $salt );
4406 * Initialize (if necessary) and return a session token value
4407 * which can be used in edit forms to show that the user's
4408 * login credentials aren't being hijacked with a foreign form
4412 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4413 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4414 * @return string The new edit token
4416 public function getEditToken( $salt = '', $request = null ) {
4417 return $this->getEditTokenObject( $salt, $request )->toString();
4421 * Get the embedded timestamp from a token.
4422 * @deprecated since 1.27, use \MediaWiki\Session\Token::getTimestamp instead.
4423 * @param string $val Input token
4426 public static function getEditTokenTimestamp( $val ) {
4427 wfDeprecated( __METHOD__
, '1.27' );
4428 return MediaWiki\Session\Token
::getTimestamp( $val );
4432 * Check given value against the token value stored in the session.
4433 * A match should confirm that the form was submitted from the
4434 * user's own login session, not a form submission from a third-party
4437 * @param string $val Input value to compare
4438 * @param string $salt Optional function-specific data for hashing
4439 * @param WebRequest|null $request Object to use or null to use $wgRequest
4440 * @param int $maxage Fail tokens older than this, in seconds
4441 * @return bool Whether the token matches
4443 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4444 return $this->getEditTokenObject( $salt, $request )->match( $val, $maxage );
4448 * Check given value against the token value stored in the session,
4449 * ignoring the suffix.
4451 * @param string $val Input value to compare
4452 * @param string $salt Optional function-specific data for hashing
4453 * @param WebRequest|null $request Object to use or null to use $wgRequest
4454 * @param int $maxage Fail tokens older than this, in seconds
4455 * @return bool Whether the token matches
4457 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4458 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . Token
::SUFFIX
;
4459 return $this->matchEditToken( $val, $salt, $request, $maxage );
4463 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4464 * mail to the user's given address.
4466 * @param string $type Message to send, either "created", "changed" or "set"
4469 public function sendConfirmationMail( $type = 'created' ) {
4471 $expiration = null; // gets passed-by-ref and defined in next line.
4472 $token = $this->confirmationToken( $expiration );
4473 $url = $this->confirmationTokenUrl( $token );
4474 $invalidateURL = $this->invalidationTokenUrl( $token );
4475 $this->saveSettings();
4477 if ( $type == 'created' ||
$type === false ) {
4478 $message = 'confirmemail_body';
4479 } elseif ( $type === true ) {
4480 $message = 'confirmemail_body_changed';
4482 // Messages: confirmemail_body_changed, confirmemail_body_set
4483 $message = 'confirmemail_body_' . $type;
4486 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4487 wfMessage( $message,
4488 $this->getRequest()->getIP(),
4491 $wgLang->userTimeAndDate( $expiration, $this ),
4493 $wgLang->userDate( $expiration, $this ),
4494 $wgLang->userTime( $expiration, $this ) )->text() );
4498 * Send an e-mail to this user's account. Does not check for
4499 * confirmed status or validity.
4501 * @param string $subject Message subject
4502 * @param string $body Message body
4503 * @param User|null $from Optional sending user; if unspecified, default
4504 * $wgPasswordSender will be used.
4505 * @param string $replyto Reply-To address
4508 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4509 global $wgPasswordSender;
4511 if ( $from instanceof User
) {
4512 $sender = MailAddress
::newFromUser( $from );
4514 $sender = new MailAddress( $wgPasswordSender,
4515 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4517 $to = MailAddress
::newFromUser( $this );
4519 return UserMailer
::send( $to, $sender, $subject, $body, [
4520 'replyTo' => $replyto,
4525 * Generate, store, and return a new e-mail confirmation code.
4526 * A hash (unsalted, since it's used as a key) is stored.
4528 * @note Call saveSettings() after calling this function to commit
4529 * this change to the database.
4531 * @param string &$expiration Accepts the expiration time
4532 * @return string New token
4534 protected function confirmationToken( &$expiration ) {
4535 global $wgUserEmailConfirmationTokenExpiry;
4537 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4538 $expiration = wfTimestamp( TS_MW
, $expires );
4540 $token = MWCryptRand
::generateHex( 32 );
4541 $hash = md5( $token );
4542 $this->mEmailToken
= $hash;
4543 $this->mEmailTokenExpires
= $expiration;
4548 * Return a URL the user can use to confirm their email address.
4549 * @param string $token Accepts the email confirmation token
4550 * @return string New token URL
4552 protected function confirmationTokenUrl( $token ) {
4553 return $this->getTokenUrl( 'ConfirmEmail', $token );
4557 * Return a URL the user can use to invalidate their email address.
4558 * @param string $token Accepts the email confirmation token
4559 * @return string New token URL
4561 protected function invalidationTokenUrl( $token ) {
4562 return $this->getTokenUrl( 'InvalidateEmail', $token );
4566 * Internal function to format the e-mail validation/invalidation URLs.
4567 * This uses a quickie hack to use the
4568 * hardcoded English names of the Special: pages, for ASCII safety.
4570 * @note Since these URLs get dropped directly into emails, using the
4571 * short English names avoids insanely long URL-encoded links, which
4572 * also sometimes can get corrupted in some browsers/mailers
4573 * (bug 6957 with Gmail and Internet Explorer).
4575 * @param string $page Special page
4576 * @param string $token Token
4577 * @return string Formatted URL
4579 protected function getTokenUrl( $page, $token ) {
4580 // Hack to bypass localization of 'Special:'
4581 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4582 return $title->getCanonicalURL();
4586 * Mark the e-mail address confirmed.
4588 * @note Call saveSettings() after calling this function to commit the change.
4592 public function confirmEmail() {
4593 // Check if it's already confirmed, so we don't touch the database
4594 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4595 if ( !$this->isEmailConfirmed() ) {
4596 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4597 Hooks
::run( 'ConfirmEmailComplete', [ $this ] );
4603 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4604 * address if it was already confirmed.
4606 * @note Call saveSettings() after calling this function to commit the change.
4607 * @return bool Returns true
4609 public function invalidateEmail() {
4611 $this->mEmailToken
= null;
4612 $this->mEmailTokenExpires
= null;
4613 $this->setEmailAuthenticationTimestamp( null );
4615 Hooks
::run( 'InvalidateEmailComplete', [ $this ] );
4620 * Set the e-mail authentication timestamp.
4621 * @param string $timestamp TS_MW timestamp
4623 public function setEmailAuthenticationTimestamp( $timestamp ) {
4625 $this->mEmailAuthenticated
= $timestamp;
4626 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
4630 * Is this user allowed to send e-mails within limits of current
4631 * site configuration?
4634 public function canSendEmail() {
4635 global $wgEnableEmail, $wgEnableUserEmail;
4636 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4639 $canSend = $this->isEmailConfirmed();
4640 Hooks
::run( 'UserCanSendEmail', [ &$this, &$canSend ] );
4645 * Is this user allowed to receive e-mails within limits of current
4646 * site configuration?
4649 public function canReceiveEmail() {
4650 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4654 * Is this user's e-mail address valid-looking and confirmed within
4655 * limits of the current site configuration?
4657 * @note If $wgEmailAuthentication is on, this may require the user to have
4658 * confirmed their address by returning a code or using a password
4659 * sent to the address from the wiki.
4663 public function isEmailConfirmed() {
4664 global $wgEmailAuthentication;
4667 if ( Hooks
::run( 'EmailConfirmed', [ &$this, &$confirmed ] ) ) {
4668 if ( $this->isAnon() ) {
4671 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4674 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4684 * Check whether there is an outstanding request for e-mail confirmation.
4687 public function isEmailConfirmationPending() {
4688 global $wgEmailAuthentication;
4689 return $wgEmailAuthentication &&
4690 !$this->isEmailConfirmed() &&
4691 $this->mEmailToken
&&
4692 $this->mEmailTokenExpires
> wfTimestamp();
4696 * Get the timestamp of account creation.
4698 * @return string|bool|null Timestamp of account creation, false for
4699 * non-existent/anonymous user accounts, or null if existing account
4700 * but information is not in database.
4702 public function getRegistration() {
4703 if ( $this->isAnon() ) {
4707 return $this->mRegistration
;
4711 * Get the timestamp of the first edit
4713 * @return string|bool Timestamp of first edit, or false for
4714 * non-existent/anonymous user accounts.
4716 public function getFirstEditTimestamp() {
4717 if ( $this->getId() == 0 ) {
4718 return false; // anons
4720 $dbr = wfGetDB( DB_SLAVE
);
4721 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4722 [ 'rev_user' => $this->getId() ],
4724 [ 'ORDER BY' => 'rev_timestamp ASC' ]
4727 return false; // no edits
4729 return wfTimestamp( TS_MW
, $time );
4733 * Get the permissions associated with a given list of groups
4735 * @param array $groups Array of Strings List of internal group names
4736 * @return array Array of Strings List of permission key names for given groups combined
4738 public static function getGroupPermissions( $groups ) {
4739 global $wgGroupPermissions, $wgRevokePermissions;
4741 // grant every granted permission first
4742 foreach ( $groups as $group ) {
4743 if ( isset( $wgGroupPermissions[$group] ) ) {
4744 $rights = array_merge( $rights,
4745 // array_filter removes empty items
4746 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4749 // now revoke the revoked permissions
4750 foreach ( $groups as $group ) {
4751 if ( isset( $wgRevokePermissions[$group] ) ) {
4752 $rights = array_diff( $rights,
4753 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4756 return array_unique( $rights );
4760 * Get all the groups who have a given permission
4762 * @param string $role Role to check
4763 * @return array Array of Strings List of internal group names with the given permission
4765 public static function getGroupsWithPermission( $role ) {
4766 global $wgGroupPermissions;
4767 $allowedGroups = [];
4768 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4769 if ( self
::groupHasPermission( $group, $role ) ) {
4770 $allowedGroups[] = $group;
4773 return $allowedGroups;
4777 * Check, if the given group has the given permission
4779 * If you're wanting to check whether all users have a permission, use
4780 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4784 * @param string $group Group to check
4785 * @param string $role Role to check
4788 public static function groupHasPermission( $group, $role ) {
4789 global $wgGroupPermissions, $wgRevokePermissions;
4790 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4791 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4795 * Check if all users may be assumed to have the given permission
4797 * We generally assume so if the right is granted to '*' and isn't revoked
4798 * on any group. It doesn't attempt to take grants or other extension
4799 * limitations on rights into account in the general case, though, as that
4800 * would require it to always return false and defeat the purpose.
4801 * Specifically, session-based rights restrictions (such as OAuth or bot
4802 * passwords) are applied based on the current session.
4805 * @param string $right Right to check
4808 public static function isEveryoneAllowed( $right ) {
4809 global $wgGroupPermissions, $wgRevokePermissions;
4812 // Use the cached results, except in unit tests which rely on
4813 // being able change the permission mid-request
4814 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4815 return $cache[$right];
4818 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4819 $cache[$right] = false;
4823 // If it's revoked anywhere, then everyone doesn't have it
4824 foreach ( $wgRevokePermissions as $rights ) {
4825 if ( isset( $rights[$right] ) && $rights[$right] ) {
4826 $cache[$right] = false;
4831 // Remove any rights that aren't allowed to the global-session user,
4832 // unless there are no sessions for this endpoint.
4833 if ( !defined( 'MW_NO_SESSION' ) ) {
4834 $allowedRights = SessionManager
::getGlobalSession()->getAllowedUserRights();
4835 if ( $allowedRights !== null && !in_array( $right, $allowedRights, true ) ) {
4836 $cache[$right] = false;
4841 // Allow extensions to say false
4842 if ( !Hooks
::run( 'UserIsEveryoneAllowed', [ $right ] ) ) {
4843 $cache[$right] = false;
4847 $cache[$right] = true;
4852 * Get the localized descriptive name for a group, if it exists
4854 * @param string $group Internal group name
4855 * @return string Localized descriptive group name
4857 public static function getGroupName( $group ) {
4858 $msg = wfMessage( "group-$group" );
4859 return $msg->isBlank() ?
$group : $msg->text();
4863 * Get the localized descriptive name for a member of a group, if it exists
4865 * @param string $group Internal group name
4866 * @param string $username Username for gender (since 1.19)
4867 * @return string Localized name for group member
4869 public static function getGroupMember( $group, $username = '#' ) {
4870 $msg = wfMessage( "group-$group-member", $username );
4871 return $msg->isBlank() ?
$group : $msg->text();
4875 * Return the set of defined explicit groups.
4876 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4877 * are not included, as they are defined automatically, not in the database.
4878 * @return array Array of internal group names
4880 public static function getAllGroups() {
4881 global $wgGroupPermissions, $wgRevokePermissions;
4883 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4884 self
::getImplicitGroups()
4889 * Get a list of all available permissions.
4890 * @return string[] Array of permission names
4892 public static function getAllRights() {
4893 if ( self
::$mAllRights === false ) {
4894 global $wgAvailableRights;
4895 if ( count( $wgAvailableRights ) ) {
4896 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
4898 self
::$mAllRights = self
::$mCoreRights;
4900 Hooks
::run( 'UserGetAllRights', [ &self
::$mAllRights ] );
4902 return self
::$mAllRights;
4906 * Get a list of implicit groups
4907 * @return array Array of Strings Array of internal group names
4909 public static function getImplicitGroups() {
4910 global $wgImplicitGroups;
4912 $groups = $wgImplicitGroups;
4913 # Deprecated, use $wgImplicitGroups instead
4914 Hooks
::run( 'UserGetImplicitGroups', [ &$groups ], '1.25' );
4920 * Get the title of a page describing a particular group
4922 * @param string $group Internal group name
4923 * @return Title|bool Title of the page if it exists, false otherwise
4925 public static function getGroupPage( $group ) {
4926 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4927 if ( $msg->exists() ) {
4928 $title = Title
::newFromText( $msg->text() );
4929 if ( is_object( $title ) ) {
4937 * Create a link to the group in HTML, if available;
4938 * else return the group name.
4940 * @param string $group Internal name of the group
4941 * @param string $text The text of the link
4942 * @return string HTML link to the group
4944 public static function makeGroupLinkHTML( $group, $text = '' ) {
4945 if ( $text == '' ) {
4946 $text = self
::getGroupName( $group );
4948 $title = self
::getGroupPage( $group );
4950 return Linker
::link( $title, htmlspecialchars( $text ) );
4952 return htmlspecialchars( $text );
4957 * Create a link to the group in Wikitext, if available;
4958 * else return the group name.
4960 * @param string $group Internal name of the group
4961 * @param string $text The text of the link
4962 * @return string Wikilink to the group
4964 public static function makeGroupLinkWiki( $group, $text = '' ) {
4965 if ( $text == '' ) {
4966 $text = self
::getGroupName( $group );
4968 $title = self
::getGroupPage( $group );
4970 $page = $title->getFullText();
4971 return "[[$page|$text]]";
4978 * Returns an array of the groups that a particular group can add/remove.
4980 * @param string $group The group to check for whether it can add/remove
4981 * @return array Array( 'add' => array( addablegroups ),
4982 * 'remove' => array( removablegroups ),
4983 * 'add-self' => array( addablegroups to self),
4984 * 'remove-self' => array( removable groups from self) )
4986 public static function changeableByGroup( $group ) {
4987 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4996 if ( empty( $wgAddGroups[$group] ) ) {
4997 // Don't add anything to $groups
4998 } elseif ( $wgAddGroups[$group] === true ) {
4999 // You get everything
5000 $groups['add'] = self
::getAllGroups();
5001 } elseif ( is_array( $wgAddGroups[$group] ) ) {
5002 $groups['add'] = $wgAddGroups[$group];
5005 // Same thing for remove
5006 if ( empty( $wgRemoveGroups[$group] ) ) {
5008 } elseif ( $wgRemoveGroups[$group] === true ) {
5009 $groups['remove'] = self
::getAllGroups();
5010 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
5011 $groups['remove'] = $wgRemoveGroups[$group];
5014 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
5015 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
5016 foreach ( $wgGroupsAddToSelf as $key => $value ) {
5017 if ( is_int( $key ) ) {
5018 $wgGroupsAddToSelf['user'][] = $value;
5023 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
5024 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
5025 if ( is_int( $key ) ) {
5026 $wgGroupsRemoveFromSelf['user'][] = $value;
5031 // Now figure out what groups the user can add to him/herself
5032 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
5034 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
5035 // No idea WHY this would be used, but it's there
5036 $groups['add-self'] = User
::getAllGroups();
5037 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
5038 $groups['add-self'] = $wgGroupsAddToSelf[$group];
5041 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
5043 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
5044 $groups['remove-self'] = User
::getAllGroups();
5045 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
5046 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
5053 * Returns an array of groups that this user can add and remove
5054 * @return array Array( 'add' => array( addablegroups ),
5055 * 'remove' => array( removablegroups ),
5056 * 'add-self' => array( addablegroups to self),
5057 * 'remove-self' => array( removable groups from self) )
5059 public function changeableGroups() {
5060 if ( $this->isAllowed( 'userrights' ) ) {
5061 // This group gives the right to modify everything (reverse-
5062 // compatibility with old "userrights lets you change
5064 // Using array_merge to make the groups reindexed
5065 $all = array_merge( User
::getAllGroups() );
5074 // Okay, it's not so simple, we will have to go through the arrays
5081 $addergroups = $this->getEffectiveGroups();
5083 foreach ( $addergroups as $addergroup ) {
5084 $groups = array_merge_recursive(
5085 $groups, $this->changeableByGroup( $addergroup )
5087 $groups['add'] = array_unique( $groups['add'] );
5088 $groups['remove'] = array_unique( $groups['remove'] );
5089 $groups['add-self'] = array_unique( $groups['add-self'] );
5090 $groups['remove-self'] = array_unique( $groups['remove-self'] );
5096 * Deferred version of incEditCountImmediate()
5098 public function incEditCount() {
5099 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle( function() {
5100 $this->incEditCountImmediate();
5105 * Increment the user's edit-count field.
5106 * Will have no effect for anonymous users.
5109 public function incEditCountImmediate() {
5110 if ( $this->isAnon() ) {
5114 $dbw = wfGetDB( DB_MASTER
);
5115 // No rows will be "affected" if user_editcount is NULL
5118 [ 'user_editcount=user_editcount+1' ],
5119 [ 'user_id' => $this->getId(), 'user_editcount IS NOT NULL' ],
5122 // Lazy initialization check...
5123 if ( $dbw->affectedRows() == 0 ) {
5124 // Now here's a goddamn hack...
5125 $dbr = wfGetDB( DB_SLAVE
);
5126 if ( $dbr !== $dbw ) {
5127 // If we actually have a slave server, the count is
5128 // at least one behind because the current transaction
5129 // has not been committed and replicated.
5130 $this->initEditCount( 1 );
5132 // But if DB_SLAVE is selecting the master, then the
5133 // count we just read includes the revision that was
5134 // just added in the working transaction.
5135 $this->initEditCount();
5138 // Edit count in user cache too
5139 $this->invalidateCache();
5143 * Initialize user_editcount from data out of the revision table
5145 * @param int $add Edits to add to the count from the revision table
5146 * @return int Number of edits
5148 protected function initEditCount( $add = 0 ) {
5149 // Pull from a slave to be less cruel to servers
5150 // Accuracy isn't the point anyway here
5151 $dbr = wfGetDB( DB_SLAVE
);
5152 $count = (int)$dbr->selectField(
5155 [ 'rev_user' => $this->getId() ],
5158 $count = $count +
$add;
5160 $dbw = wfGetDB( DB_MASTER
);
5163 [ 'user_editcount' => $count ],
5164 [ 'user_id' => $this->getId() ],
5172 * Get the description of a given right
5174 * @param string $right Right to query
5175 * @return string Localized description of the right
5177 public static function getRightDescription( $right ) {
5178 $key = "right-$right";
5179 $msg = wfMessage( $key );
5180 return $msg->isBlank() ?
$right : $msg->text();
5184 * Make a new-style password hash
5186 * @param string $password Plain-text password
5187 * @param bool|string $salt Optional salt, may be random or the user ID.
5188 * If unspecified or false, will generate one automatically
5189 * @return string Password hash
5190 * @deprecated since 1.24, use Password class
5192 public static function crypt( $password, $salt = false ) {
5193 wfDeprecated( __METHOD__
, '1.24' );
5194 $passwordFactory = new PasswordFactory();
5195 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
5196 $hash = $passwordFactory->newFromPlaintext( $password );
5197 return $hash->toString();
5201 * Compare a password hash with a plain-text password. Requires the user
5202 * ID if there's a chance that the hash is an old-style hash.
5204 * @param string $hash Password hash
5205 * @param string $password Plain-text password to compare
5206 * @param string|bool $userId User ID for old-style password salt
5209 * @deprecated since 1.24, use Password class
5211 public static function comparePasswords( $hash, $password, $userId = false ) {
5212 wfDeprecated( __METHOD__
, '1.24' );
5214 // Check for *really* old password hashes that don't even have a type
5215 // The old hash format was just an md5 hex hash, with no type information
5216 if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) {
5217 global $wgPasswordSalt;
5218 if ( $wgPasswordSalt ) {
5219 $password = ":B:{$userId}:{$hash}";
5221 $password = ":A:{$hash}";
5225 $passwordFactory = new PasswordFactory();
5226 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
5227 $hash = $passwordFactory->newFromCiphertext( $hash );
5228 return $hash->equals( $password );
5232 * Add a newuser log entry for this user.
5233 * Before 1.19 the return value was always true.
5235 * @deprecated since 1.27, AuthManager handles logging
5236 * @param string|bool $action Account creation type.
5237 * - String, one of the following values:
5238 * - 'create' for an anonymous user creating an account for himself.
5239 * This will force the action's performer to be the created user itself,
5240 * no matter the value of $wgUser
5241 * - 'create2' for a logged in user creating an account for someone else
5242 * - 'byemail' when the created user will receive its password by e-mail
5243 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
5244 * - Boolean means whether the account was created by e-mail (deprecated):
5245 * - true will be converted to 'byemail'
5246 * - false will be converted to 'create' if this object is the same as
5247 * $wgUser and to 'create2' otherwise
5248 * @param string $reason User supplied reason
5249 * @return int|bool True if not $wgNewUserLog or not $wgDisableAuthManager;
5250 * otherwise ID of log item or 0 on failure
5252 public function addNewUserLogEntry( $action = false, $reason = '' ) {
5253 global $wgUser, $wgNewUserLog, $wgDisableAuthManager;
5254 if ( !$wgDisableAuthManager ||
empty( $wgNewUserLog ) ) {
5255 return true; // disabled
5258 if ( $action === true ) {
5259 $action = 'byemail';
5260 } elseif ( $action === false ) {
5261 if ( $this->equals( $wgUser ) ) {
5264 $action = 'create2';
5268 if ( $action === 'create' ||
$action === 'autocreate' ) {
5271 $performer = $wgUser;
5274 $logEntry = new ManualLogEntry( 'newusers', $action );
5275 $logEntry->setPerformer( $performer );
5276 $logEntry->setTarget( $this->getUserPage() );
5277 $logEntry->setComment( $reason );
5278 $logEntry->setParameters( [
5279 '4::userid' => $this->getId(),
5281 $logid = $logEntry->insert();
5283 if ( $action !== 'autocreate' ) {
5284 $logEntry->publish( $logid );
5291 * Add an autocreate newuser log entry for this user
5292 * Used by things like CentralAuth and perhaps other authplugins.
5293 * Consider calling addNewUserLogEntry() directly instead.
5295 * @deprecated since 1.27, AuthManager handles logging
5298 public function addNewUserLogEntryAutoCreate() {
5299 $this->addNewUserLogEntry( 'autocreate' );
5305 * Load the user options either from cache, the database or an array
5307 * @param array $data Rows for the current user out of the user_properties table
5309 protected function loadOptions( $data = null ) {
5314 if ( $this->mOptionsLoaded
) {
5318 $this->mOptions
= self
::getDefaultOptions();
5320 if ( !$this->getId() ) {
5321 // For unlogged-in users, load language/variant options from request.
5322 // There's no need to do it for logged-in users: they can set preferences,
5323 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5324 // so don't override user's choice (especially when the user chooses site default).
5325 $variant = $wgContLang->getDefaultVariant();
5326 $this->mOptions
['variant'] = $variant;
5327 $this->mOptions
['language'] = $variant;
5328 $this->mOptionsLoaded
= true;
5332 // Maybe load from the object
5333 if ( !is_null( $this->mOptionOverrides
) ) {
5334 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5335 foreach ( $this->mOptionOverrides
as $key => $value ) {
5336 $this->mOptions
[$key] = $value;
5339 if ( !is_array( $data ) ) {
5340 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5341 // Load from database
5342 $dbr = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
5343 ?
wfGetDB( DB_MASTER
)
5344 : wfGetDB( DB_SLAVE
);
5346 $res = $dbr->select(
5348 [ 'up_property', 'up_value' ],
5349 [ 'up_user' => $this->getId() ],
5353 $this->mOptionOverrides
= [];
5355 foreach ( $res as $row ) {
5356 $data[$row->up_property
] = $row->up_value
;
5359 foreach ( $data as $property => $value ) {
5360 $this->mOptionOverrides
[$property] = $value;
5361 $this->mOptions
[$property] = $value;
5365 $this->mOptionsLoaded
= true;
5367 Hooks
::run( 'UserLoadOptions', [ $this, &$this->mOptions
] );
5371 * Saves the non-default options for this user, as previously set e.g. via
5372 * setOption(), in the database's "user_properties" (preferences) table.
5373 * Usually used via saveSettings().
5375 protected function saveOptions() {
5376 $this->loadOptions();
5378 // Not using getOptions(), to keep hidden preferences in database
5379 $saveOptions = $this->mOptions
;
5381 // Allow hooks to abort, for instance to save to a global profile.
5382 // Reset options to default state before saving.
5383 if ( !Hooks
::run( 'UserSaveOptions', [ $this, &$saveOptions ] ) ) {
5387 $userId = $this->getId();
5389 $insert_rows = []; // all the new preference rows
5390 foreach ( $saveOptions as $key => $value ) {
5391 // Don't bother storing default values
5392 $defaultOption = self
::getDefaultOption( $key );
5393 if ( ( $defaultOption === null && $value !== false && $value !== null )
5394 ||
$value != $defaultOption
5397 'up_user' => $userId,
5398 'up_property' => $key,
5399 'up_value' => $value,
5404 $dbw = wfGetDB( DB_MASTER
);
5406 $res = $dbw->select( 'user_properties',
5407 [ 'up_property', 'up_value' ], [ 'up_user' => $userId ], __METHOD__
);
5409 // Find prior rows that need to be removed or updated. These rows will
5410 // all be deleted (the later so that INSERT IGNORE applies the new values).
5412 foreach ( $res as $row ) {
5413 if ( !isset( $saveOptions[$row->up_property
] )
5414 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
5416 $keysDelete[] = $row->up_property
;
5420 if ( count( $keysDelete ) ) {
5421 // Do the DELETE by PRIMARY KEY for prior rows.
5422 // In the past a very large portion of calls to this function are for setting
5423 // 'rememberpassword' for new accounts (a preference that has since been removed).
5424 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5425 // caused gap locks on [max user ID,+infinity) which caused high contention since
5426 // updates would pile up on each other as they are for higher (newer) user IDs.
5427 // It might not be necessary these days, but it shouldn't hurt either.
5428 $dbw->delete( 'user_properties',
5429 [ 'up_user' => $userId, 'up_property' => $keysDelete ], __METHOD__
);
5431 // Insert the new preference rows
5432 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, [ 'IGNORE' ] );
5436 * Lazily instantiate and return a factory object for making passwords
5438 * @deprecated since 1.27, create a PasswordFactory directly instead
5439 * @return PasswordFactory
5441 public static function getPasswordFactory() {
5442 wfDeprecated( __METHOD__
, '1.27' );
5443 $ret = new PasswordFactory();
5444 $ret->init( RequestContext
::getMain()->getConfig() );
5449 * Provide an array of HTML5 attributes to put on an input element
5450 * intended for the user to enter a new password. This may include
5451 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
5453 * Do *not* use this when asking the user to enter his current password!
5454 * Regardless of configuration, users may have invalid passwords for whatever
5455 * reason (e.g., they were set before requirements were tightened up).
5456 * Only use it when asking for a new password, like on account creation or
5459 * Obviously, you still need to do server-side checking.
5461 * NOTE: A combination of bugs in various browsers means that this function
5462 * actually just returns array() unconditionally at the moment. May as
5463 * well keep it around for when the browser bugs get fixed, though.
5465 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
5467 * @deprecated since 1.27
5468 * @return array Array of HTML attributes suitable for feeding to
5469 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
5470 * That will get confused by the boolean attribute syntax used.)
5472 public static function passwordChangeInputAttribs() {
5473 global $wgMinimalPasswordLength;
5475 if ( $wgMinimalPasswordLength == 0 ) {
5479 # Note that the pattern requirement will always be satisfied if the
5480 # input is empty, so we need required in all cases.
5482 # @todo FIXME: Bug 23769: This needs to not claim the password is required
5483 # if e-mail confirmation is being used. Since HTML5 input validation
5484 # is b0rked anyway in some browsers, just return nothing. When it's
5485 # re-enabled, fix this code to not output required for e-mail
5487 # $ret = array( 'required' );
5490 # We can't actually do this right now, because Opera 9.6 will print out
5491 # the entered password visibly in its error message! When other
5492 # browsers add support for this attribute, or Opera fixes its support,
5493 # we can add support with a version check to avoid doing this on Opera
5494 # versions where it will be a problem. Reported to Opera as
5495 # DSK-262266, but they don't have a public bug tracker for us to follow.
5497 if ( $wgMinimalPasswordLength > 1 ) {
5498 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
5499 $ret['title'] = wfMessage( 'passwordtooshort' )
5500 ->numParams( $wgMinimalPasswordLength )->text();
5508 * Return the list of user fields that should be selected to create
5509 * a new user object.
5512 public static function selectFields() {
5520 'user_email_authenticated',
5522 'user_email_token_expires',
5523 'user_registration',
5529 * Factory function for fatal permission-denied errors
5532 * @param string $permission User right required
5535 static function newFatalPermissionDeniedStatus( $permission ) {
5538 $groups = array_map(
5539 [ 'User', 'makeGroupLinkWiki' ],
5540 User
::getGroupsWithPermission( $permission )
5544 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5546 return Status
::newFatal( 'badaccess-group0' );
5551 * Get a new instance of this user that was loaded from the master via a locking read
5553 * Use this instead of the main context User when updating that user. This avoids races
5554 * where that user was loaded from a slave or even the master but without proper locks.
5556 * @return User|null Returns null if the user was not found in the DB
5559 public function getInstanceForUpdate() {
5560 if ( !$this->getId() ) {
5561 return null; // anon
5564 $user = self
::newFromId( $this->getId() );
5565 if ( !$user->loadFromId( self
::READ_EXCLUSIVE
) ) {
5573 * Checks if two user objects point to the same user.
5579 public function equals( User
$user ) {
5580 return $this->getName() === $user->getName();