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 * Bump user_touched if it didn't change since this object was loaded
1473 * On success, the mTouched field is updated.
1474 * The user serialization cache is always cleared.
1476 * @return bool Whether user_touched was actually updated
1479 protected function checkAndSetTouched() {
1482 if ( !$this->mId
) {
1483 return false; // anon
1486 // Get a new user_touched that is higher than the old one
1487 $oldTouched = $this->mTouched
;
1488 $newTouched = $this->newTouchedTimestamp();
1490 $dbw = wfGetDB( DB_MASTER
);
1491 $dbw->update( 'user',
1492 [ 'user_touched' => $dbw->timestamp( $newTouched ) ],
1494 'user_id' => $this->mId
,
1495 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
1499 $success = ( $dbw->affectedRows() > 0 );
1502 $this->mTouched
= $newTouched;
1503 $this->clearSharedCache();
1505 // Clears on failure too since that is desired if the cache is stale
1506 $this->clearSharedCache( 'refresh' );
1513 * Clear various cached data stored in this object. The cache of the user table
1514 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1516 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1517 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1519 public function clearInstanceCache( $reloadFrom = false ) {
1520 $this->mNewtalk
= -1;
1521 $this->mDatePreference
= null;
1522 $this->mBlockedby
= -1; # Unset
1523 $this->mHash
= false;
1524 $this->mRights
= null;
1525 $this->mEffectiveGroups
= null;
1526 $this->mImplicitGroups
= null;
1527 $this->mGroups
= null;
1528 $this->mOptions
= null;
1529 $this->mOptionsLoaded
= false;
1530 $this->mEditCount
= null;
1532 if ( $reloadFrom ) {
1533 $this->mLoadedItems
= [];
1534 $this->mFrom
= $reloadFrom;
1539 * Combine the language default options with any site-specific options
1540 * and add the default language variants.
1542 * @return array Array of String options
1544 public static function getDefaultOptions() {
1545 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1547 static $defOpt = null;
1548 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1549 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1550 // mid-request and see that change reflected in the return value of this function.
1551 // Which is insane and would never happen during normal MW operation
1555 $defOpt = $wgDefaultUserOptions;
1556 // Default language setting
1557 $defOpt['language'] = $wgContLang->getCode();
1558 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1559 $defOpt[$langCode == $wgContLang->getCode() ?
'variant' : "variant-$langCode"] = $langCode;
1561 $namespaces = MediaWikiServices
::getInstance()->getSearchEngineConfig()->searchableNamespaces();
1562 foreach ( $namespaces as $nsnum => $nsname ) {
1563 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1565 $defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1567 Hooks
::run( 'UserGetDefaultOptions', [ &$defOpt ] );
1573 * Get a given default option value.
1575 * @param string $opt Name of option to retrieve
1576 * @return string Default option value
1578 public static function getDefaultOption( $opt ) {
1579 $defOpts = self
::getDefaultOptions();
1580 if ( isset( $defOpts[$opt] ) ) {
1581 return $defOpts[$opt];
1588 * Get blocking information
1589 * @param bool $bFromSlave Whether to check the slave database first.
1590 * To improve performance, non-critical checks are done against slaves.
1591 * Check when actually saving should be done against master.
1593 private function getBlockedStatus( $bFromSlave = true ) {
1594 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1596 if ( -1 != $this->mBlockedby
) {
1600 wfDebug( __METHOD__
. ": checking...\n" );
1602 // Initialize data...
1603 // Otherwise something ends up stomping on $this->mBlockedby when
1604 // things get lazy-loaded later, causing false positive block hits
1605 // due to -1 !== 0. Probably session-related... Nothing should be
1606 // overwriting mBlockedby, surely?
1609 # We only need to worry about passing the IP address to the Block generator if the
1610 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1611 # know which IP address they're actually coming from
1613 if ( !$this->isAllowed( 'ipblock-exempt' ) ) {
1614 // $wgUser->getName() only works after the end of Setup.php. Until
1615 // then, assume it's a logged-out user.
1616 $globalUserName = $wgUser->isSafeToLoad()
1617 ?
$wgUser->getName()
1618 : IP
::sanitizeIP( $wgUser->getRequest()->getIP() );
1619 if ( $this->getName() === $globalUserName ) {
1620 $ip = $this->getRequest()->getIP();
1625 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1628 if ( !$block instanceof Block
&& $ip !== null && !in_array( $ip, $wgProxyWhitelist ) ) {
1630 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1632 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1633 $block->mReason
= wfMessage( 'proxyblockreason' )->text();
1634 $block->setTarget( $ip );
1635 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1637 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1638 $block->mReason
= wfMessage( 'sorbsreason' )->text();
1639 $block->setTarget( $ip );
1643 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1644 if ( !$block instanceof Block
1645 && $wgApplyIpBlocksToXff
1647 && !in_array( $ip, $wgProxyWhitelist )
1649 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1650 $xff = array_map( 'trim', explode( ',', $xff ) );
1651 $xff = array_diff( $xff, [ $ip ] );
1652 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1653 $block = Block
::chooseBlock( $xffblocks, $xff );
1654 if ( $block instanceof Block
) {
1655 # Mangle the reason to alert the user that the block
1656 # originated from matching the X-Forwarded-For header.
1657 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->text();
1661 if ( $block instanceof Block
) {
1662 wfDebug( __METHOD__
. ": Found block.\n" );
1663 $this->mBlock
= $block;
1664 $this->mBlockedby
= $block->getByName();
1665 $this->mBlockreason
= $block->mReason
;
1666 $this->mHideName
= $block->mHideName
;
1667 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1669 $this->mBlockedby
= '';
1670 $this->mHideName
= 0;
1671 $this->mAllowUsertalk
= false;
1675 Hooks
::run( 'GetBlockedStatus', [ &$this ] );
1680 * Whether the given IP is in a DNS blacklist.
1682 * @param string $ip IP to check
1683 * @param bool $checkWhitelist Whether to check the whitelist first
1684 * @return bool True if blacklisted.
1686 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1687 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1689 if ( !$wgEnableDnsBlacklist ) {
1693 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1697 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1701 * Whether the given IP is in a given DNS blacklist.
1703 * @param string $ip IP to check
1704 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1705 * @return bool True if blacklisted.
1707 public function inDnsBlacklist( $ip, $bases ) {
1710 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1711 if ( IP
::isIPv4( $ip ) ) {
1712 // Reverse IP, bug 21255
1713 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1715 foreach ( (array)$bases as $base ) {
1717 // If we have an access key, use that too (ProjectHoneypot, etc.)
1719 if ( is_array( $base ) ) {
1720 if ( count( $base ) >= 2 ) {
1721 // Access key is 1, base URL is 0
1722 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1724 $host = "$ipReversed.{$base[0]}";
1726 $basename = $base[0];
1728 $host = "$ipReversed.$base";
1732 $ipList = gethostbynamel( $host );
1735 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
1739 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
1748 * Check if an IP address is in the local proxy list
1754 public static function isLocallyBlockedProxy( $ip ) {
1755 global $wgProxyList;
1757 if ( !$wgProxyList ) {
1761 if ( !is_array( $wgProxyList ) ) {
1762 // Load from the specified file
1763 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1766 if ( !is_array( $wgProxyList ) ) {
1768 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1770 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1771 // Old-style flipped proxy list
1780 * Is this user subject to rate limiting?
1782 * @return bool True if rate limited
1784 public function isPingLimitable() {
1785 global $wgRateLimitsExcludedIPs;
1786 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1787 // No other good way currently to disable rate limits
1788 // for specific IPs. :P
1789 // But this is a crappy hack and should die.
1792 return !$this->isAllowed( 'noratelimit' );
1796 * Primitive rate limits: enforce maximum actions per time period
1797 * to put a brake on flooding.
1799 * The method generates both a generic profiling point and a per action one
1800 * (suffix being "-$action".
1802 * @note When using a shared cache like memcached, IP-address
1803 * last-hit counters will be shared across wikis.
1805 * @param string $action Action to enforce; 'edit' if unspecified
1806 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1807 * @return bool True if a rate limiter was tripped
1809 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1810 // Call the 'PingLimiter' hook
1812 if ( !Hooks
::run( 'PingLimiter', [ &$this, $action, &$result, $incrBy ] ) ) {
1816 global $wgRateLimits;
1817 if ( !isset( $wgRateLimits[$action] ) ) {
1821 // Some groups shouldn't trigger the ping limiter, ever
1822 if ( !$this->isPingLimitable() ) {
1826 $limits = $wgRateLimits[$action];
1828 $id = $this->getId();
1830 $isNewbie = $this->isNewbie();
1834 if ( isset( $limits['anon'] ) ) {
1835 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1838 // limits for logged-in users
1839 if ( isset( $limits['user'] ) ) {
1840 $userLimit = $limits['user'];
1842 // limits for newbie logged-in users
1843 if ( $isNewbie && isset( $limits['newbie'] ) ) {
1844 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1848 // limits for anons and for newbie logged-in users
1851 if ( isset( $limits['ip'] ) ) {
1852 $ip = $this->getRequest()->getIP();
1853 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1855 // subnet-based limits
1856 if ( isset( $limits['subnet'] ) ) {
1857 $ip = $this->getRequest()->getIP();
1858 $subnet = IP
::getSubnet( $ip );
1859 if ( $subnet !== false ) {
1860 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1865 // Check for group-specific permissions
1866 // If more than one group applies, use the group with the highest limit ratio (max/period)
1867 foreach ( $this->getGroups() as $group ) {
1868 if ( isset( $limits[$group] ) ) {
1869 if ( $userLimit === false
1870 ||
$limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1872 $userLimit = $limits[$group];
1877 // Set the user limit key
1878 if ( $userLimit !== false ) {
1879 list( $max, $period ) = $userLimit;
1880 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
1881 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1884 // ip-based limits for all ping-limitable users
1885 if ( isset( $limits['ip-all'] ) ) {
1886 $ip = $this->getRequest()->getIP();
1887 // ignore if user limit is more permissive
1888 if ( $isNewbie ||
$userLimit === false
1889 ||
$limits['ip-all'][0] / $limits['ip-all'][1] > $userLimit[0] / $userLimit[1] ) {
1890 $keys["mediawiki:limiter:$action:ip-all:$ip"] = $limits['ip-all'];
1894 // subnet-based limits for all ping-limitable users
1895 if ( isset( $limits['subnet-all'] ) ) {
1896 $ip = $this->getRequest()->getIP();
1897 $subnet = IP
::getSubnet( $ip );
1898 if ( $subnet !== false ) {
1899 // ignore if user limit is more permissive
1900 if ( $isNewbie ||
$userLimit === false
1901 ||
$limits['ip-all'][0] / $limits['ip-all'][1]
1902 > $userLimit[0] / $userLimit[1] ) {
1903 $keys["mediawiki:limiter:$action:subnet-all:$subnet"] = $limits['subnet-all'];
1908 $cache = ObjectCache
::getLocalClusterInstance();
1911 foreach ( $keys as $key => $limit ) {
1912 list( $max, $period ) = $limit;
1913 $summary = "(limit $max in {$period}s)";
1914 $count = $cache->get( $key );
1917 if ( $count >= $max ) {
1918 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1919 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1922 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1925 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1926 if ( $incrBy > 0 ) {
1927 $cache->add( $key, 0, intval( $period ) ); // first ping
1930 if ( $incrBy > 0 ) {
1931 $cache->incr( $key, $incrBy );
1939 * Check if user is blocked
1941 * @param bool $bFromSlave Whether to check the slave database instead of
1942 * the master. Hacked from false due to horrible probs on site.
1943 * @return bool True if blocked, false otherwise
1945 public function isBlocked( $bFromSlave = true ) {
1946 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
1950 * Get the block affecting the user, or null if the user is not blocked
1952 * @param bool $bFromSlave Whether to check the slave database instead of the master
1953 * @return Block|null
1955 public function getBlock( $bFromSlave = true ) {
1956 $this->getBlockedStatus( $bFromSlave );
1957 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
1961 * Check if user is blocked from editing a particular article
1963 * @param Title $title Title to check
1964 * @param bool $bFromSlave Whether to check the slave database instead of the master
1967 public function isBlockedFrom( $title, $bFromSlave = false ) {
1968 global $wgBlockAllowsUTEdit;
1970 $blocked = $this->isBlocked( $bFromSlave );
1971 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
1972 // If a user's name is suppressed, they cannot make edits anywhere
1973 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName()
1974 && $title->getNamespace() == NS_USER_TALK
) {
1976 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
1979 Hooks
::run( 'UserIsBlockedFrom', [ $this, $title, &$blocked, &$allowUsertalk ] );
1985 * If user is blocked, return the name of the user who placed the block
1986 * @return string Name of blocker
1988 public function blockedBy() {
1989 $this->getBlockedStatus();
1990 return $this->mBlockedby
;
1994 * If user is blocked, return the specified reason for the block
1995 * @return string Blocking reason
1997 public function blockedFor() {
1998 $this->getBlockedStatus();
1999 return $this->mBlockreason
;
2003 * If user is blocked, return the ID for the block
2004 * @return int Block ID
2006 public function getBlockId() {
2007 $this->getBlockedStatus();
2008 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
2012 * Check if user is blocked on all wikis.
2013 * Do not use for actual edit permission checks!
2014 * This is intended for quick UI checks.
2016 * @param string $ip IP address, uses current client if none given
2017 * @return bool True if blocked, false otherwise
2019 public function isBlockedGlobally( $ip = '' ) {
2020 return $this->getGlobalBlock( $ip ) instanceof Block
;
2024 * Check if user is blocked on all wikis.
2025 * Do not use for actual edit permission checks!
2026 * This is intended for quick UI checks.
2028 * @param string $ip IP address, uses current client if none given
2029 * @return Block|null Block object if blocked, null otherwise
2030 * @throws FatalError
2031 * @throws MWException
2033 public function getGlobalBlock( $ip = '' ) {
2034 if ( $this->mGlobalBlock
!== null ) {
2035 return $this->mGlobalBlock ?
: null;
2037 // User is already an IP?
2038 if ( IP
::isIPAddress( $this->getName() ) ) {
2039 $ip = $this->getName();
2041 $ip = $this->getRequest()->getIP();
2045 Hooks
::run( 'UserIsBlockedGlobally', [ &$this, $ip, &$blocked, &$block ] );
2047 if ( $blocked && $block === null ) {
2048 // back-compat: UserIsBlockedGlobally didn't have $block param first
2050 $block->setTarget( $ip );
2053 $this->mGlobalBlock
= $blocked ?
$block : false;
2054 return $this->mGlobalBlock ?
: null;
2058 * Check if user account is locked
2060 * @return bool True if locked, false otherwise
2062 public function isLocked() {
2063 if ( $this->mLocked
!== null ) {
2064 return $this->mLocked
;
2066 $authUser = AuthManager
::callLegacyAuthPlugin( 'getUserInstance', [ &$this ], null );
2067 $this->mLocked
= $authUser && $authUser->isLocked();
2068 Hooks
::run( 'UserIsLocked', [ $this, &$this->mLocked
] );
2069 return $this->mLocked
;
2073 * Check if user account is hidden
2075 * @return bool True if hidden, false otherwise
2077 public function isHidden() {
2078 if ( $this->mHideName
!== null ) {
2079 return $this->mHideName
;
2081 $this->getBlockedStatus();
2082 if ( !$this->mHideName
) {
2083 $authUser = AuthManager
::callLegacyAuthPlugin( 'getUserInstance', [ &$this ], null );
2084 $this->mHideName
= $authUser && $authUser->isHidden();
2085 Hooks
::run( 'UserIsHidden', [ $this, &$this->mHideName
] );
2087 return $this->mHideName
;
2091 * Get the user's ID.
2092 * @return int The user's ID; 0 if the user is anonymous or nonexistent
2094 public function getId() {
2095 if ( $this->mId
=== null && $this->mName
!== null && User
::isIP( $this->mName
) ) {
2096 // Special case, we know the user is anonymous
2098 } elseif ( !$this->isItemLoaded( 'id' ) ) {
2099 // Don't load if this was initialized from an ID
2103 return (int)$this->mId
;
2107 * Set the user and reload all fields according to a given ID
2108 * @param int $v User ID to reload
2110 public function setId( $v ) {
2112 $this->clearInstanceCache( 'id' );
2116 * Get the user name, or the IP of an anonymous user
2117 * @return string User's name or IP address
2119 public function getName() {
2120 if ( $this->isItemLoaded( 'name', 'only' ) ) {
2121 // Special case optimisation
2122 return $this->mName
;
2125 if ( $this->mName
=== false ) {
2127 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
2129 return $this->mName
;
2134 * Set the user name.
2136 * This does not reload fields from the database according to the given
2137 * name. Rather, it is used to create a temporary "nonexistent user" for
2138 * later addition to the database. It can also be used to set the IP
2139 * address for an anonymous user to something other than the current
2142 * @note User::newFromName() has roughly the same function, when the named user
2144 * @param string $str New user name to set
2146 public function setName( $str ) {
2148 $this->mName
= $str;
2152 * Get the user's name escaped by underscores.
2153 * @return string Username escaped by underscores.
2155 public function getTitleKey() {
2156 return str_replace( ' ', '_', $this->getName() );
2160 * Check if the user has new messages.
2161 * @return bool True if the user has new messages
2163 public function getNewtalk() {
2166 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2167 if ( $this->mNewtalk
=== -1 ) {
2168 $this->mNewtalk
= false; # reset talk page status
2170 // Check memcached separately for anons, who have no
2171 // entire User object stored in there.
2172 if ( !$this->mId
) {
2173 global $wgDisableAnonTalk;
2174 if ( $wgDisableAnonTalk ) {
2175 // Anon newtalk disabled by configuration.
2176 $this->mNewtalk
= false;
2178 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
2181 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2185 return (bool)$this->mNewtalk
;
2189 * Return the data needed to construct links for new talk page message
2190 * alerts. If there are new messages, this will return an associative array
2191 * with the following data:
2192 * wiki: The database name of the wiki
2193 * link: Root-relative link to the user's talk page
2194 * rev: The last talk page revision that the user has seen or null. This
2195 * is useful for building diff links.
2196 * If there are no new messages, it returns an empty array.
2197 * @note This function was designed to accomodate multiple talk pages, but
2198 * currently only returns a single link and revision.
2201 public function getNewMessageLinks() {
2203 if ( !Hooks
::run( 'UserRetrieveNewTalks', [ &$this, &$talks ] ) ) {
2205 } elseif ( !$this->getNewtalk() ) {
2208 $utp = $this->getTalkPage();
2209 $dbr = wfGetDB( DB_SLAVE
);
2210 // Get the "last viewed rev" timestamp from the oldest message notification
2211 $timestamp = $dbr->selectField( 'user_newtalk',
2212 'MIN(user_last_timestamp)',
2213 $this->isAnon() ?
[ 'user_ip' => $this->getName() ] : [ 'user_id' => $this->getId() ],
2215 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2216 return [ [ 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ] ];
2220 * Get the revision ID for the last talk page revision viewed by the talk
2222 * @return int|null Revision ID or null
2224 public function getNewMessageRevisionId() {
2225 $newMessageRevisionId = null;
2226 $newMessageLinks = $this->getNewMessageLinks();
2227 if ( $newMessageLinks ) {
2228 // Note: getNewMessageLinks() never returns more than a single link
2229 // and it is always for the same wiki, but we double-check here in
2230 // case that changes some time in the future.
2231 if ( count( $newMessageLinks ) === 1
2232 && $newMessageLinks[0]['wiki'] === wfWikiID()
2233 && $newMessageLinks[0]['rev']
2235 /** @var Revision $newMessageRevision */
2236 $newMessageRevision = $newMessageLinks[0]['rev'];
2237 $newMessageRevisionId = $newMessageRevision->getId();
2240 return $newMessageRevisionId;
2244 * Internal uncached check for new messages
2247 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2248 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2249 * @return bool True if the user has new messages
2251 protected function checkNewtalk( $field, $id ) {
2252 $dbr = wfGetDB( DB_SLAVE
);
2254 $ok = $dbr->selectField( 'user_newtalk', $field, [ $field => $id ], __METHOD__
);
2256 return $ok !== false;
2260 * Add or update the new messages flag
2261 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2262 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2263 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2264 * @return bool True if successful, false otherwise
2266 protected function updateNewtalk( $field, $id, $curRev = null ) {
2267 // Get timestamp of the talk page revision prior to the current one
2268 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2269 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2270 // Mark the user as having new messages since this revision
2271 $dbw = wfGetDB( DB_MASTER
);
2272 $dbw->insert( 'user_newtalk',
2273 [ $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ],
2276 if ( $dbw->affectedRows() ) {
2277 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2280 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2286 * Clear the new messages flag for the given user
2287 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2288 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2289 * @return bool True if successful, false otherwise
2291 protected function deleteNewtalk( $field, $id ) {
2292 $dbw = wfGetDB( DB_MASTER
);
2293 $dbw->delete( 'user_newtalk',
2296 if ( $dbw->affectedRows() ) {
2297 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2300 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2306 * Update the 'You have new messages!' status.
2307 * @param bool $val Whether the user has new messages
2308 * @param Revision $curRev New, as yet unseen revision of the user talk
2309 * page. Ignored if null or !$val.
2311 public function setNewtalk( $val, $curRev = null ) {
2312 if ( wfReadOnly() ) {
2317 $this->mNewtalk
= $val;
2319 if ( $this->isAnon() ) {
2321 $id = $this->getName();
2324 $id = $this->getId();
2328 $changed = $this->updateNewtalk( $field, $id, $curRev );
2330 $changed = $this->deleteNewtalk( $field, $id );
2334 $this->invalidateCache();
2339 * Generate a current or new-future timestamp to be stored in the
2340 * user_touched field when we update things.
2341 * @return string Timestamp in TS_MW format
2343 private function newTouchedTimestamp() {
2344 global $wgClockSkewFudge;
2346 $time = wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2347 if ( $this->mTouched
&& $time <= $this->mTouched
) {
2348 $time = wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $this->mTouched
) +
1 );
2355 * Clear user data from memcached
2357 * Use after applying updates to the database; caller's
2358 * responsibility to update user_touched if appropriate.
2360 * Called implicitly from invalidateCache() and saveSettings().
2362 * @param string $mode Use 'refresh' to clear now; otherwise before DB commit
2364 public function clearSharedCache( $mode = 'changed' ) {
2365 if ( !$this->getId() ) {
2369 $cache = ObjectCache
::getMainWANInstance();
2370 $processCache = self
::getInProcessCache();
2371 $key = $this->getCacheKey( $cache );
2372 if ( $mode === 'refresh' ) {
2373 $cache->delete( $key, 1 );
2374 $processCache->delete( $key );
2376 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle(
2377 function() use ( $cache, $processCache, $key ) {
2378 $cache->delete( $key );
2379 $processCache->delete( $key );
2386 * Immediately touch the user data cache for this account
2388 * Calls touch() and removes account data from memcached
2390 public function invalidateCache() {
2392 $this->clearSharedCache();
2396 * Update the "touched" timestamp for the user
2398 * This is useful on various login/logout events when making sure that
2399 * a browser or proxy that has multiple tenants does not suffer cache
2400 * pollution where the new user sees the old users content. The value
2401 * of getTouched() is checked when determining 304 vs 200 responses.
2402 * Unlike invalidateCache(), this preserves the User object cache and
2403 * avoids database writes.
2407 public function touch() {
2408 $id = $this->getId();
2410 $key = wfMemcKey( 'user-quicktouched', 'id', $id );
2411 ObjectCache
::getMainWANInstance()->touchCheckKey( $key );
2412 $this->mQuickTouched
= null;
2417 * Validate the cache for this account.
2418 * @param string $timestamp A timestamp in TS_MW format
2421 public function validateCache( $timestamp ) {
2422 return ( $timestamp >= $this->getTouched() );
2426 * Get the user touched timestamp
2428 * Use this value only to validate caches via inequalities
2429 * such as in the case of HTTP If-Modified-Since response logic
2431 * @return string TS_MW Timestamp
2433 public function getTouched() {
2437 if ( $this->mQuickTouched
=== null ) {
2438 $key = wfMemcKey( 'user-quicktouched', 'id', $this->mId
);
2439 $cache = ObjectCache
::getMainWANInstance();
2441 $this->mQuickTouched
= wfTimestamp( TS_MW
, $cache->getCheckKeyTime( $key ) );
2444 return max( $this->mTouched
, $this->mQuickTouched
);
2447 return $this->mTouched
;
2451 * Get the user_touched timestamp field (time of last DB updates)
2452 * @return string TS_MW Timestamp
2455 public function getDBTouched() {
2458 return $this->mTouched
;
2462 * @deprecated Removed in 1.27.
2466 public function getPassword() {
2467 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2471 * @deprecated Removed in 1.27.
2475 public function getTemporaryPassword() {
2476 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2480 * Set the password and reset the random token.
2481 * Calls through to authentication plugin if necessary;
2482 * will have no effect if the auth plugin refuses to
2483 * pass the change through or if the legal password
2486 * As a special case, setting the password to null
2487 * wipes it, so the account cannot be logged in until
2488 * a new password is set, for instance via e-mail.
2490 * @deprecated since 1.27, use AuthManager instead
2491 * @param string $str New password to set
2492 * @throws PasswordError On failure
2495 public function setPassword( $str ) {
2496 global $wgAuth, $wgDisableAuthManager;
2498 if ( !$wgDisableAuthManager ) {
2499 return $this->setPasswordInternal( $str );
2502 if ( $str !== null ) {
2503 if ( !$wgAuth->allowPasswordChange() ) {
2504 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2507 $status = $this->checkPasswordValidity( $str );
2508 if ( !$status->isGood() ) {
2509 throw new PasswordError( $status->getMessage()->text() );
2513 if ( !$wgAuth->setPassword( $this, $str ) ) {
2514 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2517 $this->setOption( 'watchlisttoken', false );
2518 $this->setPasswordInternal( $str );
2524 * Set the password and reset the random token unconditionally.
2526 * @deprecated since 1.27, use AuthManager instead
2527 * @param string|null $str New password to set or null to set an invalid
2528 * password hash meaning that the user will not be able to log in
2529 * through the web interface.
2531 public function setInternalPassword( $str ) {
2532 global $wgAuth, $wgDisableAuthManager;
2534 if ( !$wgDisableAuthManager ) {
2535 $this->setPasswordInternal( $str );
2538 if ( $wgAuth->allowSetLocalPassword() ) {
2539 $this->setOption( 'watchlisttoken', false );
2540 $this->setPasswordInternal( $str );
2545 * Actually set the password and such
2546 * @since 1.27 cannot set a password for a user not in the database
2547 * @param string|null $str New password to set or null to set an invalid
2548 * password hash meaning that the user will not be able to log in
2549 * through the web interface.
2550 * @return bool Success
2552 private function setPasswordInternal( $str ) {
2553 global $wgDisableAuthManager;
2555 if ( $wgDisableAuthManager ) {
2556 $id = self
::idFromName( $this->getName(), self
::READ_LATEST
);
2558 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2561 $passwordFactory = new PasswordFactory();
2562 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
2563 $dbw = wfGetDB( DB_MASTER
);
2567 'user_password' => $passwordFactory->newFromPlaintext( $str )->toString(),
2568 'user_newpassword' => PasswordFactory
::newInvalidPassword()->toString(),
2569 'user_newpass_time' => $dbw->timestampOrNull( null ),
2577 // When the main password is changed, invalidate all bot passwords too
2578 BotPassword
::invalidateAllPasswordsForUser( $this->getName() );
2580 $manager = AuthManager
::singleton();
2582 // If the user doesn't exist yet, fail
2583 if ( !$manager->userExists( $this->getName() ) ) {
2584 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2588 'username' => $this->getName(),
2592 $reqs = $manager->getAuthenticationRequests( AuthManager
::ACTION_CHANGE
, $this );
2593 $reqs = AuthenticationRequest
::loadRequestsFromSubmission( $reqs, $data );
2594 foreach ( $reqs as $req ) {
2595 $status = $manager->allowsAuthenticationDataChange( $req );
2596 if ( !$status->isOk() ) {
2597 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
2598 ->info( __METHOD__
. ': Password change rejected: ' . $status->getWikiText() );
2602 foreach ( $reqs as $req ) {
2603 $manager->changeAuthenticationData( $req );
2606 $this->setOption( 'watchlisttoken', false );
2609 SessionManager
::singleton()->invalidateSessionsForUser( $this );
2615 * Get the user's current token.
2616 * @param bool $forceCreation Force the generation of a new token if the
2617 * user doesn't have one (default=true for backwards compatibility).
2618 * @return string|null Token
2620 public function getToken( $forceCreation = true ) {
2621 global $wgAuthenticationTokenVersion;
2624 if ( !$this->mToken
&& $forceCreation ) {
2628 if ( !$this->mToken
) {
2629 // The user doesn't have a token, return null to indicate that.
2631 } elseif ( $this->mToken
=== self
::INVALID_TOKEN
) {
2632 // We return a random value here so existing token checks are very
2634 return MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2635 } elseif ( $wgAuthenticationTokenVersion === null ) {
2636 // $wgAuthenticationTokenVersion not in use, so return the raw secret
2637 return $this->mToken
;
2639 // $wgAuthenticationTokenVersion in use, so hmac it.
2640 $ret = MWCryptHash
::hmac( $wgAuthenticationTokenVersion, $this->mToken
, false );
2642 // The raw hash can be overly long. Shorten it up.
2643 $len = max( 32, self
::TOKEN_LENGTH
);
2644 if ( strlen( $ret ) < $len ) {
2645 // Should never happen, even md5 is 128 bits
2646 throw new \
UnexpectedValueException( 'Hmac returned less than 128 bits' );
2648 return substr( $ret, -$len );
2653 * Set the random token (used for persistent authentication)
2654 * Called from loadDefaults() among other places.
2656 * @param string|bool $token If specified, set the token to this value
2658 public function setToken( $token = false ) {
2660 if ( $this->mToken
=== self
::INVALID_TOKEN
) {
2661 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
2662 ->debug( __METHOD__
. ": Ignoring attempt to set token for system user \"$this\"" );
2663 } elseif ( !$token ) {
2664 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2666 $this->mToken
= $token;
2671 * Set the password for a password reminder or new account email
2673 * @deprecated Removed in 1.27. Use PasswordReset instead.
2674 * @param string $str New password to set or null to set an invalid
2675 * password hash meaning that the user will not be able to use it
2676 * @param bool $throttle If true, reset the throttle timestamp to the present
2678 public function setNewpassword( $str, $throttle = true ) {
2679 global $wgDisableAuthManager;
2681 if ( $wgDisableAuthManager ) {
2682 $id = $this->getId();
2684 throw new LogicException( 'Cannot set new password for a user that is not in the database.' );
2687 $dbw = wfGetDB( DB_MASTER
);
2689 $passwordFactory = new PasswordFactory();
2690 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
2692 'user_newpassword' => $passwordFactory->newFromPlaintext( $str )->toString(),
2695 if ( $str === null ) {
2696 $update['user_newpass_time'] = null;
2697 } elseif ( $throttle ) {
2698 $update['user_newpass_time'] = $dbw->timestamp();
2701 $dbw->update( 'user', $update, [ 'user_id' => $id ], __METHOD__
);
2703 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2708 * Has password reminder email been sent within the last
2709 * $wgPasswordReminderResendTime hours?
2710 * @deprecated Removed in 1.27. See above.
2713 public function isPasswordReminderThrottled() {
2714 global $wgPasswordReminderResendTime, $wgDisableAuthManager;
2716 if ( $wgDisableAuthManager ) {
2717 if ( !$wgPasswordReminderResendTime ) {
2723 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
2724 ?
wfGetDB( DB_MASTER
)
2725 : wfGetDB( DB_SLAVE
);
2726 $newpassTime = $db->selectField(
2728 'user_newpass_time',
2729 [ 'user_id' => $this->getId() ],
2733 if ( $newpassTime === null ) {
2736 $expiry = wfTimestamp( TS_UNIX
, $newpassTime ) +
$wgPasswordReminderResendTime * 3600;
2737 return time() < $expiry;
2739 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2744 * Get the user's e-mail address
2745 * @return string User's email address
2747 public function getEmail() {
2749 Hooks
::run( 'UserGetEmail', [ $this, &$this->mEmail
] );
2750 return $this->mEmail
;
2754 * Get the timestamp of the user's e-mail authentication
2755 * @return string TS_MW timestamp
2757 public function getEmailAuthenticationTimestamp() {
2759 Hooks
::run( 'UserGetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
2760 return $this->mEmailAuthenticated
;
2764 * Set the user's e-mail address
2765 * @param string $str New e-mail address
2767 public function setEmail( $str ) {
2769 if ( $str == $this->mEmail
) {
2772 $this->invalidateEmail();
2773 $this->mEmail
= $str;
2774 Hooks
::run( 'UserSetEmail', [ $this, &$this->mEmail
] );
2778 * Set the user's e-mail address and a confirmation mail if needed.
2781 * @param string $str New e-mail address
2784 public function setEmailWithConfirmation( $str ) {
2785 global $wgEnableEmail, $wgEmailAuthentication;
2787 if ( !$wgEnableEmail ) {
2788 return Status
::newFatal( 'emaildisabled' );
2791 $oldaddr = $this->getEmail();
2792 if ( $str === $oldaddr ) {
2793 return Status
::newGood( true );
2796 $type = $oldaddr != '' ?
'changed' : 'set';
2797 $notificationResult = null;
2799 if ( $wgEmailAuthentication ) {
2800 // Send the user an email notifying the user of the change in registered
2801 // email address on their previous email address
2802 if ( $type == 'changed' ) {
2803 $change = $str != '' ?
'changed' : 'removed';
2804 $notificationResult = $this->sendMail(
2805 wfMessage( 'notificationemail_subject_' . $change )->text(),
2806 wfMessage( 'notificationemail_body_' . $change,
2807 $this->getRequest()->getIP(),
2814 $this->setEmail( $str );
2816 if ( $str !== '' && $wgEmailAuthentication ) {
2817 // Send a confirmation request to the new address if needed
2818 $result = $this->sendConfirmationMail( $type );
2820 if ( $notificationResult !== null ) {
2821 $result->merge( $notificationResult );
2824 if ( $result->isGood() ) {
2825 // Say to the caller that a confirmation and notification mail has been sent
2826 $result->value
= 'eauth';
2829 $result = Status
::newGood( true );
2836 * Get the user's real name
2837 * @return string User's real name
2839 public function getRealName() {
2840 if ( !$this->isItemLoaded( 'realname' ) ) {
2844 return $this->mRealName
;
2848 * Set the user's real name
2849 * @param string $str New real name
2851 public function setRealName( $str ) {
2853 $this->mRealName
= $str;
2857 * Get the user's current setting for a given option.
2859 * @param string $oname The option to check
2860 * @param string $defaultOverride A default value returned if the option does not exist
2861 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2862 * @return string User's current value for the option
2863 * @see getBoolOption()
2864 * @see getIntOption()
2866 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2867 global $wgHiddenPrefs;
2868 $this->loadOptions();
2870 # We want 'disabled' preferences to always behave as the default value for
2871 # users, even if they have set the option explicitly in their settings (ie they
2872 # set it, and then it was disabled removing their ability to change it). But
2873 # we don't want to erase the preferences in the database in case the preference
2874 # is re-enabled again. So don't touch $mOptions, just override the returned value
2875 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2876 return self
::getDefaultOption( $oname );
2879 if ( array_key_exists( $oname, $this->mOptions
) ) {
2880 return $this->mOptions
[$oname];
2882 return $defaultOverride;
2887 * Get all user's options
2889 * @param int $flags Bitwise combination of:
2890 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2891 * to the default value. (Since 1.25)
2894 public function getOptions( $flags = 0 ) {
2895 global $wgHiddenPrefs;
2896 $this->loadOptions();
2897 $options = $this->mOptions
;
2899 # We want 'disabled' preferences to always behave as the default value for
2900 # users, even if they have set the option explicitly in their settings (ie they
2901 # set it, and then it was disabled removing their ability to change it). But
2902 # we don't want to erase the preferences in the database in case the preference
2903 # is re-enabled again. So don't touch $mOptions, just override the returned value
2904 foreach ( $wgHiddenPrefs as $pref ) {
2905 $default = self
::getDefaultOption( $pref );
2906 if ( $default !== null ) {
2907 $options[$pref] = $default;
2911 if ( $flags & self
::GETOPTIONS_EXCLUDE_DEFAULTS
) {
2912 $options = array_diff_assoc( $options, self
::getDefaultOptions() );
2919 * Get the user's current setting for a given option, as a boolean value.
2921 * @param string $oname The option to check
2922 * @return bool User's current value for the option
2925 public function getBoolOption( $oname ) {
2926 return (bool)$this->getOption( $oname );
2930 * Get the user's current setting for a given option, as an integer value.
2932 * @param string $oname The option to check
2933 * @param int $defaultOverride A default value returned if the option does not exist
2934 * @return int User's current value for the option
2937 public function getIntOption( $oname, $defaultOverride = 0 ) {
2938 $val = $this->getOption( $oname );
2940 $val = $defaultOverride;
2942 return intval( $val );
2946 * Set the given option for a user.
2948 * You need to call saveSettings() to actually write to the database.
2950 * @param string $oname The option to set
2951 * @param mixed $val New value to set
2953 public function setOption( $oname, $val ) {
2954 $this->loadOptions();
2956 // Explicitly NULL values should refer to defaults
2957 if ( is_null( $val ) ) {
2958 $val = self
::getDefaultOption( $oname );
2961 $this->mOptions
[$oname] = $val;
2965 * Get a token stored in the preferences (like the watchlist one),
2966 * resetting it if it's empty (and saving changes).
2968 * @param string $oname The option name to retrieve the token from
2969 * @return string|bool User's current value for the option, or false if this option is disabled.
2970 * @see resetTokenFromOption()
2972 * @deprecated 1.26 Applications should use the OAuth extension
2974 public function getTokenFromOption( $oname ) {
2975 global $wgHiddenPrefs;
2977 $id = $this->getId();
2978 if ( !$id ||
in_array( $oname, $wgHiddenPrefs ) ) {
2982 $token = $this->getOption( $oname );
2984 // Default to a value based on the user token to avoid space
2985 // wasted on storing tokens for all users. When this option
2986 // is set manually by the user, only then is it stored.
2987 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
2994 * Reset a token stored in the preferences (like the watchlist one).
2995 * *Does not* save user's preferences (similarly to setOption()).
2997 * @param string $oname The option name to reset the token in
2998 * @return string|bool New token value, or false if this option is disabled.
2999 * @see getTokenFromOption()
3002 public function resetTokenFromOption( $oname ) {
3003 global $wgHiddenPrefs;
3004 if ( in_array( $oname, $wgHiddenPrefs ) ) {
3008 $token = MWCryptRand
::generateHex( 40 );
3009 $this->setOption( $oname, $token );
3014 * Return a list of the types of user options currently returned by
3015 * User::getOptionKinds().
3017 * Currently, the option kinds are:
3018 * - 'registered' - preferences which are registered in core MediaWiki or
3019 * by extensions using the UserGetDefaultOptions hook.
3020 * - 'registered-multiselect' - as above, using the 'multiselect' type.
3021 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
3022 * - 'userjs' - preferences with names starting with 'userjs-', intended to
3023 * be used by user scripts.
3024 * - 'special' - "preferences" that are not accessible via User::getOptions
3025 * or User::setOptions.
3026 * - 'unused' - preferences about which MediaWiki doesn't know anything.
3027 * These are usually legacy options, removed in newer versions.
3029 * The API (and possibly others) use this function to determine the possible
3030 * option types for validation purposes, so make sure to update this when a
3031 * new option kind is added.
3033 * @see User::getOptionKinds
3034 * @return array Option kinds
3036 public static function listOptionKinds() {
3039 'registered-multiselect',
3040 'registered-checkmatrix',
3048 * Return an associative array mapping preferences keys to the kind of a preference they're
3049 * used for. Different kinds are handled differently when setting or reading preferences.
3051 * See User::listOptionKinds for the list of valid option types that can be provided.
3053 * @see User::listOptionKinds
3054 * @param IContextSource $context
3055 * @param array $options Assoc. array with options keys to check as keys.
3056 * Defaults to $this->mOptions.
3057 * @return array The key => kind mapping data
3059 public function getOptionKinds( IContextSource
$context, $options = null ) {
3060 $this->loadOptions();
3061 if ( $options === null ) {
3062 $options = $this->mOptions
;
3065 $prefs = Preferences
::getPreferences( $this, $context );
3068 // Pull out the "special" options, so they don't get converted as
3069 // multiselect or checkmatrix.
3070 $specialOptions = array_fill_keys( Preferences
::getSaveBlacklist(), true );
3071 foreach ( $specialOptions as $name => $value ) {
3072 unset( $prefs[$name] );
3075 // Multiselect and checkmatrix options are stored in the database with
3076 // one key per option, each having a boolean value. Extract those keys.
3077 $multiselectOptions = [];
3078 foreach ( $prefs as $name => $info ) {
3079 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
3080 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
3081 $opts = HTMLFormField
::flattenOptions( $info['options'] );
3082 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
3084 foreach ( $opts as $value ) {
3085 $multiselectOptions["$prefix$value"] = true;
3088 unset( $prefs[$name] );
3091 $checkmatrixOptions = [];
3092 foreach ( $prefs as $name => $info ) {
3093 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
3094 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
3095 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
3096 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
3097 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
3099 foreach ( $columns as $column ) {
3100 foreach ( $rows as $row ) {
3101 $checkmatrixOptions["$prefix$column-$row"] = true;
3105 unset( $prefs[$name] );
3109 // $value is ignored
3110 foreach ( $options as $key => $value ) {
3111 if ( isset( $prefs[$key] ) ) {
3112 $mapping[$key] = 'registered';
3113 } elseif ( isset( $multiselectOptions[$key] ) ) {
3114 $mapping[$key] = 'registered-multiselect';
3115 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
3116 $mapping[$key] = 'registered-checkmatrix';
3117 } elseif ( isset( $specialOptions[$key] ) ) {
3118 $mapping[$key] = 'special';
3119 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
3120 $mapping[$key] = 'userjs';
3122 $mapping[$key] = 'unused';
3130 * Reset certain (or all) options to the site defaults
3132 * The optional parameter determines which kinds of preferences will be reset.
3133 * Supported values are everything that can be reported by getOptionKinds()
3134 * and 'all', which forces a reset of *all* preferences and overrides everything else.
3136 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
3137 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
3138 * for backwards-compatibility.
3139 * @param IContextSource|null $context Context source used when $resetKinds
3140 * does not contain 'all', passed to getOptionKinds().
3141 * Defaults to RequestContext::getMain() when null.
3143 public function resetOptions(
3144 $resetKinds = [ 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ],
3145 IContextSource
$context = null
3148 $defaultOptions = self
::getDefaultOptions();
3150 if ( !is_array( $resetKinds ) ) {
3151 $resetKinds = [ $resetKinds ];
3154 if ( in_array( 'all', $resetKinds ) ) {
3155 $newOptions = $defaultOptions;
3157 if ( $context === null ) {
3158 $context = RequestContext
::getMain();
3161 $optionKinds = $this->getOptionKinds( $context );
3162 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
3165 // Use default values for the options that should be deleted, and
3166 // copy old values for the ones that shouldn't.
3167 foreach ( $this->mOptions
as $key => $value ) {
3168 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
3169 if ( array_key_exists( $key, $defaultOptions ) ) {
3170 $newOptions[$key] = $defaultOptions[$key];
3173 $newOptions[$key] = $value;
3178 Hooks
::run( 'UserResetAllOptions', [ $this, &$newOptions, $this->mOptions
, $resetKinds ] );
3180 $this->mOptions
= $newOptions;
3181 $this->mOptionsLoaded
= true;
3185 * Get the user's preferred date format.
3186 * @return string User's preferred date format
3188 public function getDatePreference() {
3189 // Important migration for old data rows
3190 if ( is_null( $this->mDatePreference
) ) {
3192 $value = $this->getOption( 'date' );
3193 $map = $wgLang->getDatePreferenceMigrationMap();
3194 if ( isset( $map[$value] ) ) {
3195 $value = $map[$value];
3197 $this->mDatePreference
= $value;
3199 return $this->mDatePreference
;
3203 * Determine based on the wiki configuration and the user's options,
3204 * whether this user must be over HTTPS no matter what.
3208 public function requiresHTTPS() {
3209 global $wgSecureLogin;
3210 if ( !$wgSecureLogin ) {
3213 $https = $this->getBoolOption( 'prefershttps' );
3214 Hooks
::run( 'UserRequiresHTTPS', [ $this, &$https ] );
3216 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
3223 * Get the user preferred stub threshold
3227 public function getStubThreshold() {
3228 global $wgMaxArticleSize; # Maximum article size, in Kb
3229 $threshold = $this->getIntOption( 'stubthreshold' );
3230 if ( $threshold > $wgMaxArticleSize * 1024 ) {
3231 // If they have set an impossible value, disable the preference
3232 // so we can use the parser cache again.
3239 * Get the permissions this user has.
3240 * @return array Array of String permission names
3242 public function getRights() {
3243 if ( is_null( $this->mRights
) ) {
3244 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
3246 // Deny any rights denied by the user's session, unless this
3247 // endpoint has no sessions.
3248 if ( !defined( 'MW_NO_SESSION' ) ) {
3249 $allowedRights = $this->getRequest()->getSession()->getAllowedUserRights();
3250 if ( $allowedRights !== null ) {
3251 $this->mRights
= array_intersect( $this->mRights
, $allowedRights );
3255 Hooks
::run( 'UserGetRights', [ $this, &$this->mRights
] );
3256 // Force reindexation of rights when a hook has unset one of them
3257 $this->mRights
= array_values( array_unique( $this->mRights
) );
3259 return $this->mRights
;
3263 * Get the list of explicit group memberships this user has.
3264 * The implicit * and user groups are not included.
3265 * @return array Array of String internal group names
3267 public function getGroups() {
3269 $this->loadGroups();
3270 return $this->mGroups
;
3274 * Get the list of implicit group memberships this user has.
3275 * This includes all explicit groups, plus 'user' if logged in,
3276 * '*' for all accounts, and autopromoted groups
3277 * @param bool $recache Whether to avoid the cache
3278 * @return array Array of String internal group names
3280 public function getEffectiveGroups( $recache = false ) {
3281 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
3282 $this->mEffectiveGroups
= array_unique( array_merge(
3283 $this->getGroups(), // explicit groups
3284 $this->getAutomaticGroups( $recache ) // implicit groups
3286 // Hook for additional groups
3287 Hooks
::run( 'UserEffectiveGroups', [ &$this, &$this->mEffectiveGroups
] );
3288 // Force reindexation of groups when a hook has unset one of them
3289 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
3291 return $this->mEffectiveGroups
;
3295 * Get the list of implicit group memberships this user has.
3296 * This includes 'user' if logged in, '*' for all accounts,
3297 * and autopromoted groups
3298 * @param bool $recache Whether to avoid the cache
3299 * @return array Array of String internal group names
3301 public function getAutomaticGroups( $recache = false ) {
3302 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
3303 $this->mImplicitGroups
= [ '*' ];
3304 if ( $this->getId() ) {
3305 $this->mImplicitGroups
[] = 'user';
3307 $this->mImplicitGroups
= array_unique( array_merge(
3308 $this->mImplicitGroups
,
3309 Autopromote
::getAutopromoteGroups( $this )
3313 // Assure data consistency with rights/groups,
3314 // as getEffectiveGroups() depends on this function
3315 $this->mEffectiveGroups
= null;
3318 return $this->mImplicitGroups
;
3322 * Returns the groups the user has belonged to.
3324 * The user may still belong to the returned groups. Compare with getGroups().
3326 * The function will not return groups the user had belonged to before MW 1.17
3328 * @return array Names of the groups the user has belonged to.
3330 public function getFormerGroups() {
3333 if ( is_null( $this->mFormerGroups
) ) {
3334 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3335 ?
wfGetDB( DB_MASTER
)
3336 : wfGetDB( DB_SLAVE
);
3337 $res = $db->select( 'user_former_groups',
3339 [ 'ufg_user' => $this->mId
],
3341 $this->mFormerGroups
= [];
3342 foreach ( $res as $row ) {
3343 $this->mFormerGroups
[] = $row->ufg_group
;
3347 return $this->mFormerGroups
;
3351 * Get the user's edit count.
3352 * @return int|null Null for anonymous users
3354 public function getEditCount() {
3355 if ( !$this->getId() ) {
3359 if ( $this->mEditCount
=== null ) {
3360 /* Populate the count, if it has not been populated yet */
3361 $dbr = wfGetDB( DB_SLAVE
);
3362 // check if the user_editcount field has been initialized
3363 $count = $dbr->selectField(
3364 'user', 'user_editcount',
3365 [ 'user_id' => $this->mId
],
3369 if ( $count === null ) {
3370 // it has not been initialized. do so.
3371 $count = $this->initEditCount();
3373 $this->mEditCount
= $count;
3375 return (int)$this->mEditCount
;
3379 * Add the user to the given group.
3380 * This takes immediate effect.
3381 * @param string $group Name of the group to add
3384 public function addGroup( $group ) {
3387 if ( !Hooks
::run( 'UserAddGroup', [ $this, &$group ] ) ) {
3391 $dbw = wfGetDB( DB_MASTER
);
3392 if ( $this->getId() ) {
3393 $dbw->insert( 'user_groups',
3395 'ug_user' => $this->getId(),
3396 'ug_group' => $group,
3402 $this->loadGroups();
3403 $this->mGroups
[] = $group;
3404 // In case loadGroups was not called before, we now have the right twice.
3405 // Get rid of the duplicate.
3406 $this->mGroups
= array_unique( $this->mGroups
);
3408 // Refresh the groups caches, and clear the rights cache so it will be
3409 // refreshed on the next call to $this->getRights().
3410 $this->getEffectiveGroups( true );
3411 $this->mRights
= null;
3413 $this->invalidateCache();
3419 * Remove the user from the given group.
3420 * This takes immediate effect.
3421 * @param string $group Name of the group to remove
3424 public function removeGroup( $group ) {
3426 if ( !Hooks
::run( 'UserRemoveGroup', [ $this, &$group ] ) ) {
3430 $dbw = wfGetDB( DB_MASTER
);
3431 $dbw->delete( 'user_groups',
3433 'ug_user' => $this->getId(),
3434 'ug_group' => $group,
3437 // Remember that the user was in this group
3438 $dbw->insert( 'user_former_groups',
3440 'ufg_user' => $this->getId(),
3441 'ufg_group' => $group,
3447 $this->loadGroups();
3448 $this->mGroups
= array_diff( $this->mGroups
, [ $group ] );
3450 // Refresh the groups caches, and clear the rights cache so it will be
3451 // refreshed on the next call to $this->getRights().
3452 $this->getEffectiveGroups( true );
3453 $this->mRights
= null;
3455 $this->invalidateCache();
3461 * Get whether the user is logged in
3464 public function isLoggedIn() {
3465 return $this->getId() != 0;
3469 * Get whether the user is anonymous
3472 public function isAnon() {
3473 return !$this->isLoggedIn();
3477 * @return bool Whether this user is flagged as being a bot role account
3480 public function isBot() {
3481 if ( in_array( 'bot', $this->getGroups() ) && $this->isAllowed( 'bot' ) ) {
3486 Hooks
::run( "UserIsBot", [ $this, &$isBot ] );
3492 * Check if user is allowed to access a feature / make an action
3494 * @param string ... Permissions to test
3495 * @return bool True if user is allowed to perform *any* of the given actions
3497 public function isAllowedAny() {
3498 $permissions = func_get_args();
3499 foreach ( $permissions as $permission ) {
3500 if ( $this->isAllowed( $permission ) ) {
3509 * @param string ... Permissions to test
3510 * @return bool True if the user is allowed to perform *all* of the given actions
3512 public function isAllowedAll() {
3513 $permissions = func_get_args();
3514 foreach ( $permissions as $permission ) {
3515 if ( !$this->isAllowed( $permission ) ) {
3523 * Internal mechanics of testing a permission
3524 * @param string $action
3527 public function isAllowed( $action = '' ) {
3528 if ( $action === '' ) {
3529 return true; // In the spirit of DWIM
3531 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3532 // by misconfiguration: 0 == 'foo'
3533 return in_array( $action, $this->getRights(), true );
3537 * Check whether to enable recent changes patrol features for this user
3538 * @return bool True or false
3540 public function useRCPatrol() {
3541 global $wgUseRCPatrol;
3542 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3546 * Check whether to enable new pages patrol features for this user
3547 * @return bool True or false
3549 public function useNPPatrol() {
3550 global $wgUseRCPatrol, $wgUseNPPatrol;
3552 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3553 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3558 * Check whether to enable new files patrol features for this user
3559 * @return bool True or false
3561 public function useFilePatrol() {
3562 global $wgUseRCPatrol, $wgUseFilePatrol;
3564 ( $wgUseRCPatrol ||
$wgUseFilePatrol )
3565 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3570 * Get the WebRequest object to use with this object
3572 * @return WebRequest
3574 public function getRequest() {
3575 if ( $this->mRequest
) {
3576 return $this->mRequest
;
3584 * Check the watched status of an article.
3585 * @since 1.22 $checkRights parameter added
3586 * @param Title $title Title of the article to look at
3587 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3588 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3591 public function isWatched( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3592 if ( $title->isWatchable() && ( !$checkRights ||
$this->isAllowed( 'viewmywatchlist' ) ) ) {
3593 return MediaWikiServices
::getInstance()->getWatchedItemStore()->isWatched( $this, $title );
3600 * @since 1.22 $checkRights parameter added
3601 * @param Title $title Title of the article to look at
3602 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3603 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3605 public function addWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3606 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3607 MediaWikiServices
::getInstance()->getWatchedItemStore()->addWatchBatchForUser(
3609 [ $title->getSubjectPage(), $title->getTalkPage() ]
3612 $this->invalidateCache();
3616 * Stop watching an article.
3617 * @since 1.22 $checkRights parameter added
3618 * @param Title $title Title of the article to look at
3619 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3620 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3622 public function removeWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3623 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3624 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
3625 $store->removeWatch( $this, $title->getSubjectPage() );
3626 $store->removeWatch( $this, $title->getTalkPage() );
3628 $this->invalidateCache();
3632 * Clear the user's notification timestamp for the given title.
3633 * If e-notif e-mails are on, they will receive notification mails on
3634 * the next change of the page if it's watched etc.
3635 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3636 * @param Title $title Title of the article to look at
3637 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3639 public function clearNotification( &$title, $oldid = 0 ) {
3640 global $wgUseEnotif, $wgShowUpdatedMarker;
3642 // Do nothing if the database is locked to writes
3643 if ( wfReadOnly() ) {
3647 // Do nothing if not allowed to edit the watchlist
3648 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3652 // If we're working on user's talk page, we should update the talk page message indicator
3653 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3654 if ( !Hooks
::run( 'UserClearNewTalkNotification', [ &$this, $oldid ] ) ) {
3658 // Try to update the DB post-send and only if needed...
3659 DeferredUpdates
::addCallableUpdate( function() use ( $title, $oldid ) {
3660 if ( !$this->getNewtalk() ) {
3661 return; // no notifications to clear
3664 // Delete the last notifications (they stack up)
3665 $this->setNewtalk( false );
3667 // If there is a new, unseen, revision, use its timestamp
3669 ?
$title->getNextRevisionID( $oldid, Title
::GAID_FOR_UPDATE
)
3672 $this->setNewtalk( true, Revision
::newFromId( $nextid ) );
3677 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3681 if ( $this->isAnon() ) {
3682 // Nothing else to do...
3686 // Only update the timestamp if the page is being watched.
3687 // The query to find out if it is watched is cached both in memcached and per-invocation,
3688 // and when it does have to be executed, it can be on a slave
3689 // If this is the user's newtalk page, we always update the timestamp
3691 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3695 MediaWikiServices
::getInstance()->getWatchedItemStore()
3696 ->resetNotificationTimestamp( $this, $title, $force, $oldid );
3700 * Resets all of the given user's page-change notification timestamps.
3701 * If e-notif e-mails are on, they will receive notification mails on
3702 * the next change of any watched page.
3703 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3705 public function clearAllNotifications() {
3706 if ( wfReadOnly() ) {
3710 // Do nothing if not allowed to edit the watchlist
3711 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3715 global $wgUseEnotif, $wgShowUpdatedMarker;
3716 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3717 $this->setNewtalk( false );
3720 $id = $this->getId();
3722 $dbw = wfGetDB( DB_MASTER
);
3723 $dbw->update( 'watchlist',
3724 [ /* SET */ 'wl_notificationtimestamp' => null ],
3725 [ /* WHERE */ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ],
3728 // We also need to clear here the "you have new message" notification for the own user_talk page;
3729 // it's cleared one page view later in WikiPage::doViewUpdates().
3734 * Set a cookie on the user's client. Wrapper for
3735 * WebResponse::setCookie
3736 * @deprecated since 1.27
3737 * @param string $name Name of the cookie to set
3738 * @param string $value Value to set
3739 * @param int $exp Expiration time, as a UNIX time value;
3740 * if 0 or not specified, use the default $wgCookieExpiration
3741 * @param bool $secure
3742 * true: Force setting the secure attribute when setting the cookie
3743 * false: Force NOT setting the secure attribute when setting the cookie
3744 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3745 * @param array $params Array of options sent passed to WebResponse::setcookie()
3746 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3749 protected function setCookie(
3750 $name, $value, $exp = 0, $secure = null, $params = [], $request = null
3752 wfDeprecated( __METHOD__
, '1.27' );
3753 if ( $request === null ) {
3754 $request = $this->getRequest();
3756 $params['secure'] = $secure;
3757 $request->response()->setCookie( $name, $value, $exp, $params );
3761 * Clear a cookie on the user's client
3762 * @deprecated since 1.27
3763 * @param string $name Name of the cookie to clear
3764 * @param bool $secure
3765 * true: Force setting the secure attribute when setting the cookie
3766 * false: Force NOT setting the secure attribute when setting the cookie
3767 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3768 * @param array $params Array of options sent passed to WebResponse::setcookie()
3770 protected function clearCookie( $name, $secure = null, $params = [] ) {
3771 wfDeprecated( __METHOD__
, '1.27' );
3772 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3776 * Set an extended login cookie on the user's client. The expiry of the cookie
3777 * is controlled by the $wgExtendedLoginCookieExpiration configuration
3780 * @see User::setCookie
3782 * @deprecated since 1.27
3783 * @param string $name Name of the cookie to set
3784 * @param string $value Value to set
3785 * @param bool $secure
3786 * true: Force setting the secure attribute when setting the cookie
3787 * false: Force NOT setting the secure attribute when setting the cookie
3788 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3790 protected function setExtendedLoginCookie( $name, $value, $secure ) {
3791 global $wgExtendedLoginCookieExpiration, $wgCookieExpiration;
3793 wfDeprecated( __METHOD__
, '1.27' );
3796 $exp +
= $wgExtendedLoginCookieExpiration !== null
3797 ?
$wgExtendedLoginCookieExpiration
3798 : $wgCookieExpiration;
3800 $this->setCookie( $name, $value, $exp, $secure );
3804 * Persist this user's session (e.g. set cookies)
3806 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3808 * @param bool $secure Whether to force secure/insecure cookies or use default
3809 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3811 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3813 if ( 0 == $this->mId
) {
3817 $session = $this->getRequest()->getSession();
3818 if ( $request && $session->getRequest() !== $request ) {
3819 $session = $session->sessionWithRequest( $request );
3821 $delay = $session->delaySave();
3823 if ( !$session->getUser()->equals( $this ) ) {
3824 if ( !$session->canSetUser() ) {
3825 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3826 ->warning( __METHOD__
.
3827 ": Cannot save user \"$this\" to a user \"{$session->getUser()}\"'s immutable session"
3831 $session->setUser( $this );
3834 $session->setRememberUser( $rememberMe );
3835 if ( $secure !== null ) {
3836 $session->setForceHTTPS( $secure );
3839 $session->persist();
3841 ScopedCallback
::consume( $delay );
3845 * Log this user out.
3847 public function logout() {
3848 if ( Hooks
::run( 'UserLogout', [ &$this ] ) ) {
3854 * Clear the user's session, and reset the instance cache.
3857 public function doLogout() {
3858 $session = $this->getRequest()->getSession();
3859 if ( !$session->canSetUser() ) {
3860 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3861 ->warning( __METHOD__
. ": Cannot log out of an immutable session" );
3862 } elseif ( !$session->getUser()->equals( $this ) ) {
3863 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3864 ->warning( __METHOD__
.
3865 ": Cannot log user \"$this\" out of a user \"{$session->getUser()}\"'s session"
3867 // But we still may as well make this user object anon
3868 $this->clearInstanceCache( 'defaults' );
3870 $this->clearInstanceCache( 'defaults' );
3871 $delay = $session->delaySave();
3872 $session->unpersist(); // Clear cookies (T127436)
3873 $session->setLoggedOutTimestamp( time() );
3874 $session->setUser( new User
);
3875 $session->set( 'wsUserID', 0 ); // Other code expects this
3876 ScopedCallback
::consume( $delay );
3881 * Save this user's settings into the database.
3882 * @todo Only rarely do all these fields need to be set!
3884 public function saveSettings() {
3885 if ( wfReadOnly() ) {
3886 // @TODO: caller should deal with this instead!
3887 // This should really just be an exception.
3888 MWExceptionHandler
::logException( new DBExpectedError(
3890 "Could not update user with ID '{$this->mId}'; DB is read-only."
3896 if ( 0 == $this->mId
) {
3900 // Get a new user_touched that is higher than the old one.
3901 // This will be used for a CAS check as a last-resort safety
3902 // check against race conditions and slave lag.
3903 $oldTouched = $this->mTouched
;
3904 $newTouched = $this->newTouchedTimestamp();
3906 $dbw = wfGetDB( DB_MASTER
);
3907 $dbw->update( 'user',
3909 'user_name' => $this->mName
,
3910 'user_real_name' => $this->mRealName
,
3911 'user_email' => $this->mEmail
,
3912 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3913 'user_touched' => $dbw->timestamp( $newTouched ),
3914 'user_token' => strval( $this->mToken
),
3915 'user_email_token' => $this->mEmailToken
,
3916 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
3918 'user_id' => $this->mId
,
3919 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
3923 if ( !$dbw->affectedRows() ) {
3924 // Maybe the problem was a missed cache update; clear it to be safe
3925 $this->clearSharedCache( 'refresh' );
3926 // User was changed in the meantime or loaded with stale data
3927 $from = ( $this->queryFlagsUsed
& self
::READ_LATEST
) ?
'master' : 'slave';
3928 throw new MWException(
3929 "CAS update failed on user_touched for user ID '{$this->mId}' (read from $from);" .
3930 " the version of the user to be saved is older than the current version."
3934 $this->mTouched
= $newTouched;
3935 $this->saveOptions();
3937 Hooks
::run( 'UserSaveSettings', [ $this ] );
3938 $this->clearSharedCache();
3939 $this->getUserPage()->invalidateCache();
3943 * If only this user's username is known, and it exists, return the user ID.
3945 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
3948 public function idForName( $flags = 0 ) {
3949 $s = trim( $this->getName() );
3954 $db = ( ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
)
3955 ?
wfGetDB( DB_MASTER
)
3956 : wfGetDB( DB_SLAVE
);
3958 $options = ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
)
3959 ?
[ 'LOCK IN SHARE MODE' ]
3962 $id = $db->selectField( 'user',
3963 'user_id', [ 'user_name' => $s ], __METHOD__
, $options );
3969 * Add a user to the database, return the user object
3971 * @param string $name Username to add
3972 * @param array $params Array of Strings Non-default parameters to save to
3973 * the database as user_* fields:
3974 * - email: The user's email address.
3975 * - email_authenticated: The email authentication timestamp.
3976 * - real_name: The user's real name.
3977 * - options: An associative array of non-default options.
3978 * - token: Random authentication token. Do not set.
3979 * - registration: Registration timestamp. Do not set.
3981 * @return User|null User object, or null if the username already exists.
3983 public static function createNew( $name, $params = [] ) {
3984 foreach ( [ 'password', 'newpassword', 'newpass_time', 'password_expires' ] as $field ) {
3985 if ( isset( $params[$field] ) ) {
3986 wfDeprecated( __METHOD__
. " with param '$field'", '1.27' );
3987 unset( $params[$field] );
3993 $user->setToken(); // init token
3994 if ( isset( $params['options'] ) ) {
3995 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
3996 unset( $params['options'] );
3998 $dbw = wfGetDB( DB_MASTER
);
3999 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
4001 $noPass = PasswordFactory
::newInvalidPassword()->toString();
4004 'user_id' => $seqVal,
4005 'user_name' => $name,
4006 'user_password' => $noPass,
4007 'user_newpassword' => $noPass,
4008 'user_email' => $user->mEmail
,
4009 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
4010 'user_real_name' => $user->mRealName
,
4011 'user_token' => strval( $user->mToken
),
4012 'user_registration' => $dbw->timestamp( $user->mRegistration
),
4013 'user_editcount' => 0,
4014 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
4016 foreach ( $params as $name => $value ) {
4017 $fields["user_$name"] = $value;
4019 $dbw->insert( 'user', $fields, __METHOD__
, [ 'IGNORE' ] );
4020 if ( $dbw->affectedRows() ) {
4021 $newUser = User
::newFromId( $dbw->insertId() );
4029 * Add this existing user object to the database. If the user already
4030 * exists, a fatal status object is returned, and the user object is
4031 * initialised with the data from the database.
4033 * Previously, this function generated a DB error due to a key conflict
4034 * if the user already existed. Many extension callers use this function
4035 * in code along the lines of:
4037 * $user = User::newFromName( $name );
4038 * if ( !$user->isLoggedIn() ) {
4039 * $user->addToDatabase();
4041 * // do something with $user...
4043 * However, this was vulnerable to a race condition (bug 16020). By
4044 * initialising the user object if the user exists, we aim to support this
4045 * calling sequence as far as possible.
4047 * Note that if the user exists, this function will acquire a write lock,
4048 * so it is still advisable to make the call conditional on isLoggedIn(),
4049 * and to commit the transaction after calling.
4051 * @throws MWException
4054 public function addToDatabase() {
4056 if ( !$this->mToken
) {
4057 $this->setToken(); // init token
4060 $this->mTouched
= $this->newTouchedTimestamp();
4062 $noPass = PasswordFactory
::newInvalidPassword()->toString();
4064 $dbw = wfGetDB( DB_MASTER
);
4065 $inWrite = $dbw->writesOrCallbacksPending();
4066 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
4067 $dbw->insert( 'user',
4069 'user_id' => $seqVal,
4070 'user_name' => $this->mName
,
4071 'user_password' => $noPass,
4072 'user_newpassword' => $noPass,
4073 'user_email' => $this->mEmail
,
4074 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
4075 'user_real_name' => $this->mRealName
,
4076 'user_token' => strval( $this->mToken
),
4077 'user_registration' => $dbw->timestamp( $this->mRegistration
),
4078 'user_editcount' => 0,
4079 'user_touched' => $dbw->timestamp( $this->mTouched
),
4083 if ( !$dbw->affectedRows() ) {
4084 // The queries below cannot happen in the same REPEATABLE-READ snapshot.
4085 // Handle this by COMMIT, if possible, or by LOCK IN SHARE MODE otherwise.
4087 // Can't commit due to pending writes that may need atomicity.
4088 // This may cause some lock contention unlike the case below.
4089 $options = [ 'LOCK IN SHARE MODE' ];
4090 $flags = self
::READ_LOCKING
;
4092 // Often, this case happens early in views before any writes when
4093 // using CentralAuth. It's should be OK to commit and break the snapshot.
4094 $dbw->commit( __METHOD__
, 'flush' );
4096 $flags = self
::READ_LATEST
;
4098 $this->mId
= $dbw->selectField( 'user', 'user_id',
4099 [ 'user_name' => $this->mName
], __METHOD__
, $options );
4102 if ( $this->loadFromDatabase( $flags ) ) {
4107 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
4108 "to insert user '{$this->mName}' row, but it was not present in select!" );
4110 return Status
::newFatal( 'userexists' );
4112 $this->mId
= $dbw->insertId();
4113 self
::$idCacheByName[$this->mName
] = $this->mId
;
4115 // Clear instance cache other than user table data, which is already accurate
4116 $this->clearInstanceCache();
4118 $this->saveOptions();
4119 return Status
::newGood();
4123 * If this user is logged-in and blocked,
4124 * block any IP address they've successfully logged in from.
4125 * @return bool A block was spread
4127 public function spreadAnyEditBlock() {
4128 if ( $this->isLoggedIn() && $this->isBlocked() ) {
4129 return $this->spreadBlock();
4136 * If this (non-anonymous) user is blocked,
4137 * block the IP address they've successfully logged in from.
4138 * @return bool A block was spread
4140 protected function spreadBlock() {
4141 wfDebug( __METHOD__
. "()\n" );
4143 if ( $this->mId
== 0 ) {
4147 $userblock = Block
::newFromTarget( $this->getName() );
4148 if ( !$userblock ) {
4152 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
4156 * Get whether the user is explicitly blocked from account creation.
4157 * @return bool|Block
4159 public function isBlockedFromCreateAccount() {
4160 $this->getBlockedStatus();
4161 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
4162 return $this->mBlock
;
4165 # bug 13611: if the IP address the user is trying to create an account from is
4166 # blocked with createaccount disabled, prevent new account creation there even
4167 # when the user is logged in
4168 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
4169 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
4171 return $this->mBlockedFromCreateAccount
instanceof Block
4172 && $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
4173 ?
$this->mBlockedFromCreateAccount
4178 * Get whether the user is blocked from using Special:Emailuser.
4181 public function isBlockedFromEmailuser() {
4182 $this->getBlockedStatus();
4183 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
4187 * Get whether the user is allowed to create an account.
4190 public function isAllowedToCreateAccount() {
4191 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
4195 * Get this user's personal page title.
4197 * @return Title User's personal page title
4199 public function getUserPage() {
4200 return Title
::makeTitle( NS_USER
, $this->getName() );
4204 * Get this user's talk page title.
4206 * @return Title User's talk page title
4208 public function getTalkPage() {
4209 $title = $this->getUserPage();
4210 return $title->getTalkPage();
4214 * Determine whether the user is a newbie. Newbies are either
4215 * anonymous IPs, or the most recently created accounts.
4218 public function isNewbie() {
4219 return !$this->isAllowed( 'autoconfirmed' );
4223 * Check to see if the given clear-text password is one of the accepted passwords
4224 * @deprecated since 1.27, use AuthManager instead
4225 * @param string $password User password
4226 * @return bool True if the given password is correct, otherwise False
4228 public function checkPassword( $password ) {
4229 global $wgAuth, $wgLegacyEncoding, $wgDisableAuthManager;
4231 if ( $wgDisableAuthManager ) {
4234 // Some passwords will give a fatal Status, which means there is
4235 // some sort of technical or security reason for this password to
4236 // be completely invalid and should never be checked (e.g., T64685)
4237 if ( !$this->checkPasswordValidity( $password )->isOK() ) {
4241 // Certain authentication plugins do NOT want to save
4242 // domain passwords in a mysql database, so we should
4243 // check this (in case $wgAuth->strict() is false).
4244 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
4246 } elseif ( $wgAuth->strict() ) {
4247 // Auth plugin doesn't allow local authentication
4249 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
4250 // Auth plugin doesn't allow local authentication for this user name
4254 $passwordFactory = new PasswordFactory();
4255 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4256 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
4257 ?
wfGetDB( DB_MASTER
)
4258 : wfGetDB( DB_SLAVE
);
4261 $mPassword = $passwordFactory->newFromCiphertext( $db->selectField(
4262 'user', 'user_password', [ 'user_id' => $this->getId() ], __METHOD__
4264 } catch ( PasswordError
$e ) {
4265 wfDebug( 'Invalid password hash found in database.' );
4266 $mPassword = PasswordFactory
::newInvalidPassword();
4269 if ( !$mPassword->equals( $password ) ) {
4270 if ( $wgLegacyEncoding ) {
4271 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
4272 // Check for this with iconv
4273 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
4274 if ( $cp1252Password === $password ||
!$mPassword->equals( $cp1252Password ) ) {
4282 if ( $passwordFactory->needsUpdate( $mPassword ) && !wfReadOnly() ) {
4283 $this->setPasswordInternal( $password );
4288 $manager = AuthManager
::singleton();
4289 $reqs = AuthenticationRequest
::loadRequestsFromSubmission(
4290 $manager->getAuthenticationRequests( AuthManager
::ACTION_LOGIN
),
4292 'username' => $this->getName(),
4293 'password' => $password,
4296 $res = AuthManager
::singleton()->beginAuthentication( $reqs, 'null:' );
4297 switch ( $res->status
) {
4298 case AuthenticationResponse
::PASS
:
4300 case AuthenticationResponse
::FAIL
:
4301 // Hope it's not a PreAuthenticationProvider that failed...
4302 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
4303 ->info( __METHOD__
. ': Authentication failed: ' . $res->message
->plain() );
4306 throw new BadMethodCallException(
4307 'AuthManager returned a response unsupported by ' . __METHOD__
4314 * Check if the given clear-text password matches the temporary password
4315 * sent by e-mail for password reset operations.
4317 * @deprecated since 1.27, use AuthManager instead
4318 * @param string $plaintext
4319 * @return bool True if matches, false otherwise
4321 public function checkTemporaryPassword( $plaintext ) {
4322 global $wgNewPasswordExpiry, $wgDisableAuthManager;
4324 if ( $wgDisableAuthManager ) {
4327 $passwordFactory = new PasswordFactory();
4328 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4329 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
4330 ?
wfGetDB( DB_MASTER
)
4331 : wfGetDB( DB_SLAVE
);
4333 $row = $db->selectRow(
4335 [ 'user_newpassword', 'user_newpass_time' ],
4336 [ 'user_id' => $this->getId() ],
4340 $newPassword = $passwordFactory->newFromCiphertext( $row->user_newpassword
);
4341 } catch ( PasswordError
$e ) {
4342 wfDebug( 'Invalid password hash found in database.' );
4343 $newPassword = PasswordFactory
::newInvalidPassword();
4346 if ( $newPassword->equals( $plaintext ) ) {
4347 if ( is_null( $row->user_newpass_time
) ) {
4350 $expiry = wfTimestamp( TS_UNIX
, $row->user_newpass_time
) +
$wgNewPasswordExpiry;
4351 return ( time() < $expiry );
4356 // Can't check the temporary password individually.
4357 return $this->checkPassword( $plaintext );
4362 * Initialize (if necessary) and return a session token value
4363 * which can be used in edit forms to show that the user's
4364 * login credentials aren't being hijacked with a foreign form
4368 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4369 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4370 * @return MediaWiki\Session\Token The new edit token
4372 public function getEditTokenObject( $salt = '', $request = null ) {
4373 if ( $this->isAnon() ) {
4374 return new LoggedOutEditToken();
4378 $request = $this->getRequest();
4380 return $request->getSession()->getToken( $salt );
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 string The new edit token
4394 public function getEditToken( $salt = '', $request = null ) {
4395 return $this->getEditTokenObject( $salt, $request )->toString();
4399 * Get the embedded timestamp from a token.
4400 * @deprecated since 1.27, use \MediaWiki\Session\Token::getTimestamp instead.
4401 * @param string $val Input token
4404 public static function getEditTokenTimestamp( $val ) {
4405 wfDeprecated( __METHOD__
, '1.27' );
4406 return MediaWiki\Session\Token
::getTimestamp( $val );
4410 * Check given value against the token value stored in the session.
4411 * A match should confirm that the form was submitted from the
4412 * user's own login session, not a form submission from a third-party
4415 * @param string $val Input value to compare
4416 * @param string $salt Optional function-specific data for hashing
4417 * @param WebRequest|null $request Object to use or null to use $wgRequest
4418 * @param int $maxage Fail tokens older than this, in seconds
4419 * @return bool Whether the token matches
4421 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4422 return $this->getEditTokenObject( $salt, $request )->match( $val, $maxage );
4426 * Check given value against the token value stored in the session,
4427 * ignoring the suffix.
4429 * @param string $val Input value to compare
4430 * @param string $salt Optional function-specific data for hashing
4431 * @param WebRequest|null $request Object to use or null to use $wgRequest
4432 * @param int $maxage Fail tokens older than this, in seconds
4433 * @return bool Whether the token matches
4435 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4436 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . Token
::SUFFIX
;
4437 return $this->matchEditToken( $val, $salt, $request, $maxage );
4441 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4442 * mail to the user's given address.
4444 * @param string $type Message to send, either "created", "changed" or "set"
4447 public function sendConfirmationMail( $type = 'created' ) {
4449 $expiration = null; // gets passed-by-ref and defined in next line.
4450 $token = $this->confirmationToken( $expiration );
4451 $url = $this->confirmationTokenUrl( $token );
4452 $invalidateURL = $this->invalidationTokenUrl( $token );
4453 $this->saveSettings();
4455 if ( $type == 'created' ||
$type === false ) {
4456 $message = 'confirmemail_body';
4457 } elseif ( $type === true ) {
4458 $message = 'confirmemail_body_changed';
4460 // Messages: confirmemail_body_changed, confirmemail_body_set
4461 $message = 'confirmemail_body_' . $type;
4464 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4465 wfMessage( $message,
4466 $this->getRequest()->getIP(),
4469 $wgLang->userTimeAndDate( $expiration, $this ),
4471 $wgLang->userDate( $expiration, $this ),
4472 $wgLang->userTime( $expiration, $this ) )->text() );
4476 * Send an e-mail to this user's account. Does not check for
4477 * confirmed status or validity.
4479 * @param string $subject Message subject
4480 * @param string $body Message body
4481 * @param User|null $from Optional sending user; if unspecified, default
4482 * $wgPasswordSender will be used.
4483 * @param string $replyto Reply-To address
4486 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4487 global $wgPasswordSender;
4489 if ( $from instanceof User
) {
4490 $sender = MailAddress
::newFromUser( $from );
4492 $sender = new MailAddress( $wgPasswordSender,
4493 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4495 $to = MailAddress
::newFromUser( $this );
4497 return UserMailer
::send( $to, $sender, $subject, $body, [
4498 'replyTo' => $replyto,
4503 * Generate, store, and return a new e-mail confirmation code.
4504 * A hash (unsalted, since it's used as a key) is stored.
4506 * @note Call saveSettings() after calling this function to commit
4507 * this change to the database.
4509 * @param string &$expiration Accepts the expiration time
4510 * @return string New token
4512 protected function confirmationToken( &$expiration ) {
4513 global $wgUserEmailConfirmationTokenExpiry;
4515 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4516 $expiration = wfTimestamp( TS_MW
, $expires );
4518 $token = MWCryptRand
::generateHex( 32 );
4519 $hash = md5( $token );
4520 $this->mEmailToken
= $hash;
4521 $this->mEmailTokenExpires
= $expiration;
4526 * Return a URL the user can use to confirm their email address.
4527 * @param string $token Accepts the email confirmation token
4528 * @return string New token URL
4530 protected function confirmationTokenUrl( $token ) {
4531 return $this->getTokenUrl( 'ConfirmEmail', $token );
4535 * Return a URL the user can use to invalidate their email address.
4536 * @param string $token Accepts the email confirmation token
4537 * @return string New token URL
4539 protected function invalidationTokenUrl( $token ) {
4540 return $this->getTokenUrl( 'InvalidateEmail', $token );
4544 * Internal function to format the e-mail validation/invalidation URLs.
4545 * This uses a quickie hack to use the
4546 * hardcoded English names of the Special: pages, for ASCII safety.
4548 * @note Since these URLs get dropped directly into emails, using the
4549 * short English names avoids insanely long URL-encoded links, which
4550 * also sometimes can get corrupted in some browsers/mailers
4551 * (bug 6957 with Gmail and Internet Explorer).
4553 * @param string $page Special page
4554 * @param string $token Token
4555 * @return string Formatted URL
4557 protected function getTokenUrl( $page, $token ) {
4558 // Hack to bypass localization of 'Special:'
4559 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4560 return $title->getCanonicalURL();
4564 * Mark the e-mail address confirmed.
4566 * @note Call saveSettings() after calling this function to commit the change.
4570 public function confirmEmail() {
4571 // Check if it's already confirmed, so we don't touch the database
4572 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4573 if ( !$this->isEmailConfirmed() ) {
4574 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4575 Hooks
::run( 'ConfirmEmailComplete', [ $this ] );
4581 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4582 * address if it was already confirmed.
4584 * @note Call saveSettings() after calling this function to commit the change.
4585 * @return bool Returns true
4587 public function invalidateEmail() {
4589 $this->mEmailToken
= null;
4590 $this->mEmailTokenExpires
= null;
4591 $this->setEmailAuthenticationTimestamp( null );
4593 Hooks
::run( 'InvalidateEmailComplete', [ $this ] );
4598 * Set the e-mail authentication timestamp.
4599 * @param string $timestamp TS_MW timestamp
4601 public function setEmailAuthenticationTimestamp( $timestamp ) {
4603 $this->mEmailAuthenticated
= $timestamp;
4604 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
4608 * Is this user allowed to send e-mails within limits of current
4609 * site configuration?
4612 public function canSendEmail() {
4613 global $wgEnableEmail, $wgEnableUserEmail;
4614 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4617 $canSend = $this->isEmailConfirmed();
4618 Hooks
::run( 'UserCanSendEmail', [ &$this, &$canSend ] );
4623 * Is this user allowed to receive e-mails within limits of current
4624 * site configuration?
4627 public function canReceiveEmail() {
4628 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4632 * Is this user's e-mail address valid-looking and confirmed within
4633 * limits of the current site configuration?
4635 * @note If $wgEmailAuthentication is on, this may require the user to have
4636 * confirmed their address by returning a code or using a password
4637 * sent to the address from the wiki.
4641 public function isEmailConfirmed() {
4642 global $wgEmailAuthentication;
4645 if ( Hooks
::run( 'EmailConfirmed', [ &$this, &$confirmed ] ) ) {
4646 if ( $this->isAnon() ) {
4649 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4652 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4662 * Check whether there is an outstanding request for e-mail confirmation.
4665 public function isEmailConfirmationPending() {
4666 global $wgEmailAuthentication;
4667 return $wgEmailAuthentication &&
4668 !$this->isEmailConfirmed() &&
4669 $this->mEmailToken
&&
4670 $this->mEmailTokenExpires
> wfTimestamp();
4674 * Get the timestamp of account creation.
4676 * @return string|bool|null Timestamp of account creation, false for
4677 * non-existent/anonymous user accounts, or null if existing account
4678 * but information is not in database.
4680 public function getRegistration() {
4681 if ( $this->isAnon() ) {
4685 return $this->mRegistration
;
4689 * Get the timestamp of the first edit
4691 * @return string|bool Timestamp of first edit, or false for
4692 * non-existent/anonymous user accounts.
4694 public function getFirstEditTimestamp() {
4695 if ( $this->getId() == 0 ) {
4696 return false; // anons
4698 $dbr = wfGetDB( DB_SLAVE
);
4699 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4700 [ 'rev_user' => $this->getId() ],
4702 [ 'ORDER BY' => 'rev_timestamp ASC' ]
4705 return false; // no edits
4707 return wfTimestamp( TS_MW
, $time );
4711 * Get the permissions associated with a given list of groups
4713 * @param array $groups Array of Strings List of internal group names
4714 * @return array Array of Strings List of permission key names for given groups combined
4716 public static function getGroupPermissions( $groups ) {
4717 global $wgGroupPermissions, $wgRevokePermissions;
4719 // grant every granted permission first
4720 foreach ( $groups as $group ) {
4721 if ( isset( $wgGroupPermissions[$group] ) ) {
4722 $rights = array_merge( $rights,
4723 // array_filter removes empty items
4724 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4727 // now revoke the revoked permissions
4728 foreach ( $groups as $group ) {
4729 if ( isset( $wgRevokePermissions[$group] ) ) {
4730 $rights = array_diff( $rights,
4731 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4734 return array_unique( $rights );
4738 * Get all the groups who have a given permission
4740 * @param string $role Role to check
4741 * @return array Array of Strings List of internal group names with the given permission
4743 public static function getGroupsWithPermission( $role ) {
4744 global $wgGroupPermissions;
4745 $allowedGroups = [];
4746 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4747 if ( self
::groupHasPermission( $group, $role ) ) {
4748 $allowedGroups[] = $group;
4751 return $allowedGroups;
4755 * Check, if the given group has the given permission
4757 * If you're wanting to check whether all users have a permission, use
4758 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4762 * @param string $group Group to check
4763 * @param string $role Role to check
4766 public static function groupHasPermission( $group, $role ) {
4767 global $wgGroupPermissions, $wgRevokePermissions;
4768 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4769 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4773 * Check if all users may be assumed to have the given permission
4775 * We generally assume so if the right is granted to '*' and isn't revoked
4776 * on any group. It doesn't attempt to take grants or other extension
4777 * limitations on rights into account in the general case, though, as that
4778 * would require it to always return false and defeat the purpose.
4779 * Specifically, session-based rights restrictions (such as OAuth or bot
4780 * passwords) are applied based on the current session.
4783 * @param string $right Right to check
4786 public static function isEveryoneAllowed( $right ) {
4787 global $wgGroupPermissions, $wgRevokePermissions;
4790 // Use the cached results, except in unit tests which rely on
4791 // being able change the permission mid-request
4792 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4793 return $cache[$right];
4796 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4797 $cache[$right] = false;
4801 // If it's revoked anywhere, then everyone doesn't have it
4802 foreach ( $wgRevokePermissions as $rights ) {
4803 if ( isset( $rights[$right] ) && $rights[$right] ) {
4804 $cache[$right] = false;
4809 // Remove any rights that aren't allowed to the global-session user,
4810 // unless there are no sessions for this endpoint.
4811 if ( !defined( 'MW_NO_SESSION' ) ) {
4812 $allowedRights = SessionManager
::getGlobalSession()->getAllowedUserRights();
4813 if ( $allowedRights !== null && !in_array( $right, $allowedRights, true ) ) {
4814 $cache[$right] = false;
4819 // Allow extensions to say false
4820 if ( !Hooks
::run( 'UserIsEveryoneAllowed', [ $right ] ) ) {
4821 $cache[$right] = false;
4825 $cache[$right] = true;
4830 * Get the localized descriptive name for a group, if it exists
4832 * @param string $group Internal group name
4833 * @return string Localized descriptive group name
4835 public static function getGroupName( $group ) {
4836 $msg = wfMessage( "group-$group" );
4837 return $msg->isBlank() ?
$group : $msg->text();
4841 * Get the localized descriptive name for a member of a group, if it exists
4843 * @param string $group Internal group name
4844 * @param string $username Username for gender (since 1.19)
4845 * @return string Localized name for group member
4847 public static function getGroupMember( $group, $username = '#' ) {
4848 $msg = wfMessage( "group-$group-member", $username );
4849 return $msg->isBlank() ?
$group : $msg->text();
4853 * Return the set of defined explicit groups.
4854 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4855 * are not included, as they are defined automatically, not in the database.
4856 * @return array Array of internal group names
4858 public static function getAllGroups() {
4859 global $wgGroupPermissions, $wgRevokePermissions;
4861 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4862 self
::getImplicitGroups()
4867 * Get a list of all available permissions.
4868 * @return string[] Array of permission names
4870 public static function getAllRights() {
4871 if ( self
::$mAllRights === false ) {
4872 global $wgAvailableRights;
4873 if ( count( $wgAvailableRights ) ) {
4874 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
4876 self
::$mAllRights = self
::$mCoreRights;
4878 Hooks
::run( 'UserGetAllRights', [ &self
::$mAllRights ] );
4880 return self
::$mAllRights;
4884 * Get a list of implicit groups
4885 * @return array Array of Strings Array of internal group names
4887 public static function getImplicitGroups() {
4888 global $wgImplicitGroups;
4890 $groups = $wgImplicitGroups;
4891 # Deprecated, use $wgImplicitGroups instead
4892 Hooks
::run( 'UserGetImplicitGroups', [ &$groups ], '1.25' );
4898 * Get the title of a page describing a particular group
4900 * @param string $group Internal group name
4901 * @return Title|bool Title of the page if it exists, false otherwise
4903 public static function getGroupPage( $group ) {
4904 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4905 if ( $msg->exists() ) {
4906 $title = Title
::newFromText( $msg->text() );
4907 if ( is_object( $title ) ) {
4915 * Create a link to the group in HTML, if available;
4916 * else return the group name.
4918 * @param string $group Internal name of the group
4919 * @param string $text The text of the link
4920 * @return string HTML link to the group
4922 public static function makeGroupLinkHTML( $group, $text = '' ) {
4923 if ( $text == '' ) {
4924 $text = self
::getGroupName( $group );
4926 $title = self
::getGroupPage( $group );
4928 return Linker
::link( $title, htmlspecialchars( $text ) );
4930 return htmlspecialchars( $text );
4935 * Create a link to the group in Wikitext, if available;
4936 * else return the group name.
4938 * @param string $group Internal name of the group
4939 * @param string $text The text of the link
4940 * @return string Wikilink to the group
4942 public static function makeGroupLinkWiki( $group, $text = '' ) {
4943 if ( $text == '' ) {
4944 $text = self
::getGroupName( $group );
4946 $title = self
::getGroupPage( $group );
4948 $page = $title->getFullText();
4949 return "[[$page|$text]]";
4956 * Returns an array of the groups that a particular group can add/remove.
4958 * @param string $group The group to check for whether it can add/remove
4959 * @return array Array( 'add' => array( addablegroups ),
4960 * 'remove' => array( removablegroups ),
4961 * 'add-self' => array( addablegroups to self),
4962 * 'remove-self' => array( removable groups from self) )
4964 public static function changeableByGroup( $group ) {
4965 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4974 if ( empty( $wgAddGroups[$group] ) ) {
4975 // Don't add anything to $groups
4976 } elseif ( $wgAddGroups[$group] === true ) {
4977 // You get everything
4978 $groups['add'] = self
::getAllGroups();
4979 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4980 $groups['add'] = $wgAddGroups[$group];
4983 // Same thing for remove
4984 if ( empty( $wgRemoveGroups[$group] ) ) {
4986 } elseif ( $wgRemoveGroups[$group] === true ) {
4987 $groups['remove'] = self
::getAllGroups();
4988 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4989 $groups['remove'] = $wgRemoveGroups[$group];
4992 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4993 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4994 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4995 if ( is_int( $key ) ) {
4996 $wgGroupsAddToSelf['user'][] = $value;
5001 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
5002 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
5003 if ( is_int( $key ) ) {
5004 $wgGroupsRemoveFromSelf['user'][] = $value;
5009 // Now figure out what groups the user can add to him/herself
5010 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
5012 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
5013 // No idea WHY this would be used, but it's there
5014 $groups['add-self'] = User
::getAllGroups();
5015 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
5016 $groups['add-self'] = $wgGroupsAddToSelf[$group];
5019 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
5021 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
5022 $groups['remove-self'] = User
::getAllGroups();
5023 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
5024 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
5031 * Returns an array of groups that this user can add and remove
5032 * @return array Array( 'add' => array( addablegroups ),
5033 * 'remove' => array( removablegroups ),
5034 * 'add-self' => array( addablegroups to self),
5035 * 'remove-self' => array( removable groups from self) )
5037 public function changeableGroups() {
5038 if ( $this->isAllowed( 'userrights' ) ) {
5039 // This group gives the right to modify everything (reverse-
5040 // compatibility with old "userrights lets you change
5042 // Using array_merge to make the groups reindexed
5043 $all = array_merge( User
::getAllGroups() );
5052 // Okay, it's not so simple, we will have to go through the arrays
5059 $addergroups = $this->getEffectiveGroups();
5061 foreach ( $addergroups as $addergroup ) {
5062 $groups = array_merge_recursive(
5063 $groups, $this->changeableByGroup( $addergroup )
5065 $groups['add'] = array_unique( $groups['add'] );
5066 $groups['remove'] = array_unique( $groups['remove'] );
5067 $groups['add-self'] = array_unique( $groups['add-self'] );
5068 $groups['remove-self'] = array_unique( $groups['remove-self'] );
5074 * Deferred version of incEditCountImmediate()
5076 public function incEditCount() {
5077 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle( function() {
5078 $this->incEditCountImmediate();
5083 * Increment the user's edit-count field.
5084 * Will have no effect for anonymous users.
5087 public function incEditCountImmediate() {
5088 if ( $this->isAnon() ) {
5092 $dbw = wfGetDB( DB_MASTER
);
5093 // No rows will be "affected" if user_editcount is NULL
5096 [ 'user_editcount=user_editcount+1' ],
5097 [ 'user_id' => $this->getId(), 'user_editcount IS NOT NULL' ],
5100 // Lazy initialization check...
5101 if ( $dbw->affectedRows() == 0 ) {
5102 // Now here's a goddamn hack...
5103 $dbr = wfGetDB( DB_SLAVE
);
5104 if ( $dbr !== $dbw ) {
5105 // If we actually have a slave server, the count is
5106 // at least one behind because the current transaction
5107 // has not been committed and replicated.
5108 $this->initEditCount( 1 );
5110 // But if DB_SLAVE is selecting the master, then the
5111 // count we just read includes the revision that was
5112 // just added in the working transaction.
5113 $this->initEditCount();
5116 // Edit count in user cache too
5117 $this->invalidateCache();
5121 * Initialize user_editcount from data out of the revision table
5123 * @param int $add Edits to add to the count from the revision table
5124 * @return int Number of edits
5126 protected function initEditCount( $add = 0 ) {
5127 // Pull from a slave to be less cruel to servers
5128 // Accuracy isn't the point anyway here
5129 $dbr = wfGetDB( DB_SLAVE
);
5130 $count = (int)$dbr->selectField(
5133 [ 'rev_user' => $this->getId() ],
5136 $count = $count +
$add;
5138 $dbw = wfGetDB( DB_MASTER
);
5141 [ 'user_editcount' => $count ],
5142 [ 'user_id' => $this->getId() ],
5150 * Get the description of a given right
5152 * @param string $right Right to query
5153 * @return string Localized description of the right
5155 public static function getRightDescription( $right ) {
5156 $key = "right-$right";
5157 $msg = wfMessage( $key );
5158 return $msg->isBlank() ?
$right : $msg->text();
5162 * Make a new-style password hash
5164 * @param string $password Plain-text password
5165 * @param bool|string $salt Optional salt, may be random or the user ID.
5166 * If unspecified or false, will generate one automatically
5167 * @return string Password hash
5168 * @deprecated since 1.24, use Password class
5170 public static function crypt( $password, $salt = false ) {
5171 wfDeprecated( __METHOD__
, '1.24' );
5172 $passwordFactory = new PasswordFactory();
5173 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
5174 $hash = $passwordFactory->newFromPlaintext( $password );
5175 return $hash->toString();
5179 * Compare a password hash with a plain-text password. Requires the user
5180 * ID if there's a chance that the hash is an old-style hash.
5182 * @param string $hash Password hash
5183 * @param string $password Plain-text password to compare
5184 * @param string|bool $userId User ID for old-style password salt
5187 * @deprecated since 1.24, use Password class
5189 public static function comparePasswords( $hash, $password, $userId = false ) {
5190 wfDeprecated( __METHOD__
, '1.24' );
5192 // Check for *really* old password hashes that don't even have a type
5193 // The old hash format was just an md5 hex hash, with no type information
5194 if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) {
5195 global $wgPasswordSalt;
5196 if ( $wgPasswordSalt ) {
5197 $password = ":B:{$userId}:{$hash}";
5199 $password = ":A:{$hash}";
5203 $passwordFactory = new PasswordFactory();
5204 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
5205 $hash = $passwordFactory->newFromCiphertext( $hash );
5206 return $hash->equals( $password );
5210 * Add a newuser log entry for this user.
5211 * Before 1.19 the return value was always true.
5213 * @deprecated since 1.27, AuthManager handles logging
5214 * @param string|bool $action Account creation type.
5215 * - String, one of the following values:
5216 * - 'create' for an anonymous user creating an account for himself.
5217 * This will force the action's performer to be the created user itself,
5218 * no matter the value of $wgUser
5219 * - 'create2' for a logged in user creating an account for someone else
5220 * - 'byemail' when the created user will receive its password by e-mail
5221 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
5222 * - Boolean means whether the account was created by e-mail (deprecated):
5223 * - true will be converted to 'byemail'
5224 * - false will be converted to 'create' if this object is the same as
5225 * $wgUser and to 'create2' otherwise
5226 * @param string $reason User supplied reason
5227 * @return int|bool True if not $wgNewUserLog or not $wgDisableAuthManager;
5228 * otherwise ID of log item or 0 on failure
5230 public function addNewUserLogEntry( $action = false, $reason = '' ) {
5231 global $wgUser, $wgNewUserLog, $wgDisableAuthManager;
5232 if ( !$wgDisableAuthManager ||
empty( $wgNewUserLog ) ) {
5233 return true; // disabled
5236 if ( $action === true ) {
5237 $action = 'byemail';
5238 } elseif ( $action === false ) {
5239 if ( $this->equals( $wgUser ) ) {
5242 $action = 'create2';
5246 if ( $action === 'create' ||
$action === 'autocreate' ) {
5249 $performer = $wgUser;
5252 $logEntry = new ManualLogEntry( 'newusers', $action );
5253 $logEntry->setPerformer( $performer );
5254 $logEntry->setTarget( $this->getUserPage() );
5255 $logEntry->setComment( $reason );
5256 $logEntry->setParameters( [
5257 '4::userid' => $this->getId(),
5259 $logid = $logEntry->insert();
5261 if ( $action !== 'autocreate' ) {
5262 $logEntry->publish( $logid );
5269 * Add an autocreate newuser log entry for this user
5270 * Used by things like CentralAuth and perhaps other authplugins.
5271 * Consider calling addNewUserLogEntry() directly instead.
5273 * @deprecated since 1.27, AuthManager handles logging
5276 public function addNewUserLogEntryAutoCreate() {
5277 $this->addNewUserLogEntry( 'autocreate' );
5283 * Load the user options either from cache, the database or an array
5285 * @param array $data Rows for the current user out of the user_properties table
5287 protected function loadOptions( $data = null ) {
5292 if ( $this->mOptionsLoaded
) {
5296 $this->mOptions
= self
::getDefaultOptions();
5298 if ( !$this->getId() ) {
5299 // For unlogged-in users, load language/variant options from request.
5300 // There's no need to do it for logged-in users: they can set preferences,
5301 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5302 // so don't override user's choice (especially when the user chooses site default).
5303 $variant = $wgContLang->getDefaultVariant();
5304 $this->mOptions
['variant'] = $variant;
5305 $this->mOptions
['language'] = $variant;
5306 $this->mOptionsLoaded
= true;
5310 // Maybe load from the object
5311 if ( !is_null( $this->mOptionOverrides
) ) {
5312 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5313 foreach ( $this->mOptionOverrides
as $key => $value ) {
5314 $this->mOptions
[$key] = $value;
5317 if ( !is_array( $data ) ) {
5318 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5319 // Load from database
5320 $dbr = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
5321 ?
wfGetDB( DB_MASTER
)
5322 : wfGetDB( DB_SLAVE
);
5324 $res = $dbr->select(
5326 [ 'up_property', 'up_value' ],
5327 [ 'up_user' => $this->getId() ],
5331 $this->mOptionOverrides
= [];
5333 foreach ( $res as $row ) {
5334 $data[$row->up_property
] = $row->up_value
;
5337 foreach ( $data as $property => $value ) {
5338 $this->mOptionOverrides
[$property] = $value;
5339 $this->mOptions
[$property] = $value;
5343 $this->mOptionsLoaded
= true;
5345 Hooks
::run( 'UserLoadOptions', [ $this, &$this->mOptions
] );
5349 * Saves the non-default options for this user, as previously set e.g. via
5350 * setOption(), in the database's "user_properties" (preferences) table.
5351 * Usually used via saveSettings().
5353 protected function saveOptions() {
5354 $this->loadOptions();
5356 // Not using getOptions(), to keep hidden preferences in database
5357 $saveOptions = $this->mOptions
;
5359 // Allow hooks to abort, for instance to save to a global profile.
5360 // Reset options to default state before saving.
5361 if ( !Hooks
::run( 'UserSaveOptions', [ $this, &$saveOptions ] ) ) {
5365 $userId = $this->getId();
5367 $insert_rows = []; // all the new preference rows
5368 foreach ( $saveOptions as $key => $value ) {
5369 // Don't bother storing default values
5370 $defaultOption = self
::getDefaultOption( $key );
5371 if ( ( $defaultOption === null && $value !== false && $value !== null )
5372 ||
$value != $defaultOption
5375 'up_user' => $userId,
5376 'up_property' => $key,
5377 'up_value' => $value,
5382 $dbw = wfGetDB( DB_MASTER
);
5384 $res = $dbw->select( 'user_properties',
5385 [ 'up_property', 'up_value' ], [ 'up_user' => $userId ], __METHOD__
);
5387 // Find prior rows that need to be removed or updated. These rows will
5388 // all be deleted (the later so that INSERT IGNORE applies the new values).
5390 foreach ( $res as $row ) {
5391 if ( !isset( $saveOptions[$row->up_property
] )
5392 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
5394 $keysDelete[] = $row->up_property
;
5398 if ( count( $keysDelete ) ) {
5399 // Do the DELETE by PRIMARY KEY for prior rows.
5400 // In the past a very large portion of calls to this function are for setting
5401 // 'rememberpassword' for new accounts (a preference that has since been removed).
5402 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5403 // caused gap locks on [max user ID,+infinity) which caused high contention since
5404 // updates would pile up on each other as they are for higher (newer) user IDs.
5405 // It might not be necessary these days, but it shouldn't hurt either.
5406 $dbw->delete( 'user_properties',
5407 [ 'up_user' => $userId, 'up_property' => $keysDelete ], __METHOD__
);
5409 // Insert the new preference rows
5410 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, [ 'IGNORE' ] );
5414 * Lazily instantiate and return a factory object for making passwords
5416 * @deprecated since 1.27, create a PasswordFactory directly instead
5417 * @return PasswordFactory
5419 public static function getPasswordFactory() {
5420 wfDeprecated( __METHOD__
, '1.27' );
5421 $ret = new PasswordFactory();
5422 $ret->init( RequestContext
::getMain()->getConfig() );
5427 * Provide an array of HTML5 attributes to put on an input element
5428 * intended for the user to enter a new password. This may include
5429 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
5431 * Do *not* use this when asking the user to enter his current password!
5432 * Regardless of configuration, users may have invalid passwords for whatever
5433 * reason (e.g., they were set before requirements were tightened up).
5434 * Only use it when asking for a new password, like on account creation or
5437 * Obviously, you still need to do server-side checking.
5439 * NOTE: A combination of bugs in various browsers means that this function
5440 * actually just returns array() unconditionally at the moment. May as
5441 * well keep it around for when the browser bugs get fixed, though.
5443 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
5445 * @deprecated since 1.27
5446 * @return array Array of HTML attributes suitable for feeding to
5447 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
5448 * That will get confused by the boolean attribute syntax used.)
5450 public static function passwordChangeInputAttribs() {
5451 global $wgMinimalPasswordLength;
5453 if ( $wgMinimalPasswordLength == 0 ) {
5457 # Note that the pattern requirement will always be satisfied if the
5458 # input is empty, so we need required in all cases.
5460 # @todo FIXME: Bug 23769: This needs to not claim the password is required
5461 # if e-mail confirmation is being used. Since HTML5 input validation
5462 # is b0rked anyway in some browsers, just return nothing. When it's
5463 # re-enabled, fix this code to not output required for e-mail
5465 # $ret = array( 'required' );
5468 # We can't actually do this right now, because Opera 9.6 will print out
5469 # the entered password visibly in its error message! When other
5470 # browsers add support for this attribute, or Opera fixes its support,
5471 # we can add support with a version check to avoid doing this on Opera
5472 # versions where it will be a problem. Reported to Opera as
5473 # DSK-262266, but they don't have a public bug tracker for us to follow.
5475 if ( $wgMinimalPasswordLength > 1 ) {
5476 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
5477 $ret['title'] = wfMessage( 'passwordtooshort' )
5478 ->numParams( $wgMinimalPasswordLength )->text();
5486 * Return the list of user fields that should be selected to create
5487 * a new user object.
5490 public static function selectFields() {
5498 'user_email_authenticated',
5500 'user_email_token_expires',
5501 'user_registration',
5507 * Factory function for fatal permission-denied errors
5510 * @param string $permission User right required
5513 static function newFatalPermissionDeniedStatus( $permission ) {
5516 $groups = array_map(
5517 [ 'User', 'makeGroupLinkWiki' ],
5518 User
::getGroupsWithPermission( $permission )
5522 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5524 return Status
::newFatal( 'badaccess-group0' );
5529 * Get a new instance of this user that was loaded from the master via a locking read
5531 * Use this instead of the main context User when updating that user. This avoids races
5532 * where that user was loaded from a slave or even the master but without proper locks.
5534 * @return User|null Returns null if the user was not found in the DB
5537 public function getInstanceForUpdate() {
5538 if ( !$this->getId() ) {
5539 return null; // anon
5542 $user = self
::newFromId( $this->getId() );
5543 if ( !$user->loadFromId( self
::READ_EXCLUSIVE
) ) {
5551 * Checks if two user objects point to the same user.
5557 public function equals( User
$user ) {
5558 return $this->getName() === $user->getName();