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 ) ||
$data['mVersion'] < self
::VERSION
) {
509 $processCache->set( $key, $data );
511 wfDebug( "User: got user {$this->mId} from cache\n" );
513 // Restore from cache
514 foreach ( self
::$mCacheVars as $name ) {
515 $this->$name = $data[$name];
522 * Save user data to the shared cache
524 * This method should not be called outside the User class
526 public function saveToCache() {
529 $this->loadOptions();
531 if ( $this->isAnon() ) {
532 // Anonymous users are uncached
537 foreach ( self
::$mCacheVars as $name ) {
538 $data[$name] = $this->$name;
540 $data['mVersion'] = self
::VERSION
;
541 $opts = Database
::getCacheSetOptions( wfGetDB( DB_SLAVE
) );
543 $cache = ObjectCache
::getMainWANInstance();
544 $processCache = self
::getInProcessCache();
545 $key = $this->getCacheKey( $cache );
546 $cache->set( $key, $data, $cache::TTL_HOUR
, $opts );
547 $processCache->set( $key, $data );
550 /** @name newFrom*() static factory methods */
554 * Static factory method for creation from username.
556 * This is slightly less efficient than newFromId(), so use newFromId() if
557 * you have both an ID and a name handy.
559 * @param string $name Username, validated by Title::newFromText()
560 * @param string|bool $validate Validate username. Takes the same parameters as
561 * User::getCanonicalName(), except that true is accepted as an alias
562 * for 'valid', for BC.
564 * @return User|bool User object, or false if the username is invalid
565 * (e.g. if it contains illegal characters or is an IP address). If the
566 * username is not present in the database, the result will be a user object
567 * with a name, zero user ID and default settings.
569 public static function newFromName( $name, $validate = 'valid' ) {
570 if ( $validate === true ) {
573 $name = self
::getCanonicalName( $name, $validate );
574 if ( $name === false ) {
577 // Create unloaded user object
581 $u->setItemLoaded( 'name' );
587 * Static factory method for creation from a given user ID.
589 * @param int $id Valid user ID
590 * @return User The corresponding User object
592 public static function newFromId( $id ) {
596 $u->setItemLoaded( 'id' );
601 * Factory method to fetch whichever user has a given email confirmation code.
602 * This code is generated when an account is created or its e-mail address
605 * If the code is invalid or has expired, returns NULL.
607 * @param string $code Confirmation code
608 * @param int $flags User::READ_* bitfield
611 public static function newFromConfirmationCode( $code, $flags = 0 ) {
612 $db = ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
613 ?
wfGetDB( DB_MASTER
)
614 : wfGetDB( DB_SLAVE
);
616 $id = $db->selectField(
620 'user_email_token' => md5( $code ),
621 'user_email_token_expires > ' . $db->addQuotes( $db->timestamp() ),
625 return $id ? User
::newFromId( $id ) : null;
629 * Create a new user object using data from session. If the login
630 * credentials are invalid, the result is an anonymous user.
632 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
635 public static function newFromSession( WebRequest
$request = null ) {
637 $user->mFrom
= 'session';
638 $user->mRequest
= $request;
643 * Create a new user object from a user row.
644 * The row should have the following fields from the user table in it:
645 * - either user_name or user_id to load further data if needed (or both)
647 * - all other fields (email, etc.)
648 * It is useless to provide the remaining fields if either user_id,
649 * user_name and user_real_name are not provided because the whole row
650 * will be loaded once more from the database when accessing them.
652 * @param stdClass $row A row from the user table
653 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
656 public static function newFromRow( $row, $data = null ) {
658 $user->loadFromRow( $row, $data );
663 * Static factory method for creation of a "system" user from username.
665 * A "system" user is an account that's used to attribute logged actions
666 * taken by MediaWiki itself, as opposed to a bot or human user. Examples
667 * might include the 'Maintenance script' or 'Conversion script' accounts
668 * used by various scripts in the maintenance/ directory or accounts such
669 * as 'MediaWiki message delivery' used by the MassMessage extension.
671 * This can optionally create the user if it doesn't exist, and "steal" the
672 * account if it does exist.
674 * @param string $name Username
675 * @param array $options Options are:
676 * - validate: As for User::getCanonicalName(), default 'valid'
677 * - create: Whether to create the user if it doesn't already exist, default true
678 * - steal: Whether to reset the account's password and email if it
679 * already exists, default false
683 public static function newSystemUser( $name, $options = [] ) {
684 global $wgDisableAuthManager;
687 'validate' => 'valid',
692 $name = self
::getCanonicalName( $name, $options['validate'] );
693 if ( $name === false ) {
697 $fields = self
::selectFields();
698 if ( $wgDisableAuthManager ) {
699 $fields = array_merge( $fields, [ 'user_password', 'user_newpassword' ] );
702 $dbw = wfGetDB( DB_MASTER
);
703 $row = $dbw->selectRow(
706 [ 'user_name' => $name ],
710 // No user. Create it?
711 return $options['create'] ? self
::createNew( $name ) : null;
713 $user = self
::newFromRow( $row );
715 // A user is considered to exist as a non-system user if it has a
716 // password set, or a temporary password set, or an email set, or a
717 // non-invalid token.
718 if ( !$user->mEmail
&& $user->mToken
=== self
::INVALID_TOKEN
) {
719 if ( $wgDisableAuthManager ) {
720 $passwordFactory = new PasswordFactory();
721 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
723 $password = $passwordFactory->newFromCiphertext( $row->user_password
);
724 } catch ( PasswordError
$e ) {
725 wfDebug( 'Invalid password hash found in database.' );
726 $password = PasswordFactory
::newInvalidPassword();
729 $newpassword = $passwordFactory->newFromCiphertext( $row->user_newpassword
);
730 } catch ( PasswordError
$e ) {
731 wfDebug( 'Invalid password hash found in database.' );
732 $newpassword = PasswordFactory
::newInvalidPassword();
734 $canAuthenticate = !$password instanceof InvalidPassword ||
735 !$newpassword instanceof InvalidPassword
;
737 $canAuthenticate = AuthManager
::singleton()->userCanAuthenticate( $name );
740 if ( $user->mEmail ||
$user->mToken
!== self
::INVALID_TOKEN ||
$canAuthenticate ) {
741 // User exists. Steal it?
742 if ( !$options['steal'] ) {
746 if ( $wgDisableAuthManager ) {
747 $nopass = PasswordFactory
::newInvalidPassword()->toString();
751 'user_password' => $nopass,
752 'user_newpassword' => $nopass,
753 'user_newpass_time' => null,
755 [ 'user_id' => $user->getId() ],
759 AuthManager
::singleton()->revokeAccessForUser( $name );
762 $user->invalidateEmail();
763 $user->mToken
= self
::INVALID_TOKEN
;
764 $user->saveSettings();
765 SessionManager
::singleton()->preventSessionsForUser( $user->getName() );
774 * Get the username corresponding to a given user ID
775 * @param int $id User ID
776 * @return string|bool The corresponding username
778 public static function whoIs( $id ) {
779 return UserCache
::singleton()->getProp( $id, 'name' );
783 * Get the real name of a user given their user ID
785 * @param int $id User ID
786 * @return string|bool The corresponding user's real name
788 public static function whoIsReal( $id ) {
789 return UserCache
::singleton()->getProp( $id, 'real_name' );
793 * Get database id given a user name
794 * @param string $name Username
795 * @param integer $flags User::READ_* constant bitfield
796 * @return int|null The corresponding user's ID, or null if user is nonexistent
798 public static function idFromName( $name, $flags = self
::READ_NORMAL
) {
799 $nt = Title
::makeTitleSafe( NS_USER
, $name );
800 if ( is_null( $nt ) ) {
805 if ( !( $flags & self
::READ_LATEST
) && isset( self
::$idCacheByName[$name] ) ) {
806 return self
::$idCacheByName[$name];
809 $db = ( $flags & self
::READ_LATEST
)
810 ?
wfGetDB( DB_MASTER
)
811 : wfGetDB( DB_SLAVE
);
816 [ 'user_name' => $nt->getText() ],
820 if ( $s === false ) {
823 $result = $s->user_id
;
826 self
::$idCacheByName[$name] = $result;
828 if ( count( self
::$idCacheByName ) > 1000 ) {
829 self
::$idCacheByName = [];
836 * Reset the cache used in idFromName(). For use in tests.
838 public static function resetIdByNameCache() {
839 self
::$idCacheByName = [];
843 * Does the string match an anonymous IPv4 address?
845 * This function exists for username validation, in order to reject
846 * usernames which are similar in form to IP addresses. Strings such
847 * as 300.300.300.300 will return true because it looks like an IP
848 * address, despite not being strictly valid.
850 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
851 * address because the usemod software would "cloak" anonymous IP
852 * addresses like this, if we allowed accounts like this to be created
853 * new users could get the old edits of these anonymous users.
855 * @param string $name Name to match
858 public static function isIP( $name ) {
859 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
860 || IP
::isIPv6( $name );
864 * Is the input a valid username?
866 * Checks if the input is a valid username, we don't want an empty string,
867 * an IP address, anything that contains slashes (would mess up subpages),
868 * is longer than the maximum allowed username size or doesn't begin with
871 * @param string $name Name to match
874 public static function isValidUserName( $name ) {
875 global $wgContLang, $wgMaxNameChars;
878 || User
::isIP( $name )
879 ||
strpos( $name, '/' ) !== false
880 ||
strlen( $name ) > $wgMaxNameChars
881 ||
$name != $wgContLang->ucfirst( $name )
886 // Ensure that the name can't be misresolved as a different title,
887 // such as with extra namespace keys at the start.
888 $parsed = Title
::newFromText( $name );
889 if ( is_null( $parsed )
890 ||
$parsed->getNamespace()
891 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
895 // Check an additional blacklist of troublemaker characters.
896 // Should these be merged into the title char list?
897 $unicodeBlacklist = '/[' .
898 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
899 '\x{00a0}' . # non-breaking space
900 '\x{2000}-\x{200f}' . # various whitespace
901 '\x{2028}-\x{202f}' . # breaks and control chars
902 '\x{3000}' . # ideographic space
903 '\x{e000}-\x{f8ff}' . # private use
905 if ( preg_match( $unicodeBlacklist, $name ) ) {
913 * Usernames which fail to pass this function will be blocked
914 * from user login and new account registrations, but may be used
915 * internally by batch processes.
917 * If an account already exists in this form, login will be blocked
918 * by a failure to pass this function.
920 * @param string $name Name to match
923 public static function isUsableName( $name ) {
924 global $wgReservedUsernames;
925 // Must be a valid username, obviously ;)
926 if ( !self
::isValidUserName( $name ) ) {
930 static $reservedUsernames = false;
931 if ( !$reservedUsernames ) {
932 $reservedUsernames = $wgReservedUsernames;
933 Hooks
::run( 'UserGetReservedNames', [ &$reservedUsernames ] );
936 // Certain names may be reserved for batch processes.
937 foreach ( $reservedUsernames as $reserved ) {
938 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
939 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
941 if ( $reserved == $name ) {
949 * Usernames which fail to pass this function will be blocked
950 * from new account registrations, but may be used internally
951 * either by batch processes or by user accounts which have
952 * already been created.
954 * Additional blacklisting may be added here rather than in
955 * isValidUserName() to avoid disrupting existing accounts.
957 * @param string $name String to match
960 public static function isCreatableName( $name ) {
961 global $wgInvalidUsernameCharacters;
963 // Ensure that the username isn't longer than 235 bytes, so that
964 // (at least for the builtin skins) user javascript and css files
965 // will work. (bug 23080)
966 if ( strlen( $name ) > 235 ) {
967 wfDebugLog( 'username', __METHOD__
.
968 ": '$name' invalid due to length" );
972 // Preg yells if you try to give it an empty string
973 if ( $wgInvalidUsernameCharacters !== '' ) {
974 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
975 wfDebugLog( 'username', __METHOD__
.
976 ": '$name' invalid due to wgInvalidUsernameCharacters" );
981 return self
::isUsableName( $name );
985 * Is the input a valid password for this user?
987 * @param string $password Desired password
990 public function isValidPassword( $password ) {
991 // simple boolean wrapper for getPasswordValidity
992 return $this->getPasswordValidity( $password ) === true;
996 * Given unvalidated password input, return error message on failure.
998 * @param string $password Desired password
999 * @return bool|string|array True on success, string or array of error message on failure
1001 public function getPasswordValidity( $password ) {
1002 $result = $this->checkPasswordValidity( $password );
1003 if ( $result->isGood() ) {
1007 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
1008 $messages[] = $error['message'];
1010 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
1011 $messages[] = $warning['message'];
1013 if ( count( $messages ) === 1 ) {
1014 return $messages[0];
1021 * Check if this is a valid password for this user
1023 * Create a Status object based on the password's validity.
1024 * The Status should be set to fatal if the user should not
1025 * be allowed to log in, and should have any errors that
1026 * would block changing the password.
1028 * If the return value of this is not OK, the password
1029 * should not be checked. If the return value is not Good,
1030 * the password can be checked, but the user should not be
1031 * able to set their password to this.
1033 * @param string $password Desired password
1034 * @param string $purpose one of 'login', 'create', 'reset'
1038 public function checkPasswordValidity( $password, $purpose = 'login' ) {
1039 global $wgPasswordPolicy;
1041 $upp = new UserPasswordPolicy(
1042 $wgPasswordPolicy['policies'],
1043 $wgPasswordPolicy['checks']
1046 $status = Status
::newGood();
1047 $result = false; // init $result to false for the internal checks
1049 if ( !Hooks
::run( 'isValidPassword', [ $password, &$result, $this ] ) ) {
1050 $status->error( $result );
1054 if ( $result === false ) {
1055 $status->merge( $upp->checkUserPassword( $this, $password, $purpose ) );
1057 } elseif ( $result === true ) {
1060 $status->error( $result );
1061 return $status; // the isValidPassword hook set a string $result and returned true
1066 * Given unvalidated user input, return a canonical username, or false if
1067 * the username is invalid.
1068 * @param string $name User input
1069 * @param string|bool $validate Type of validation to use:
1070 * - false No validation
1071 * - 'valid' Valid for batch processes
1072 * - 'usable' Valid for batch processes and login
1073 * - 'creatable' Valid for batch processes, login and account creation
1075 * @throws InvalidArgumentException
1076 * @return bool|string
1078 public static function getCanonicalName( $name, $validate = 'valid' ) {
1079 // Force usernames to capital
1081 $name = $wgContLang->ucfirst( $name );
1083 # Reject names containing '#'; these will be cleaned up
1084 # with title normalisation, but then it's too late to
1086 if ( strpos( $name, '#' ) !== false ) {
1090 // Clean up name according to title rules,
1091 // but only when validation is requested (bug 12654)
1092 $t = ( $validate !== false ) ?
1093 Title
::newFromText( $name, NS_USER
) : Title
::makeTitle( NS_USER
, $name );
1094 // Check for invalid titles
1095 if ( is_null( $t ) ||
$t->getNamespace() !== NS_USER ||
$t->isExternal() ) {
1099 // Reject various classes of invalid names
1100 $name = AuthManager
::callLegacyAuthPlugin(
1101 'getCanonicalName', [ $t->getText() ], $t->getText()
1104 switch ( $validate ) {
1108 if ( !User
::isValidUserName( $name ) ) {
1113 if ( !User
::isUsableName( $name ) ) {
1118 if ( !User
::isCreatableName( $name ) ) {
1123 throw new InvalidArgumentException(
1124 'Invalid parameter value for $validate in ' . __METHOD__
);
1130 * Count the number of edits of a user
1132 * @param int $uid User ID to check
1133 * @return int The user's edit count
1135 * @deprecated since 1.21 in favour of User::getEditCount
1137 public static function edits( $uid ) {
1138 wfDeprecated( __METHOD__
, '1.21' );
1139 $user = self
::newFromId( $uid );
1140 return $user->getEditCount();
1144 * Return a random password.
1146 * @deprecated since 1.27, use PasswordFactory::generateRandomPasswordString()
1147 * @return string New random password
1149 public static function randomPassword() {
1150 global $wgMinimalPasswordLength;
1151 return PasswordFactory
::generateRandomPasswordString( $wgMinimalPasswordLength );
1155 * Set cached properties to default.
1157 * @note This no longer clears uncached lazy-initialised properties;
1158 * the constructor does that instead.
1160 * @param string|bool $name
1162 public function loadDefaults( $name = false ) {
1164 $this->mName
= $name;
1165 $this->mRealName
= '';
1167 $this->mOptionOverrides
= null;
1168 $this->mOptionsLoaded
= false;
1170 $loggedOut = $this->mRequest
&& !defined( 'MW_NO_SESSION' )
1171 ?
$this->mRequest
->getSession()->getLoggedOutTimestamp() : 0;
1172 if ( $loggedOut !== 0 ) {
1173 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1175 $this->mTouched
= '1'; # Allow any pages to be cached
1178 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1179 $this->mEmailAuthenticated
= null;
1180 $this->mEmailToken
= '';
1181 $this->mEmailTokenExpires
= null;
1182 $this->mRegistration
= wfTimestamp( TS_MW
);
1183 $this->mGroups
= [];
1185 Hooks
::run( 'UserLoadDefaults', [ $this, $name ] );
1189 * Return whether an item has been loaded.
1191 * @param string $item Item to check. Current possibilities:
1195 * @param string $all 'all' to check if the whole object has been loaded
1196 * or any other string to check if only the item is available (e.g.
1200 public function isItemLoaded( $item, $all = 'all' ) {
1201 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1202 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1206 * Set that an item has been loaded
1208 * @param string $item
1210 protected function setItemLoaded( $item ) {
1211 if ( is_array( $this->mLoadedItems
) ) {
1212 $this->mLoadedItems
[$item] = true;
1217 * Load user data from the session.
1219 * @return bool True if the user is logged in, false otherwise.
1221 private function loadFromSession() {
1224 Hooks
::run( 'UserLoadFromSession', [ $this, &$result ], '1.27' );
1225 if ( $result !== null ) {
1229 // MediaWiki\Session\Session already did the necessary authentication of the user
1230 // returned here, so just use it if applicable.
1231 $session = $this->getRequest()->getSession();
1232 $user = $session->getUser();
1233 if ( $user->isLoggedIn() ) {
1234 $this->loadFromUserObject( $user );
1235 // Other code expects these to be set in the session, so set them.
1236 $session->set( 'wsUserID', $this->getId() );
1237 $session->set( 'wsUserName', $this->getName() );
1238 $session->set( 'wsToken', $this->getToken() );
1246 * Load user and user_group data from the database.
1247 * $this->mId must be set, this is how the user is identified.
1249 * @param integer $flags User::READ_* constant bitfield
1250 * @return bool True if the user exists, false if the user is anonymous
1252 public function loadFromDatabase( $flags = self
::READ_LATEST
) {
1254 $this->mId
= intval( $this->mId
);
1257 if ( !$this->mId
) {
1258 $this->loadDefaults();
1262 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
1263 $db = wfGetDB( $index );
1265 $s = $db->selectRow(
1267 self
::selectFields(),
1268 [ 'user_id' => $this->mId
],
1273 $this->queryFlagsUsed
= $flags;
1274 Hooks
::run( 'UserLoadFromDatabase', [ $this, &$s ] );
1276 if ( $s !== false ) {
1277 // Initialise user table data
1278 $this->loadFromRow( $s );
1279 $this->mGroups
= null; // deferred
1280 $this->getEditCount(); // revalidation for nulls
1285 $this->loadDefaults();
1291 * Initialize this object from a row from the user table.
1293 * @param stdClass $row Row from the user table to load.
1294 * @param array $data Further user data to load into the object
1296 * user_groups Array with groups out of the user_groups table
1297 * user_properties Array with properties out of the user_properties table
1299 protected function loadFromRow( $row, $data = null ) {
1302 $this->mGroups
= null; // deferred
1304 if ( isset( $row->user_name
) ) {
1305 $this->mName
= $row->user_name
;
1306 $this->mFrom
= 'name';
1307 $this->setItemLoaded( 'name' );
1312 if ( isset( $row->user_real_name
) ) {
1313 $this->mRealName
= $row->user_real_name
;
1314 $this->setItemLoaded( 'realname' );
1319 if ( isset( $row->user_id
) ) {
1320 $this->mId
= intval( $row->user_id
);
1321 $this->mFrom
= 'id';
1322 $this->setItemLoaded( 'id' );
1327 if ( isset( $row->user_id
) && isset( $row->user_name
) ) {
1328 self
::$idCacheByName[$row->user_name
] = $row->user_id
;
1331 if ( isset( $row->user_editcount
) ) {
1332 $this->mEditCount
= $row->user_editcount
;
1337 if ( isset( $row->user_touched
) ) {
1338 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1343 if ( isset( $row->user_token
) ) {
1344 // The definition for the column is binary(32), so trim the NULs
1345 // that appends. The previous definition was char(32), so trim
1347 $this->mToken
= rtrim( $row->user_token
, " \0" );
1348 if ( $this->mToken
=== '' ) {
1349 $this->mToken
= null;
1355 if ( isset( $row->user_email
) ) {
1356 $this->mEmail
= $row->user_email
;
1357 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1358 $this->mEmailToken
= $row->user_email_token
;
1359 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1360 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1366 $this->mLoadedItems
= true;
1369 if ( is_array( $data ) ) {
1370 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1371 $this->mGroups
= $data['user_groups'];
1373 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1374 $this->loadOptions( $data['user_properties'] );
1380 * Load the data for this user object from another user object.
1384 protected function loadFromUserObject( $user ) {
1386 $user->loadGroups();
1387 $user->loadOptions();
1388 foreach ( self
::$mCacheVars as $var ) {
1389 $this->$var = $user->$var;
1394 * Load the groups from the database if they aren't already loaded.
1396 private function loadGroups() {
1397 if ( is_null( $this->mGroups
) ) {
1398 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
1399 ?
wfGetDB( DB_MASTER
)
1400 : wfGetDB( DB_SLAVE
);
1401 $res = $db->select( 'user_groups',
1403 [ 'ug_user' => $this->mId
],
1405 $this->mGroups
= [];
1406 foreach ( $res as $row ) {
1407 $this->mGroups
[] = $row->ug_group
;
1413 * Add the user to the group if he/she meets given criteria.
1415 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1416 * possible to remove manually via Special:UserRights. In such case it
1417 * will not be re-added automatically. The user will also not lose the
1418 * group if they no longer meet the criteria.
1420 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1422 * @return array Array of groups the user has been promoted to.
1424 * @see $wgAutopromoteOnce
1426 public function addAutopromoteOnceGroups( $event ) {
1427 global $wgAutopromoteOnceLogInRC;
1429 if ( wfReadOnly() ||
!$this->getId() ) {
1433 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1434 if ( !count( $toPromote ) ) {
1438 if ( !$this->checkAndSetTouched() ) {
1439 return []; // raced out (bug T48834)
1442 $oldGroups = $this->getGroups(); // previous groups
1443 foreach ( $toPromote as $group ) {
1444 $this->addGroup( $group );
1446 // update groups in external authentication database
1447 Hooks
::run( 'UserGroupsChanged', [ $this, $toPromote, [], false, false ] );
1448 AuthManager
::callLegacyAuthPlugin( 'updateExternalDBGroups', [ $this, $toPromote ] );
1450 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1452 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1453 $logEntry->setPerformer( $this );
1454 $logEntry->setTarget( $this->getUserPage() );
1455 $logEntry->setParameters( [
1456 '4::oldgroups' => $oldGroups,
1457 '5::newgroups' => $newGroups,
1459 $logid = $logEntry->insert();
1460 if ( $wgAutopromoteOnceLogInRC ) {
1461 $logEntry->publish( $logid );
1468 * Bump user_touched if it didn't change since this object was loaded
1470 * On success, the mTouched field is updated.
1471 * The user serialization cache is always cleared.
1473 * @return bool Whether user_touched was actually updated
1476 protected function checkAndSetTouched() {
1479 if ( !$this->mId
) {
1480 return false; // anon
1483 // Get a new user_touched that is higher than the old one
1484 $oldTouched = $this->mTouched
;
1485 $newTouched = $this->newTouchedTimestamp();
1487 $dbw = wfGetDB( DB_MASTER
);
1488 $dbw->update( 'user',
1489 [ 'user_touched' => $dbw->timestamp( $newTouched ) ],
1491 'user_id' => $this->mId
,
1492 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
1496 $success = ( $dbw->affectedRows() > 0 );
1499 $this->mTouched
= $newTouched;
1500 $this->clearSharedCache();
1502 // Clears on failure too since that is desired if the cache is stale
1503 $this->clearSharedCache( 'refresh' );
1510 * Clear various cached data stored in this object. The cache of the user table
1511 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1513 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1514 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1516 public function clearInstanceCache( $reloadFrom = false ) {
1517 $this->mNewtalk
= -1;
1518 $this->mDatePreference
= null;
1519 $this->mBlockedby
= -1; # Unset
1520 $this->mHash
= false;
1521 $this->mRights
= null;
1522 $this->mEffectiveGroups
= null;
1523 $this->mImplicitGroups
= null;
1524 $this->mGroups
= null;
1525 $this->mOptions
= null;
1526 $this->mOptionsLoaded
= false;
1527 $this->mEditCount
= null;
1529 if ( $reloadFrom ) {
1530 $this->mLoadedItems
= [];
1531 $this->mFrom
= $reloadFrom;
1536 * Combine the language default options with any site-specific options
1537 * and add the default language variants.
1539 * @return array Array of String options
1541 public static function getDefaultOptions() {
1542 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1544 static $defOpt = null;
1545 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1546 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1547 // mid-request and see that change reflected in the return value of this function.
1548 // Which is insane and would never happen during normal MW operation
1552 $defOpt = $wgDefaultUserOptions;
1553 // Default language setting
1554 $defOpt['language'] = $wgContLang->getCode();
1555 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1556 $defOpt[$langCode == $wgContLang->getCode() ?
'variant' : "variant-$langCode"] = $langCode;
1558 $namespaces = MediaWikiServices
::getInstance()->getSearchEngineConfig()->searchableNamespaces();
1559 foreach ( $namespaces as $nsnum => $nsname ) {
1560 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1562 $defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1564 Hooks
::run( 'UserGetDefaultOptions', [ &$defOpt ] );
1570 * Get a given default option value.
1572 * @param string $opt Name of option to retrieve
1573 * @return string Default option value
1575 public static function getDefaultOption( $opt ) {
1576 $defOpts = self
::getDefaultOptions();
1577 if ( isset( $defOpts[$opt] ) ) {
1578 return $defOpts[$opt];
1585 * Get blocking information
1586 * @param bool $bFromSlave Whether to check the slave database first.
1587 * To improve performance, non-critical checks are done against slaves.
1588 * Check when actually saving should be done against master.
1590 private function getBlockedStatus( $bFromSlave = true ) {
1591 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1593 if ( -1 != $this->mBlockedby
) {
1597 wfDebug( __METHOD__
. ": checking...\n" );
1599 // Initialize data...
1600 // Otherwise something ends up stomping on $this->mBlockedby when
1601 // things get lazy-loaded later, causing false positive block hits
1602 // due to -1 !== 0. Probably session-related... Nothing should be
1603 // overwriting mBlockedby, surely?
1606 # We only need to worry about passing the IP address to the Block generator if the
1607 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1608 # know which IP address they're actually coming from
1610 if ( !$this->isAllowed( 'ipblock-exempt' ) ) {
1611 // $wgUser->getName() only works after the end of Setup.php. Until
1612 // then, assume it's a logged-out user.
1613 $globalUserName = $wgUser->isSafeToLoad()
1614 ?
$wgUser->getName()
1615 : IP
::sanitizeIP( $wgUser->getRequest()->getIP() );
1616 if ( $this->getName() === $globalUserName ) {
1617 $ip = $this->getRequest()->getIP();
1622 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1625 if ( !$block instanceof Block
&& $ip !== null && !in_array( $ip, $wgProxyWhitelist ) ) {
1627 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1629 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1630 $block->mReason
= wfMessage( 'proxyblockreason' )->text();
1631 $block->setTarget( $ip );
1632 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1634 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1635 $block->mReason
= wfMessage( 'sorbsreason' )->text();
1636 $block->setTarget( $ip );
1640 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1641 if ( !$block instanceof Block
1642 && $wgApplyIpBlocksToXff
1644 && !in_array( $ip, $wgProxyWhitelist )
1646 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1647 $xff = array_map( 'trim', explode( ',', $xff ) );
1648 $xff = array_diff( $xff, [ $ip ] );
1649 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1650 $block = Block
::chooseBlock( $xffblocks, $xff );
1651 if ( $block instanceof Block
) {
1652 # Mangle the reason to alert the user that the block
1653 # originated from matching the X-Forwarded-For header.
1654 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->text();
1658 if ( $block instanceof Block
) {
1659 wfDebug( __METHOD__
. ": Found block.\n" );
1660 $this->mBlock
= $block;
1661 $this->mBlockedby
= $block->getByName();
1662 $this->mBlockreason
= $block->mReason
;
1663 $this->mHideName
= $block->mHideName
;
1664 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1666 $this->mBlockedby
= '';
1667 $this->mHideName
= 0;
1668 $this->mAllowUsertalk
= false;
1672 Hooks
::run( 'GetBlockedStatus', [ &$this ] );
1677 * Whether the given IP is in a DNS blacklist.
1679 * @param string $ip IP to check
1680 * @param bool $checkWhitelist Whether to check the whitelist first
1681 * @return bool True if blacklisted.
1683 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1684 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1686 if ( !$wgEnableDnsBlacklist ) {
1690 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1694 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1698 * Whether the given IP is in a given DNS blacklist.
1700 * @param string $ip IP to check
1701 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1702 * @return bool True if blacklisted.
1704 public function inDnsBlacklist( $ip, $bases ) {
1707 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1708 if ( IP
::isIPv4( $ip ) ) {
1709 // Reverse IP, bug 21255
1710 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1712 foreach ( (array)$bases as $base ) {
1714 // If we have an access key, use that too (ProjectHoneypot, etc.)
1716 if ( is_array( $base ) ) {
1717 if ( count( $base ) >= 2 ) {
1718 // Access key is 1, base URL is 0
1719 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1721 $host = "$ipReversed.{$base[0]}";
1723 $basename = $base[0];
1725 $host = "$ipReversed.$base";
1729 $ipList = gethostbynamel( $host );
1732 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
1736 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
1745 * Check if an IP address is in the local proxy list
1751 public static function isLocallyBlockedProxy( $ip ) {
1752 global $wgProxyList;
1754 if ( !$wgProxyList ) {
1758 if ( !is_array( $wgProxyList ) ) {
1759 // Load from the specified file
1760 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1763 if ( !is_array( $wgProxyList ) ) {
1765 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1767 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1768 // Old-style flipped proxy list
1777 * Is this user subject to rate limiting?
1779 * @return bool True if rate limited
1781 public function isPingLimitable() {
1782 global $wgRateLimitsExcludedIPs;
1783 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1784 // No other good way currently to disable rate limits
1785 // for specific IPs. :P
1786 // But this is a crappy hack and should die.
1789 return !$this->isAllowed( 'noratelimit' );
1793 * Primitive rate limits: enforce maximum actions per time period
1794 * to put a brake on flooding.
1796 * The method generates both a generic profiling point and a per action one
1797 * (suffix being "-$action".
1799 * @note When using a shared cache like memcached, IP-address
1800 * last-hit counters will be shared across wikis.
1802 * @param string $action Action to enforce; 'edit' if unspecified
1803 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1804 * @return bool True if a rate limiter was tripped
1806 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1807 // Call the 'PingLimiter' hook
1809 if ( !Hooks
::run( 'PingLimiter', [ &$this, $action, &$result, $incrBy ] ) ) {
1813 global $wgRateLimits;
1814 if ( !isset( $wgRateLimits[$action] ) ) {
1818 // Some groups shouldn't trigger the ping limiter, ever
1819 if ( !$this->isPingLimitable() ) {
1823 $limits = $wgRateLimits[$action];
1825 $id = $this->getId();
1827 $isNewbie = $this->isNewbie();
1831 if ( isset( $limits['anon'] ) ) {
1832 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1835 // limits for logged-in users
1836 if ( isset( $limits['user'] ) ) {
1837 $userLimit = $limits['user'];
1839 // limits for newbie logged-in users
1840 if ( $isNewbie && isset( $limits['newbie'] ) ) {
1841 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1845 // limits for anons and for newbie logged-in users
1848 if ( isset( $limits['ip'] ) ) {
1849 $ip = $this->getRequest()->getIP();
1850 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1852 // subnet-based limits
1853 if ( isset( $limits['subnet'] ) ) {
1854 $ip = $this->getRequest()->getIP();
1855 $subnet = IP
::getSubnet( $ip );
1856 if ( $subnet !== false ) {
1857 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1862 // Check for group-specific permissions
1863 // If more than one group applies, use the group with the highest limit ratio (max/period)
1864 foreach ( $this->getGroups() as $group ) {
1865 if ( isset( $limits[$group] ) ) {
1866 if ( $userLimit === false
1867 ||
$limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1869 $userLimit = $limits[$group];
1874 // Set the user limit key
1875 if ( $userLimit !== false ) {
1876 list( $max, $period ) = $userLimit;
1877 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
1878 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1881 // ip-based limits for all ping-limitable users
1882 if ( isset( $limits['ip-all'] ) ) {
1883 $ip = $this->getRequest()->getIP();
1884 // ignore if user limit is more permissive
1885 if ( $isNewbie ||
$userLimit === false
1886 ||
$limits['ip-all'][0] / $limits['ip-all'][1] > $userLimit[0] / $userLimit[1] ) {
1887 $keys["mediawiki:limiter:$action:ip-all:$ip"] = $limits['ip-all'];
1891 // subnet-based limits for all ping-limitable users
1892 if ( isset( $limits['subnet-all'] ) ) {
1893 $ip = $this->getRequest()->getIP();
1894 $subnet = IP
::getSubnet( $ip );
1895 if ( $subnet !== false ) {
1896 // ignore if user limit is more permissive
1897 if ( $isNewbie ||
$userLimit === false
1898 ||
$limits['ip-all'][0] / $limits['ip-all'][1]
1899 > $userLimit[0] / $userLimit[1] ) {
1900 $keys["mediawiki:limiter:$action:subnet-all:$subnet"] = $limits['subnet-all'];
1905 $cache = ObjectCache
::getLocalClusterInstance();
1908 foreach ( $keys as $key => $limit ) {
1909 list( $max, $period ) = $limit;
1910 $summary = "(limit $max in {$period}s)";
1911 $count = $cache->get( $key );
1914 if ( $count >= $max ) {
1915 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1916 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1919 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1922 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1923 if ( $incrBy > 0 ) {
1924 $cache->add( $key, 0, intval( $period ) ); // first ping
1927 if ( $incrBy > 0 ) {
1928 $cache->incr( $key, $incrBy );
1936 * Check if user is blocked
1938 * @param bool $bFromSlave Whether to check the slave database instead of
1939 * the master. Hacked from false due to horrible probs on site.
1940 * @return bool True if blocked, false otherwise
1942 public function isBlocked( $bFromSlave = true ) {
1943 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
1947 * Get the block affecting the user, or null if the user is not blocked
1949 * @param bool $bFromSlave Whether to check the slave database instead of the master
1950 * @return Block|null
1952 public function getBlock( $bFromSlave = true ) {
1953 $this->getBlockedStatus( $bFromSlave );
1954 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
1958 * Check if user is blocked from editing a particular article
1960 * @param Title $title Title to check
1961 * @param bool $bFromSlave Whether to check the slave database instead of the master
1964 public function isBlockedFrom( $title, $bFromSlave = false ) {
1965 global $wgBlockAllowsUTEdit;
1967 $blocked = $this->isBlocked( $bFromSlave );
1968 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
1969 // If a user's name is suppressed, they cannot make edits anywhere
1970 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName()
1971 && $title->getNamespace() == NS_USER_TALK
) {
1973 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
1976 Hooks
::run( 'UserIsBlockedFrom', [ $this, $title, &$blocked, &$allowUsertalk ] );
1982 * If user is blocked, return the name of the user who placed the block
1983 * @return string Name of blocker
1985 public function blockedBy() {
1986 $this->getBlockedStatus();
1987 return $this->mBlockedby
;
1991 * If user is blocked, return the specified reason for the block
1992 * @return string Blocking reason
1994 public function blockedFor() {
1995 $this->getBlockedStatus();
1996 return $this->mBlockreason
;
2000 * If user is blocked, return the ID for the block
2001 * @return int Block ID
2003 public function getBlockId() {
2004 $this->getBlockedStatus();
2005 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
2009 * Check if user is blocked on all wikis.
2010 * Do not use for actual edit permission checks!
2011 * This is intended for quick UI checks.
2013 * @param string $ip IP address, uses current client if none given
2014 * @return bool True if blocked, false otherwise
2016 public function isBlockedGlobally( $ip = '' ) {
2017 return $this->getGlobalBlock( $ip ) instanceof Block
;
2021 * Check if user is blocked on all wikis.
2022 * Do not use for actual edit permission checks!
2023 * This is intended for quick UI checks.
2025 * @param string $ip IP address, uses current client if none given
2026 * @return Block|null Block object if blocked, null otherwise
2027 * @throws FatalError
2028 * @throws MWException
2030 public function getGlobalBlock( $ip = '' ) {
2031 if ( $this->mGlobalBlock
!== null ) {
2032 return $this->mGlobalBlock ?
: null;
2034 // User is already an IP?
2035 if ( IP
::isIPAddress( $this->getName() ) ) {
2036 $ip = $this->getName();
2038 $ip = $this->getRequest()->getIP();
2042 Hooks
::run( 'UserIsBlockedGlobally', [ &$this, $ip, &$blocked, &$block ] );
2044 if ( $blocked && $block === null ) {
2045 // back-compat: UserIsBlockedGlobally didn't have $block param first
2047 $block->setTarget( $ip );
2050 $this->mGlobalBlock
= $blocked ?
$block : false;
2051 return $this->mGlobalBlock ?
: null;
2055 * Check if user account is locked
2057 * @return bool True if locked, false otherwise
2059 public function isLocked() {
2060 if ( $this->mLocked
!== null ) {
2061 return $this->mLocked
;
2063 $authUser = AuthManager
::callLegacyAuthPlugin( 'getUserInstance', [ &$this ], null );
2064 $this->mLocked
= $authUser && $authUser->isLocked();
2065 Hooks
::run( 'UserIsLocked', [ $this, &$this->mLocked
] );
2066 return $this->mLocked
;
2070 * Check if user account is hidden
2072 * @return bool True if hidden, false otherwise
2074 public function isHidden() {
2075 if ( $this->mHideName
!== null ) {
2076 return $this->mHideName
;
2078 $this->getBlockedStatus();
2079 if ( !$this->mHideName
) {
2080 $authUser = AuthManager
::callLegacyAuthPlugin( 'getUserInstance', [ &$this ], null );
2081 $this->mHideName
= $authUser && $authUser->isHidden();
2082 Hooks
::run( 'UserIsHidden', [ $this, &$this->mHideName
] );
2084 return $this->mHideName
;
2088 * Get the user's ID.
2089 * @return int The user's ID; 0 if the user is anonymous or nonexistent
2091 public function getId() {
2092 if ( $this->mId
=== null && $this->mName
!== null && User
::isIP( $this->mName
) ) {
2093 // Special case, we know the user is anonymous
2095 } elseif ( !$this->isItemLoaded( 'id' ) ) {
2096 // Don't load if this was initialized from an ID
2100 return (int)$this->mId
;
2104 * Set the user and reload all fields according to a given ID
2105 * @param int $v User ID to reload
2107 public function setId( $v ) {
2109 $this->clearInstanceCache( 'id' );
2113 * Get the user name, or the IP of an anonymous user
2114 * @return string User's name or IP address
2116 public function getName() {
2117 if ( $this->isItemLoaded( 'name', 'only' ) ) {
2118 // Special case optimisation
2119 return $this->mName
;
2122 if ( $this->mName
=== false ) {
2124 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
2126 return $this->mName
;
2131 * Set the user name.
2133 * This does not reload fields from the database according to the given
2134 * name. Rather, it is used to create a temporary "nonexistent user" for
2135 * later addition to the database. It can also be used to set the IP
2136 * address for an anonymous user to something other than the current
2139 * @note User::newFromName() has roughly the same function, when the named user
2141 * @param string $str New user name to set
2143 public function setName( $str ) {
2145 $this->mName
= $str;
2149 * Get the user's name escaped by underscores.
2150 * @return string Username escaped by underscores.
2152 public function getTitleKey() {
2153 return str_replace( ' ', '_', $this->getName() );
2157 * Check if the user has new messages.
2158 * @return bool True if the user has new messages
2160 public function getNewtalk() {
2163 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2164 if ( $this->mNewtalk
=== -1 ) {
2165 $this->mNewtalk
= false; # reset talk page status
2167 // Check memcached separately for anons, who have no
2168 // entire User object stored in there.
2169 if ( !$this->mId
) {
2170 global $wgDisableAnonTalk;
2171 if ( $wgDisableAnonTalk ) {
2172 // Anon newtalk disabled by configuration.
2173 $this->mNewtalk
= false;
2175 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
2178 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2182 return (bool)$this->mNewtalk
;
2186 * Return the data needed to construct links for new talk page message
2187 * alerts. If there are new messages, this will return an associative array
2188 * with the following data:
2189 * wiki: The database name of the wiki
2190 * link: Root-relative link to the user's talk page
2191 * rev: The last talk page revision that the user has seen or null. This
2192 * is useful for building diff links.
2193 * If there are no new messages, it returns an empty array.
2194 * @note This function was designed to accomodate multiple talk pages, but
2195 * currently only returns a single link and revision.
2198 public function getNewMessageLinks() {
2200 if ( !Hooks
::run( 'UserRetrieveNewTalks', [ &$this, &$talks ] ) ) {
2202 } elseif ( !$this->getNewtalk() ) {
2205 $utp = $this->getTalkPage();
2206 $dbr = wfGetDB( DB_SLAVE
);
2207 // Get the "last viewed rev" timestamp from the oldest message notification
2208 $timestamp = $dbr->selectField( 'user_newtalk',
2209 'MIN(user_last_timestamp)',
2210 $this->isAnon() ?
[ 'user_ip' => $this->getName() ] : [ 'user_id' => $this->getId() ],
2212 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2213 return [ [ 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ] ];
2217 * Get the revision ID for the last talk page revision viewed by the talk
2219 * @return int|null Revision ID or null
2221 public function getNewMessageRevisionId() {
2222 $newMessageRevisionId = null;
2223 $newMessageLinks = $this->getNewMessageLinks();
2224 if ( $newMessageLinks ) {
2225 // Note: getNewMessageLinks() never returns more than a single link
2226 // and it is always for the same wiki, but we double-check here in
2227 // case that changes some time in the future.
2228 if ( count( $newMessageLinks ) === 1
2229 && $newMessageLinks[0]['wiki'] === wfWikiID()
2230 && $newMessageLinks[0]['rev']
2232 /** @var Revision $newMessageRevision */
2233 $newMessageRevision = $newMessageLinks[0]['rev'];
2234 $newMessageRevisionId = $newMessageRevision->getId();
2237 return $newMessageRevisionId;
2241 * Internal uncached check for new messages
2244 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2245 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2246 * @return bool True if the user has new messages
2248 protected function checkNewtalk( $field, $id ) {
2249 $dbr = wfGetDB( DB_SLAVE
);
2251 $ok = $dbr->selectField( 'user_newtalk', $field, [ $field => $id ], __METHOD__
);
2253 return $ok !== false;
2257 * Add or update the new messages flag
2258 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2259 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2260 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2261 * @return bool True if successful, false otherwise
2263 protected function updateNewtalk( $field, $id, $curRev = null ) {
2264 // Get timestamp of the talk page revision prior to the current one
2265 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2266 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2267 // Mark the user as having new messages since this revision
2268 $dbw = wfGetDB( DB_MASTER
);
2269 $dbw->insert( 'user_newtalk',
2270 [ $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ],
2273 if ( $dbw->affectedRows() ) {
2274 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2277 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2283 * Clear the new messages flag for the given user
2284 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2285 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2286 * @return bool True if successful, false otherwise
2288 protected function deleteNewtalk( $field, $id ) {
2289 $dbw = wfGetDB( DB_MASTER
);
2290 $dbw->delete( 'user_newtalk',
2293 if ( $dbw->affectedRows() ) {
2294 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2297 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2303 * Update the 'You have new messages!' status.
2304 * @param bool $val Whether the user has new messages
2305 * @param Revision $curRev New, as yet unseen revision of the user talk
2306 * page. Ignored if null or !$val.
2308 public function setNewtalk( $val, $curRev = null ) {
2309 if ( wfReadOnly() ) {
2314 $this->mNewtalk
= $val;
2316 if ( $this->isAnon() ) {
2318 $id = $this->getName();
2321 $id = $this->getId();
2325 $changed = $this->updateNewtalk( $field, $id, $curRev );
2327 $changed = $this->deleteNewtalk( $field, $id );
2331 $this->invalidateCache();
2336 * Generate a current or new-future timestamp to be stored in the
2337 * user_touched field when we update things.
2338 * @return string Timestamp in TS_MW format
2340 private function newTouchedTimestamp() {
2341 global $wgClockSkewFudge;
2343 $time = wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2344 if ( $this->mTouched
&& $time <= $this->mTouched
) {
2345 $time = wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $this->mTouched
) +
1 );
2352 * Clear user data from memcached
2354 * Use after applying updates to the database; caller's
2355 * responsibility to update user_touched if appropriate.
2357 * Called implicitly from invalidateCache() and saveSettings().
2359 * @param string $mode Use 'refresh' to clear now; otherwise before DB commit
2361 public function clearSharedCache( $mode = 'changed' ) {
2362 if ( !$this->getId() ) {
2366 $cache = ObjectCache
::getMainWANInstance();
2367 $processCache = self
::getInProcessCache();
2368 $key = $this->getCacheKey( $cache );
2369 if ( $mode === 'refresh' ) {
2370 $cache->delete( $key, 1 );
2371 $processCache->delete( $key );
2373 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle(
2374 function() use ( $cache, $processCache, $key ) {
2375 $cache->delete( $key );
2376 $processCache->delete( $key );
2383 * Immediately touch the user data cache for this account
2385 * Calls touch() and removes account data from memcached
2387 public function invalidateCache() {
2389 $this->clearSharedCache();
2393 * Update the "touched" timestamp for the user
2395 * This is useful on various login/logout events when making sure that
2396 * a browser or proxy that has multiple tenants does not suffer cache
2397 * pollution where the new user sees the old users content. The value
2398 * of getTouched() is checked when determining 304 vs 200 responses.
2399 * Unlike invalidateCache(), this preserves the User object cache and
2400 * avoids database writes.
2404 public function touch() {
2405 $id = $this->getId();
2407 $key = wfMemcKey( 'user-quicktouched', 'id', $id );
2408 ObjectCache
::getMainWANInstance()->touchCheckKey( $key );
2409 $this->mQuickTouched
= null;
2414 * Validate the cache for this account.
2415 * @param string $timestamp A timestamp in TS_MW format
2418 public function validateCache( $timestamp ) {
2419 return ( $timestamp >= $this->getTouched() );
2423 * Get the user touched timestamp
2425 * Use this value only to validate caches via inequalities
2426 * such as in the case of HTTP If-Modified-Since response logic
2428 * @return string TS_MW Timestamp
2430 public function getTouched() {
2434 if ( $this->mQuickTouched
=== null ) {
2435 $key = wfMemcKey( 'user-quicktouched', 'id', $this->mId
);
2436 $cache = ObjectCache
::getMainWANInstance();
2438 $this->mQuickTouched
= wfTimestamp( TS_MW
, $cache->getCheckKeyTime( $key ) );
2441 return max( $this->mTouched
, $this->mQuickTouched
);
2444 return $this->mTouched
;
2448 * Get the user_touched timestamp field (time of last DB updates)
2449 * @return string TS_MW Timestamp
2452 public function getDBTouched() {
2455 return $this->mTouched
;
2459 * @deprecated Removed in 1.27.
2463 public function getPassword() {
2464 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2468 * @deprecated Removed in 1.27.
2472 public function getTemporaryPassword() {
2473 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2477 * Set the password and reset the random token.
2478 * Calls through to authentication plugin if necessary;
2479 * will have no effect if the auth plugin refuses to
2480 * pass the change through or if the legal password
2483 * As a special case, setting the password to null
2484 * wipes it, so the account cannot be logged in until
2485 * a new password is set, for instance via e-mail.
2487 * @deprecated since 1.27, use AuthManager instead
2488 * @param string $str New password to set
2489 * @throws PasswordError On failure
2492 public function setPassword( $str ) {
2493 global $wgAuth, $wgDisableAuthManager;
2495 if ( !$wgDisableAuthManager ) {
2496 return $this->setPasswordInternal( $str );
2499 if ( $str !== null ) {
2500 if ( !$wgAuth->allowPasswordChange() ) {
2501 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2504 $status = $this->checkPasswordValidity( $str );
2505 if ( !$status->isGood() ) {
2506 throw new PasswordError( $status->getMessage()->text() );
2510 if ( !$wgAuth->setPassword( $this, $str ) ) {
2511 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2514 $this->setOption( 'watchlisttoken', false );
2515 $this->setPasswordInternal( $str );
2521 * Set the password and reset the random token unconditionally.
2523 * @deprecated since 1.27, use AuthManager instead
2524 * @param string|null $str New password to set or null to set an invalid
2525 * password hash meaning that the user will not be able to log in
2526 * through the web interface.
2528 public function setInternalPassword( $str ) {
2529 global $wgAuth, $wgDisableAuthManager;
2531 if ( !$wgDisableAuthManager ) {
2532 $this->setPasswordInternal( $str );
2535 if ( $wgAuth->allowSetLocalPassword() ) {
2536 $this->setOption( 'watchlisttoken', false );
2537 $this->setPasswordInternal( $str );
2542 * Actually set the password and such
2543 * @since 1.27 cannot set a password for a user not in the database
2544 * @param string|null $str New password to set or null to set an invalid
2545 * password hash meaning that the user will not be able to log in
2546 * through the web interface.
2547 * @return bool Success
2549 private function setPasswordInternal( $str ) {
2550 global $wgDisableAuthManager;
2552 if ( $wgDisableAuthManager ) {
2553 $id = self
::idFromName( $this->getName(), self
::READ_LATEST
);
2555 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2558 $passwordFactory = new PasswordFactory();
2559 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
2560 $dbw = wfGetDB( DB_MASTER
);
2564 'user_password' => $passwordFactory->newFromPlaintext( $str )->toString(),
2565 'user_newpassword' => PasswordFactory
::newInvalidPassword()->toString(),
2566 'user_newpass_time' => $dbw->timestampOrNull( null ),
2574 // When the main password is changed, invalidate all bot passwords too
2575 BotPassword
::invalidateAllPasswordsForUser( $this->getName() );
2577 $manager = AuthManager
::singleton();
2579 // If the user doesn't exist yet, fail
2580 if ( !$manager->userExists( $this->getName() ) ) {
2581 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2585 'username' => $this->getName(),
2589 $reqs = $manager->getAuthenticationRequests( AuthManager
::ACTION_CHANGE
, $this );
2590 $reqs = AuthenticationRequest
::loadRequestsFromSubmission( $reqs, $data );
2591 foreach ( $reqs as $req ) {
2592 $status = $manager->allowsAuthenticationDataChange( $req );
2593 if ( !$status->isOk() ) {
2594 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
2595 ->info( __METHOD__
. ': Password change rejected: ' . $status->getWikiText() );
2599 foreach ( $reqs as $req ) {
2600 $manager->changeAuthenticationData( $req );
2603 $this->setOption( 'watchlisttoken', false );
2606 SessionManager
::singleton()->invalidateSessionsForUser( $this );
2612 * Get the user's current token.
2613 * @param bool $forceCreation Force the generation of a new token if the
2614 * user doesn't have one (default=true for backwards compatibility).
2615 * @return string|null Token
2617 public function getToken( $forceCreation = true ) {
2618 global $wgAuthenticationTokenVersion;
2621 if ( !$this->mToken
&& $forceCreation ) {
2625 if ( !$this->mToken
) {
2626 // The user doesn't have a token, return null to indicate that.
2628 } elseif ( $this->mToken
=== self
::INVALID_TOKEN
) {
2629 // We return a random value here so existing token checks are very
2631 return MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2632 } elseif ( $wgAuthenticationTokenVersion === null ) {
2633 // $wgAuthenticationTokenVersion not in use, so return the raw secret
2634 return $this->mToken
;
2636 // $wgAuthenticationTokenVersion in use, so hmac it.
2637 $ret = MWCryptHash
::hmac( $wgAuthenticationTokenVersion, $this->mToken
, false );
2639 // The raw hash can be overly long. Shorten it up.
2640 $len = max( 32, self
::TOKEN_LENGTH
);
2641 if ( strlen( $ret ) < $len ) {
2642 // Should never happen, even md5 is 128 bits
2643 throw new \
UnexpectedValueException( 'Hmac returned less than 128 bits' );
2645 return substr( $ret, -$len );
2650 * Set the random token (used for persistent authentication)
2651 * Called from loadDefaults() among other places.
2653 * @param string|bool $token If specified, set the token to this value
2655 public function setToken( $token = false ) {
2657 if ( $this->mToken
=== self
::INVALID_TOKEN
) {
2658 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
2659 ->debug( __METHOD__
. ": Ignoring attempt to set token for system user \"$this\"" );
2660 } elseif ( !$token ) {
2661 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2663 $this->mToken
= $token;
2668 * Set the password for a password reminder or new account email
2670 * @deprecated since 1.27. Some way to do this via AuthManager (probably
2671 * involving TemporaryPasswordAuthenticationRequest) has yet to be
2673 * @param string $str New password to set or null to set an invalid
2674 * password hash meaning that the user will not be able to use it
2675 * @param bool $throttle If true, reset the throttle timestamp to the present
2677 public function setNewpassword( $str, $throttle = true ) {
2678 global $wgDisableAuthManager;
2680 if ( $wgDisableAuthManager ) {
2681 $id = $this->getId();
2683 throw new LogicException( 'Cannot set new password for a user that is not in the database.' );
2686 $dbw = wfGetDB( DB_MASTER
);
2688 $passwordFactory = new PasswordFactory();
2689 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
2691 'user_newpassword' => $passwordFactory->newFromPlaintext( $str )->toString(),
2694 if ( $str === null ) {
2695 $update['user_newpass_time'] = null;
2696 } elseif ( $throttle ) {
2697 $update['user_newpass_time'] = $dbw->timestamp();
2700 $dbw->update( 'user', $update, [ 'user_id' => $id ], __METHOD__
);
2702 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2707 * Has password reminder email been sent within the last
2708 * $wgPasswordReminderResendTime hours?
2709 * @deprecated Removed in 1.27. See above.
2712 public function isPasswordReminderThrottled() {
2713 global $wgPasswordReminderResendTime, $wgDisableAuthManager;
2715 if ( $wgDisableAuthManager ) {
2716 if ( !$wgPasswordReminderResendTime ) {
2722 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
2723 ?
wfGetDB( DB_MASTER
)
2724 : wfGetDB( DB_SLAVE
);
2725 $newpassTime = $db->selectField(
2727 'user_newpass_time',
2728 [ 'user_id' => $this->getId() ],
2732 if ( $newpassTime === null ) {
2735 $expiry = wfTimestamp( TS_UNIX
, $newpassTime ) +
$wgPasswordReminderResendTime * 3600;
2736 return time() < $expiry;
2738 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2743 * Get the user's e-mail address
2744 * @return string User's email address
2746 public function getEmail() {
2748 Hooks
::run( 'UserGetEmail', [ $this, &$this->mEmail
] );
2749 return $this->mEmail
;
2753 * Get the timestamp of the user's e-mail authentication
2754 * @return string TS_MW timestamp
2756 public function getEmailAuthenticationTimestamp() {
2758 Hooks
::run( 'UserGetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
2759 return $this->mEmailAuthenticated
;
2763 * Set the user's e-mail address
2764 * @param string $str New e-mail address
2766 public function setEmail( $str ) {
2768 if ( $str == $this->mEmail
) {
2771 $this->invalidateEmail();
2772 $this->mEmail
= $str;
2773 Hooks
::run( 'UserSetEmail', [ $this, &$this->mEmail
] );
2777 * Set the user's e-mail address and a confirmation mail if needed.
2780 * @param string $str New e-mail address
2783 public function setEmailWithConfirmation( $str ) {
2784 global $wgEnableEmail, $wgEmailAuthentication;
2786 if ( !$wgEnableEmail ) {
2787 return Status
::newFatal( 'emaildisabled' );
2790 $oldaddr = $this->getEmail();
2791 if ( $str === $oldaddr ) {
2792 return Status
::newGood( true );
2795 $type = $oldaddr != '' ?
'changed' : 'set';
2796 $notificationResult = null;
2798 if ( $wgEmailAuthentication ) {
2799 // Send the user an email notifying the user of the change in registered
2800 // email address on their previous email address
2801 if ( $type == 'changed' ) {
2802 $change = $str != '' ?
'changed' : 'removed';
2803 $notificationResult = $this->sendMail(
2804 wfMessage( 'notificationemail_subject_' . $change )->text(),
2805 wfMessage( 'notificationemail_body_' . $change,
2806 $this->getRequest()->getIP(),
2813 $this->setEmail( $str );
2815 if ( $str !== '' && $wgEmailAuthentication ) {
2816 // Send a confirmation request to the new address if needed
2817 $result = $this->sendConfirmationMail( $type );
2819 if ( $notificationResult !== null ) {
2820 $result->merge( $notificationResult );
2823 if ( $result->isGood() ) {
2824 // Say to the caller that a confirmation and notification mail has been sent
2825 $result->value
= 'eauth';
2828 $result = Status
::newGood( true );
2835 * Get the user's real name
2836 * @return string User's real name
2838 public function getRealName() {
2839 if ( !$this->isItemLoaded( 'realname' ) ) {
2843 return $this->mRealName
;
2847 * Set the user's real name
2848 * @param string $str New real name
2850 public function setRealName( $str ) {
2852 $this->mRealName
= $str;
2856 * Get the user's current setting for a given option.
2858 * @param string $oname The option to check
2859 * @param string $defaultOverride A default value returned if the option does not exist
2860 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2861 * @return string User's current value for the option
2862 * @see getBoolOption()
2863 * @see getIntOption()
2865 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2866 global $wgHiddenPrefs;
2867 $this->loadOptions();
2869 # We want 'disabled' preferences to always behave as the default value for
2870 # users, even if they have set the option explicitly in their settings (ie they
2871 # set it, and then it was disabled removing their ability to change it). But
2872 # we don't want to erase the preferences in the database in case the preference
2873 # is re-enabled again. So don't touch $mOptions, just override the returned value
2874 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2875 return self
::getDefaultOption( $oname );
2878 if ( array_key_exists( $oname, $this->mOptions
) ) {
2879 return $this->mOptions
[$oname];
2881 return $defaultOverride;
2886 * Get all user's options
2888 * @param int $flags Bitwise combination of:
2889 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2890 * to the default value. (Since 1.25)
2893 public function getOptions( $flags = 0 ) {
2894 global $wgHiddenPrefs;
2895 $this->loadOptions();
2896 $options = $this->mOptions
;
2898 # We want 'disabled' preferences to always behave as the default value for
2899 # users, even if they have set the option explicitly in their settings (ie they
2900 # set it, and then it was disabled removing their ability to change it). But
2901 # we don't want to erase the preferences in the database in case the preference
2902 # is re-enabled again. So don't touch $mOptions, just override the returned value
2903 foreach ( $wgHiddenPrefs as $pref ) {
2904 $default = self
::getDefaultOption( $pref );
2905 if ( $default !== null ) {
2906 $options[$pref] = $default;
2910 if ( $flags & self
::GETOPTIONS_EXCLUDE_DEFAULTS
) {
2911 $options = array_diff_assoc( $options, self
::getDefaultOptions() );
2918 * Get the user's current setting for a given option, as a boolean value.
2920 * @param string $oname The option to check
2921 * @return bool User's current value for the option
2924 public function getBoolOption( $oname ) {
2925 return (bool)$this->getOption( $oname );
2929 * Get the user's current setting for a given option, as an integer value.
2931 * @param string $oname The option to check
2932 * @param int $defaultOverride A default value returned if the option does not exist
2933 * @return int User's current value for the option
2936 public function getIntOption( $oname, $defaultOverride = 0 ) {
2937 $val = $this->getOption( $oname );
2939 $val = $defaultOverride;
2941 return intval( $val );
2945 * Set the given option for a user.
2947 * You need to call saveSettings() to actually write to the database.
2949 * @param string $oname The option to set
2950 * @param mixed $val New value to set
2952 public function setOption( $oname, $val ) {
2953 $this->loadOptions();
2955 // Explicitly NULL values should refer to defaults
2956 if ( is_null( $val ) ) {
2957 $val = self
::getDefaultOption( $oname );
2960 $this->mOptions
[$oname] = $val;
2964 * Get a token stored in the preferences (like the watchlist one),
2965 * resetting it if it's empty (and saving changes).
2967 * @param string $oname The option name to retrieve the token from
2968 * @return string|bool User's current value for the option, or false if this option is disabled.
2969 * @see resetTokenFromOption()
2971 * @deprecated 1.26 Applications should use the OAuth extension
2973 public function getTokenFromOption( $oname ) {
2974 global $wgHiddenPrefs;
2976 $id = $this->getId();
2977 if ( !$id ||
in_array( $oname, $wgHiddenPrefs ) ) {
2981 $token = $this->getOption( $oname );
2983 // Default to a value based on the user token to avoid space
2984 // wasted on storing tokens for all users. When this option
2985 // is set manually by the user, only then is it stored.
2986 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
2993 * Reset a token stored in the preferences (like the watchlist one).
2994 * *Does not* save user's preferences (similarly to setOption()).
2996 * @param string $oname The option name to reset the token in
2997 * @return string|bool New token value, or false if this option is disabled.
2998 * @see getTokenFromOption()
3001 public function resetTokenFromOption( $oname ) {
3002 global $wgHiddenPrefs;
3003 if ( in_array( $oname, $wgHiddenPrefs ) ) {
3007 $token = MWCryptRand
::generateHex( 40 );
3008 $this->setOption( $oname, $token );
3013 * Return a list of the types of user options currently returned by
3014 * User::getOptionKinds().
3016 * Currently, the option kinds are:
3017 * - 'registered' - preferences which are registered in core MediaWiki or
3018 * by extensions using the UserGetDefaultOptions hook.
3019 * - 'registered-multiselect' - as above, using the 'multiselect' type.
3020 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
3021 * - 'userjs' - preferences with names starting with 'userjs-', intended to
3022 * be used by user scripts.
3023 * - 'special' - "preferences" that are not accessible via User::getOptions
3024 * or User::setOptions.
3025 * - 'unused' - preferences about which MediaWiki doesn't know anything.
3026 * These are usually legacy options, removed in newer versions.
3028 * The API (and possibly others) use this function to determine the possible
3029 * option types for validation purposes, so make sure to update this when a
3030 * new option kind is added.
3032 * @see User::getOptionKinds
3033 * @return array Option kinds
3035 public static function listOptionKinds() {
3038 'registered-multiselect',
3039 'registered-checkmatrix',
3047 * Return an associative array mapping preferences keys to the kind of a preference they're
3048 * used for. Different kinds are handled differently when setting or reading preferences.
3050 * See User::listOptionKinds for the list of valid option types that can be provided.
3052 * @see User::listOptionKinds
3053 * @param IContextSource $context
3054 * @param array $options Assoc. array with options keys to check as keys.
3055 * Defaults to $this->mOptions.
3056 * @return array The key => kind mapping data
3058 public function getOptionKinds( IContextSource
$context, $options = null ) {
3059 $this->loadOptions();
3060 if ( $options === null ) {
3061 $options = $this->mOptions
;
3064 $prefs = Preferences
::getPreferences( $this, $context );
3067 // Pull out the "special" options, so they don't get converted as
3068 // multiselect or checkmatrix.
3069 $specialOptions = array_fill_keys( Preferences
::getSaveBlacklist(), true );
3070 foreach ( $specialOptions as $name => $value ) {
3071 unset( $prefs[$name] );
3074 // Multiselect and checkmatrix options are stored in the database with
3075 // one key per option, each having a boolean value. Extract those keys.
3076 $multiselectOptions = [];
3077 foreach ( $prefs as $name => $info ) {
3078 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
3079 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
3080 $opts = HTMLFormField
::flattenOptions( $info['options'] );
3081 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
3083 foreach ( $opts as $value ) {
3084 $multiselectOptions["$prefix$value"] = true;
3087 unset( $prefs[$name] );
3090 $checkmatrixOptions = [];
3091 foreach ( $prefs as $name => $info ) {
3092 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
3093 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
3094 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
3095 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
3096 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
3098 foreach ( $columns as $column ) {
3099 foreach ( $rows as $row ) {
3100 $checkmatrixOptions["$prefix$column-$row"] = true;
3104 unset( $prefs[$name] );
3108 // $value is ignored
3109 foreach ( $options as $key => $value ) {
3110 if ( isset( $prefs[$key] ) ) {
3111 $mapping[$key] = 'registered';
3112 } elseif ( isset( $multiselectOptions[$key] ) ) {
3113 $mapping[$key] = 'registered-multiselect';
3114 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
3115 $mapping[$key] = 'registered-checkmatrix';
3116 } elseif ( isset( $specialOptions[$key] ) ) {
3117 $mapping[$key] = 'special';
3118 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
3119 $mapping[$key] = 'userjs';
3121 $mapping[$key] = 'unused';
3129 * Reset certain (or all) options to the site defaults
3131 * The optional parameter determines which kinds of preferences will be reset.
3132 * Supported values are everything that can be reported by getOptionKinds()
3133 * and 'all', which forces a reset of *all* preferences and overrides everything else.
3135 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
3136 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
3137 * for backwards-compatibility.
3138 * @param IContextSource|null $context Context source used when $resetKinds
3139 * does not contain 'all', passed to getOptionKinds().
3140 * Defaults to RequestContext::getMain() when null.
3142 public function resetOptions(
3143 $resetKinds = [ 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ],
3144 IContextSource
$context = null
3147 $defaultOptions = self
::getDefaultOptions();
3149 if ( !is_array( $resetKinds ) ) {
3150 $resetKinds = [ $resetKinds ];
3153 if ( in_array( 'all', $resetKinds ) ) {
3154 $newOptions = $defaultOptions;
3156 if ( $context === null ) {
3157 $context = RequestContext
::getMain();
3160 $optionKinds = $this->getOptionKinds( $context );
3161 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
3164 // Use default values for the options that should be deleted, and
3165 // copy old values for the ones that shouldn't.
3166 foreach ( $this->mOptions
as $key => $value ) {
3167 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
3168 if ( array_key_exists( $key, $defaultOptions ) ) {
3169 $newOptions[$key] = $defaultOptions[$key];
3172 $newOptions[$key] = $value;
3177 Hooks
::run( 'UserResetAllOptions', [ $this, &$newOptions, $this->mOptions
, $resetKinds ] );
3179 $this->mOptions
= $newOptions;
3180 $this->mOptionsLoaded
= true;
3184 * Get the user's preferred date format.
3185 * @return string User's preferred date format
3187 public function getDatePreference() {
3188 // Important migration for old data rows
3189 if ( is_null( $this->mDatePreference
) ) {
3191 $value = $this->getOption( 'date' );
3192 $map = $wgLang->getDatePreferenceMigrationMap();
3193 if ( isset( $map[$value] ) ) {
3194 $value = $map[$value];
3196 $this->mDatePreference
= $value;
3198 return $this->mDatePreference
;
3202 * Determine based on the wiki configuration and the user's options,
3203 * whether this user must be over HTTPS no matter what.
3207 public function requiresHTTPS() {
3208 global $wgSecureLogin;
3209 if ( !$wgSecureLogin ) {
3212 $https = $this->getBoolOption( 'prefershttps' );
3213 Hooks
::run( 'UserRequiresHTTPS', [ $this, &$https ] );
3215 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
3222 * Get the user preferred stub threshold
3226 public function getStubThreshold() {
3227 global $wgMaxArticleSize; # Maximum article size, in Kb
3228 $threshold = $this->getIntOption( 'stubthreshold' );
3229 if ( $threshold > $wgMaxArticleSize * 1024 ) {
3230 // If they have set an impossible value, disable the preference
3231 // so we can use the parser cache again.
3238 * Get the permissions this user has.
3239 * @return array Array of String permission names
3241 public function getRights() {
3242 if ( is_null( $this->mRights
) ) {
3243 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
3245 // Deny any rights denied by the user's session, unless this
3246 // endpoint has no sessions.
3247 if ( !defined( 'MW_NO_SESSION' ) ) {
3248 $allowedRights = $this->getRequest()->getSession()->getAllowedUserRights();
3249 if ( $allowedRights !== null ) {
3250 $this->mRights
= array_intersect( $this->mRights
, $allowedRights );
3254 Hooks
::run( 'UserGetRights', [ $this, &$this->mRights
] );
3255 // Force reindexation of rights when a hook has unset one of them
3256 $this->mRights
= array_values( array_unique( $this->mRights
) );
3258 return $this->mRights
;
3262 * Get the list of explicit group memberships this user has.
3263 * The implicit * and user groups are not included.
3264 * @return array Array of String internal group names
3266 public function getGroups() {
3268 $this->loadGroups();
3269 return $this->mGroups
;
3273 * Get the list of implicit group memberships this user has.
3274 * This includes all explicit groups, plus 'user' if logged in,
3275 * '*' for all accounts, and autopromoted groups
3276 * @param bool $recache Whether to avoid the cache
3277 * @return array Array of String internal group names
3279 public function getEffectiveGroups( $recache = false ) {
3280 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
3281 $this->mEffectiveGroups
= array_unique( array_merge(
3282 $this->getGroups(), // explicit groups
3283 $this->getAutomaticGroups( $recache ) // implicit groups
3285 // Hook for additional groups
3286 Hooks
::run( 'UserEffectiveGroups', [ &$this, &$this->mEffectiveGroups
] );
3287 // Force reindexation of groups when a hook has unset one of them
3288 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
3290 return $this->mEffectiveGroups
;
3294 * Get the list of implicit group memberships this user has.
3295 * This includes 'user' if logged in, '*' for all accounts,
3296 * and autopromoted groups
3297 * @param bool $recache Whether to avoid the cache
3298 * @return array Array of String internal group names
3300 public function getAutomaticGroups( $recache = false ) {
3301 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
3302 $this->mImplicitGroups
= [ '*' ];
3303 if ( $this->getId() ) {
3304 $this->mImplicitGroups
[] = 'user';
3306 $this->mImplicitGroups
= array_unique( array_merge(
3307 $this->mImplicitGroups
,
3308 Autopromote
::getAutopromoteGroups( $this )
3312 // Assure data consistency with rights/groups,
3313 // as getEffectiveGroups() depends on this function
3314 $this->mEffectiveGroups
= null;
3317 return $this->mImplicitGroups
;
3321 * Returns the groups the user has belonged to.
3323 * The user may still belong to the returned groups. Compare with getGroups().
3325 * The function will not return groups the user had belonged to before MW 1.17
3327 * @return array Names of the groups the user has belonged to.
3329 public function getFormerGroups() {
3332 if ( is_null( $this->mFormerGroups
) ) {
3333 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3334 ?
wfGetDB( DB_MASTER
)
3335 : wfGetDB( DB_SLAVE
);
3336 $res = $db->select( 'user_former_groups',
3338 [ 'ufg_user' => $this->mId
],
3340 $this->mFormerGroups
= [];
3341 foreach ( $res as $row ) {
3342 $this->mFormerGroups
[] = $row->ufg_group
;
3346 return $this->mFormerGroups
;
3350 * Get the user's edit count.
3351 * @return int|null Null for anonymous users
3353 public function getEditCount() {
3354 if ( !$this->getId() ) {
3358 if ( $this->mEditCount
=== null ) {
3359 /* Populate the count, if it has not been populated yet */
3360 $dbr = wfGetDB( DB_SLAVE
);
3361 // check if the user_editcount field has been initialized
3362 $count = $dbr->selectField(
3363 'user', 'user_editcount',
3364 [ 'user_id' => $this->mId
],
3368 if ( $count === null ) {
3369 // it has not been initialized. do so.
3370 $count = $this->initEditCount();
3372 $this->mEditCount
= $count;
3374 return (int)$this->mEditCount
;
3378 * Add the user to the given group.
3379 * This takes immediate effect.
3380 * @param string $group Name of the group to add
3383 public function addGroup( $group ) {
3386 if ( !Hooks
::run( 'UserAddGroup', [ $this, &$group ] ) ) {
3390 $dbw = wfGetDB( DB_MASTER
);
3391 if ( $this->getId() ) {
3392 $dbw->insert( 'user_groups',
3394 'ug_user' => $this->getId(),
3395 'ug_group' => $group,
3401 $this->loadGroups();
3402 $this->mGroups
[] = $group;
3403 // In case loadGroups was not called before, we now have the right twice.
3404 // Get rid of the duplicate.
3405 $this->mGroups
= array_unique( $this->mGroups
);
3407 // Refresh the groups caches, and clear the rights cache so it will be
3408 // refreshed on the next call to $this->getRights().
3409 $this->getEffectiveGroups( true );
3410 $this->mRights
= null;
3412 $this->invalidateCache();
3418 * Remove the user from the given group.
3419 * This takes immediate effect.
3420 * @param string $group Name of the group to remove
3423 public function removeGroup( $group ) {
3425 if ( !Hooks
::run( 'UserRemoveGroup', [ $this, &$group ] ) ) {
3429 $dbw = wfGetDB( DB_MASTER
);
3430 $dbw->delete( 'user_groups',
3432 'ug_user' => $this->getId(),
3433 'ug_group' => $group,
3436 // Remember that the user was in this group
3437 $dbw->insert( 'user_former_groups',
3439 'ufg_user' => $this->getId(),
3440 'ufg_group' => $group,
3446 $this->loadGroups();
3447 $this->mGroups
= array_diff( $this->mGroups
, [ $group ] );
3449 // Refresh the groups caches, and clear the rights cache so it will be
3450 // refreshed on the next call to $this->getRights().
3451 $this->getEffectiveGroups( true );
3452 $this->mRights
= null;
3454 $this->invalidateCache();
3460 * Get whether the user is logged in
3463 public function isLoggedIn() {
3464 return $this->getId() != 0;
3468 * Get whether the user is anonymous
3471 public function isAnon() {
3472 return !$this->isLoggedIn();
3476 * @return bool Whether this user is flagged as being a bot role account
3479 public function isBot() {
3480 if ( in_array( 'bot', $this->getGroups() ) && $this->isAllowed( 'bot' ) ) {
3485 Hooks
::run( "UserIsBot", [ $this, &$isBot ] );
3491 * Check if user is allowed to access a feature / make an action
3493 * @param string ... Permissions to test
3494 * @return bool True if user is allowed to perform *any* of the given actions
3496 public function isAllowedAny() {
3497 $permissions = func_get_args();
3498 foreach ( $permissions as $permission ) {
3499 if ( $this->isAllowed( $permission ) ) {
3508 * @param string ... Permissions to test
3509 * @return bool True if the user is allowed to perform *all* of the given actions
3511 public function isAllowedAll() {
3512 $permissions = func_get_args();
3513 foreach ( $permissions as $permission ) {
3514 if ( !$this->isAllowed( $permission ) ) {
3522 * Internal mechanics of testing a permission
3523 * @param string $action
3526 public function isAllowed( $action = '' ) {
3527 if ( $action === '' ) {
3528 return true; // In the spirit of DWIM
3530 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3531 // by misconfiguration: 0 == 'foo'
3532 return in_array( $action, $this->getRights(), true );
3536 * Check whether to enable recent changes patrol features for this user
3537 * @return bool True or false
3539 public function useRCPatrol() {
3540 global $wgUseRCPatrol;
3541 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3545 * Check whether to enable new pages patrol features for this user
3546 * @return bool True or false
3548 public function useNPPatrol() {
3549 global $wgUseRCPatrol, $wgUseNPPatrol;
3551 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3552 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3557 * Check whether to enable new files patrol features for this user
3558 * @return bool True or false
3560 public function useFilePatrol() {
3561 global $wgUseRCPatrol, $wgUseFilePatrol;
3563 ( $wgUseRCPatrol ||
$wgUseFilePatrol )
3564 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3569 * Get the WebRequest object to use with this object
3571 * @return WebRequest
3573 public function getRequest() {
3574 if ( $this->mRequest
) {
3575 return $this->mRequest
;
3583 * Check the watched status of an article.
3584 * @since 1.22 $checkRights parameter added
3585 * @param Title $title Title of the article to look at
3586 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3587 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3590 public function isWatched( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3591 if ( $title->isWatchable() && ( !$checkRights ||
$this->isAllowed( 'viewmywatchlist' ) ) ) {
3592 return MediaWikiServices
::getInstance()->getWatchedItemStore()->isWatched( $this, $title );
3599 * @since 1.22 $checkRights parameter added
3600 * @param Title $title Title of the article to look at
3601 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3602 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3604 public function addWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3605 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3606 MediaWikiServices
::getInstance()->getWatchedItemStore()->addWatchBatchForUser(
3608 [ $title->getSubjectPage(), $title->getTalkPage() ]
3611 $this->invalidateCache();
3615 * Stop watching an article.
3616 * @since 1.22 $checkRights parameter added
3617 * @param Title $title Title of the article to look at
3618 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3619 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3621 public function removeWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3622 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3623 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
3624 $store->removeWatch( $this, $title->getSubjectPage() );
3625 $store->removeWatch( $this, $title->getTalkPage() );
3627 $this->invalidateCache();
3631 * Clear the user's notification timestamp for the given title.
3632 * If e-notif e-mails are on, they will receive notification mails on
3633 * the next change of the page if it's watched etc.
3634 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3635 * @param Title $title Title of the article to look at
3636 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3638 public function clearNotification( &$title, $oldid = 0 ) {
3639 global $wgUseEnotif, $wgShowUpdatedMarker;
3641 // Do nothing if the database is locked to writes
3642 if ( wfReadOnly() ) {
3646 // Do nothing if not allowed to edit the watchlist
3647 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3651 // If we're working on user's talk page, we should update the talk page message indicator
3652 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3653 if ( !Hooks
::run( 'UserClearNewTalkNotification', [ &$this, $oldid ] ) ) {
3657 // Try to update the DB post-send and only if needed...
3658 DeferredUpdates
::addCallableUpdate( function() use ( $title, $oldid ) {
3659 if ( !$this->getNewtalk() ) {
3660 return; // no notifications to clear
3663 // Delete the last notifications (they stack up)
3664 $this->setNewtalk( false );
3666 // If there is a new, unseen, revision, use its timestamp
3668 ?
$title->getNextRevisionID( $oldid, Title
::GAID_FOR_UPDATE
)
3671 $this->setNewtalk( true, Revision
::newFromId( $nextid ) );
3676 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3680 if ( $this->isAnon() ) {
3681 // Nothing else to do...
3685 // Only update the timestamp if the page is being watched.
3686 // The query to find out if it is watched is cached both in memcached and per-invocation,
3687 // and when it does have to be executed, it can be on a slave
3688 // If this is the user's newtalk page, we always update the timestamp
3690 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3694 MediaWikiServices
::getInstance()->getWatchedItemStore()
3695 ->resetNotificationTimestamp( $this, $title, $force, $oldid );
3699 * Resets all of the given user's page-change notification timestamps.
3700 * If e-notif e-mails are on, they will receive notification mails on
3701 * the next change of any watched page.
3702 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3704 public function clearAllNotifications() {
3705 if ( wfReadOnly() ) {
3709 // Do nothing if not allowed to edit the watchlist
3710 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3714 global $wgUseEnotif, $wgShowUpdatedMarker;
3715 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3716 $this->setNewtalk( false );
3719 $id = $this->getId();
3721 $dbw = wfGetDB( DB_MASTER
);
3722 $dbw->update( 'watchlist',
3723 [ /* SET */ 'wl_notificationtimestamp' => null ],
3724 [ /* WHERE */ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ],
3727 // We also need to clear here the "you have new message" notification for the own user_talk page;
3728 // it's cleared one page view later in WikiPage::doViewUpdates().
3733 * Set a cookie on the user's client. Wrapper for
3734 * WebResponse::setCookie
3735 * @deprecated since 1.27
3736 * @param string $name Name of the cookie to set
3737 * @param string $value Value to set
3738 * @param int $exp Expiration time, as a UNIX time value;
3739 * if 0 or not specified, use the default $wgCookieExpiration
3740 * @param bool $secure
3741 * true: Force setting the secure attribute when setting the cookie
3742 * false: Force NOT setting the secure attribute when setting the cookie
3743 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3744 * @param array $params Array of options sent passed to WebResponse::setcookie()
3745 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3748 protected function setCookie(
3749 $name, $value, $exp = 0, $secure = null, $params = [], $request = null
3751 wfDeprecated( __METHOD__
, '1.27' );
3752 if ( $request === null ) {
3753 $request = $this->getRequest();
3755 $params['secure'] = $secure;
3756 $request->response()->setCookie( $name, $value, $exp, $params );
3760 * Clear a cookie on the user's client
3761 * @deprecated since 1.27
3762 * @param string $name Name of the cookie to clear
3763 * @param bool $secure
3764 * true: Force setting the secure attribute when setting the cookie
3765 * false: Force NOT setting the secure attribute when setting the cookie
3766 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3767 * @param array $params Array of options sent passed to WebResponse::setcookie()
3769 protected function clearCookie( $name, $secure = null, $params = [] ) {
3770 wfDeprecated( __METHOD__
, '1.27' );
3771 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3775 * Set an extended login cookie on the user's client. The expiry of the cookie
3776 * is controlled by the $wgExtendedLoginCookieExpiration configuration
3779 * @see User::setCookie
3781 * @deprecated since 1.27
3782 * @param string $name Name of the cookie to set
3783 * @param string $value Value to set
3784 * @param bool $secure
3785 * true: Force setting the secure attribute when setting the cookie
3786 * false: Force NOT setting the secure attribute when setting the cookie
3787 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3789 protected function setExtendedLoginCookie( $name, $value, $secure ) {
3790 global $wgExtendedLoginCookieExpiration, $wgCookieExpiration;
3792 wfDeprecated( __METHOD__
, '1.27' );
3795 $exp +
= $wgExtendedLoginCookieExpiration !== null
3796 ?
$wgExtendedLoginCookieExpiration
3797 : $wgCookieExpiration;
3799 $this->setCookie( $name, $value, $exp, $secure );
3803 * Persist this user's session (e.g. set cookies)
3805 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3807 * @param bool $secure Whether to force secure/insecure cookies or use default
3808 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3810 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3812 if ( 0 == $this->mId
) {
3816 $session = $this->getRequest()->getSession();
3817 if ( $request && $session->getRequest() !== $request ) {
3818 $session = $session->sessionWithRequest( $request );
3820 $delay = $session->delaySave();
3822 if ( !$session->getUser()->equals( $this ) ) {
3823 if ( !$session->canSetUser() ) {
3824 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3825 ->warning( __METHOD__
.
3826 ": Cannot save user \"$this\" to a user \"{$session->getUser()}\"'s immutable session"
3830 $session->setUser( $this );
3833 $session->setRememberUser( $rememberMe );
3834 if ( $secure !== null ) {
3835 $session->setForceHTTPS( $secure );
3838 $session->persist();
3840 ScopedCallback
::consume( $delay );
3844 * Log this user out.
3846 public function logout() {
3847 if ( Hooks
::run( 'UserLogout', [ &$this ] ) ) {
3853 * Clear the user's session, and reset the instance cache.
3856 public function doLogout() {
3857 $session = $this->getRequest()->getSession();
3858 if ( !$session->canSetUser() ) {
3859 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3860 ->warning( __METHOD__
. ": Cannot log out of an immutable session" );
3861 } elseif ( !$session->getUser()->equals( $this ) ) {
3862 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3863 ->warning( __METHOD__
.
3864 ": Cannot log user \"$this\" out of a user \"{$session->getUser()}\"'s session"
3866 // But we still may as well make this user object anon
3867 $this->clearInstanceCache( 'defaults' );
3869 $this->clearInstanceCache( 'defaults' );
3870 $delay = $session->delaySave();
3871 $session->unpersist(); // Clear cookies (T127436)
3872 $session->setLoggedOutTimestamp( time() );
3873 $session->setUser( new User
);
3874 $session->set( 'wsUserID', 0 ); // Other code expects this
3875 ScopedCallback
::consume( $delay );
3880 * Save this user's settings into the database.
3881 * @todo Only rarely do all these fields need to be set!
3883 public function saveSettings() {
3884 if ( wfReadOnly() ) {
3885 // @TODO: caller should deal with this instead!
3886 // This should really just be an exception.
3887 MWExceptionHandler
::logException( new DBExpectedError(
3889 "Could not update user with ID '{$this->mId}'; DB is read-only."
3895 if ( 0 == $this->mId
) {
3899 // Get a new user_touched that is higher than the old one.
3900 // This will be used for a CAS check as a last-resort safety
3901 // check against race conditions and slave lag.
3902 $oldTouched = $this->mTouched
;
3903 $newTouched = $this->newTouchedTimestamp();
3905 $dbw = wfGetDB( DB_MASTER
);
3906 $dbw->update( 'user',
3908 'user_name' => $this->mName
,
3909 'user_real_name' => $this->mRealName
,
3910 'user_email' => $this->mEmail
,
3911 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3912 'user_touched' => $dbw->timestamp( $newTouched ),
3913 'user_token' => strval( $this->mToken
),
3914 'user_email_token' => $this->mEmailToken
,
3915 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
3917 'user_id' => $this->mId
,
3918 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
3922 if ( !$dbw->affectedRows() ) {
3923 // Maybe the problem was a missed cache update; clear it to be safe
3924 $this->clearSharedCache( 'refresh' );
3925 // User was changed in the meantime or loaded with stale data
3926 $from = ( $this->queryFlagsUsed
& self
::READ_LATEST
) ?
'master' : 'slave';
3927 throw new MWException(
3928 "CAS update failed on user_touched for user ID '{$this->mId}' (read from $from);" .
3929 " the version of the user to be saved is older than the current version."
3933 $this->mTouched
= $newTouched;
3934 $this->saveOptions();
3936 Hooks
::run( 'UserSaveSettings', [ $this ] );
3937 $this->clearSharedCache();
3938 $this->getUserPage()->invalidateCache();
3942 * If only this user's username is known, and it exists, return the user ID.
3944 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
3947 public function idForName( $flags = 0 ) {
3948 $s = trim( $this->getName() );
3953 $db = ( ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
)
3954 ?
wfGetDB( DB_MASTER
)
3955 : wfGetDB( DB_SLAVE
);
3957 $options = ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
)
3958 ?
[ 'LOCK IN SHARE MODE' ]
3961 $id = $db->selectField( 'user',
3962 'user_id', [ 'user_name' => $s ], __METHOD__
, $options );
3968 * Add a user to the database, return the user object
3970 * @param string $name Username to add
3971 * @param array $params Array of Strings Non-default parameters to save to
3972 * the database as user_* fields:
3973 * - email: The user's email address.
3974 * - email_authenticated: The email authentication timestamp.
3975 * - real_name: The user's real name.
3976 * - options: An associative array of non-default options.
3977 * - token: Random authentication token. Do not set.
3978 * - registration: Registration timestamp. Do not set.
3980 * @return User|null User object, or null if the username already exists.
3982 public static function createNew( $name, $params = [] ) {
3983 foreach ( [ 'password', 'newpassword', 'newpass_time', 'password_expires' ] as $field ) {
3984 if ( isset( $params[$field] ) ) {
3985 wfDeprecated( __METHOD__
. " with param '$field'", '1.27' );
3986 unset( $params[$field] );
3992 $user->setToken(); // init token
3993 if ( isset( $params['options'] ) ) {
3994 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
3995 unset( $params['options'] );
3997 $dbw = wfGetDB( DB_MASTER
);
3998 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
4000 $noPass = PasswordFactory
::newInvalidPassword()->toString();
4003 'user_id' => $seqVal,
4004 'user_name' => $name,
4005 'user_password' => $noPass,
4006 'user_newpassword' => $noPass,
4007 'user_email' => $user->mEmail
,
4008 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
4009 'user_real_name' => $user->mRealName
,
4010 'user_token' => strval( $user->mToken
),
4011 'user_registration' => $dbw->timestamp( $user->mRegistration
),
4012 'user_editcount' => 0,
4013 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
4015 foreach ( $params as $name => $value ) {
4016 $fields["user_$name"] = $value;
4018 $dbw->insert( 'user', $fields, __METHOD__
, [ 'IGNORE' ] );
4019 if ( $dbw->affectedRows() ) {
4020 $newUser = User
::newFromId( $dbw->insertId() );
4028 * Add this existing user object to the database. If the user already
4029 * exists, a fatal status object is returned, and the user object is
4030 * initialised with the data from the database.
4032 * Previously, this function generated a DB error due to a key conflict
4033 * if the user already existed. Many extension callers use this function
4034 * in code along the lines of:
4036 * $user = User::newFromName( $name );
4037 * if ( !$user->isLoggedIn() ) {
4038 * $user->addToDatabase();
4040 * // do something with $user...
4042 * However, this was vulnerable to a race condition (bug 16020). By
4043 * initialising the user object if the user exists, we aim to support this
4044 * calling sequence as far as possible.
4046 * Note that if the user exists, this function will acquire a write lock,
4047 * so it is still advisable to make the call conditional on isLoggedIn(),
4048 * and to commit the transaction after calling.
4050 * @throws MWException
4053 public function addToDatabase() {
4055 if ( !$this->mToken
) {
4056 $this->setToken(); // init token
4059 $this->mTouched
= $this->newTouchedTimestamp();
4061 $noPass = PasswordFactory
::newInvalidPassword()->toString();
4063 $dbw = wfGetDB( DB_MASTER
);
4064 $inWrite = $dbw->writesOrCallbacksPending();
4065 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
4066 $dbw->insert( 'user',
4068 'user_id' => $seqVal,
4069 'user_name' => $this->mName
,
4070 'user_password' => $noPass,
4071 'user_newpassword' => $noPass,
4072 'user_email' => $this->mEmail
,
4073 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
4074 'user_real_name' => $this->mRealName
,
4075 'user_token' => strval( $this->mToken
),
4076 'user_registration' => $dbw->timestamp( $this->mRegistration
),
4077 'user_editcount' => 0,
4078 'user_touched' => $dbw->timestamp( $this->mTouched
),
4082 if ( !$dbw->affectedRows() ) {
4083 // The queries below cannot happen in the same REPEATABLE-READ snapshot.
4084 // Handle this by COMMIT, if possible, or by LOCK IN SHARE MODE otherwise.
4086 // Can't commit due to pending writes that may need atomicity.
4087 // This may cause some lock contention unlike the case below.
4088 $options = [ 'LOCK IN SHARE MODE' ];
4089 $flags = self
::READ_LOCKING
;
4091 // Often, this case happens early in views before any writes when
4092 // using CentralAuth. It's should be OK to commit and break the snapshot.
4093 $dbw->commit( __METHOD__
, 'flush' );
4095 $flags = self
::READ_LATEST
;
4097 $this->mId
= $dbw->selectField( 'user', 'user_id',
4098 [ 'user_name' => $this->mName
], __METHOD__
, $options );
4101 if ( $this->loadFromDatabase( $flags ) ) {
4106 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
4107 "to insert user '{$this->mName}' row, but it was not present in select!" );
4109 return Status
::newFatal( 'userexists' );
4111 $this->mId
= $dbw->insertId();
4112 self
::$idCacheByName[$this->mName
] = $this->mId
;
4114 // Clear instance cache other than user table data, which is already accurate
4115 $this->clearInstanceCache();
4117 $this->saveOptions();
4118 return Status
::newGood();
4122 * If this user is logged-in and blocked,
4123 * block any IP address they've successfully logged in from.
4124 * @return bool A block was spread
4126 public function spreadAnyEditBlock() {
4127 if ( $this->isLoggedIn() && $this->isBlocked() ) {
4128 return $this->spreadBlock();
4135 * If this (non-anonymous) user is blocked,
4136 * block the IP address they've successfully logged in from.
4137 * @return bool A block was spread
4139 protected function spreadBlock() {
4140 wfDebug( __METHOD__
. "()\n" );
4142 if ( $this->mId
== 0 ) {
4146 $userblock = Block
::newFromTarget( $this->getName() );
4147 if ( !$userblock ) {
4151 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
4155 * Get whether the user is explicitly blocked from account creation.
4156 * @return bool|Block
4158 public function isBlockedFromCreateAccount() {
4159 $this->getBlockedStatus();
4160 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
4161 return $this->mBlock
;
4164 # bug 13611: if the IP address the user is trying to create an account from is
4165 # blocked with createaccount disabled, prevent new account creation there even
4166 # when the user is logged in
4167 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
4168 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
4170 return $this->mBlockedFromCreateAccount
instanceof Block
4171 && $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
4172 ?
$this->mBlockedFromCreateAccount
4177 * Get whether the user is blocked from using Special:Emailuser.
4180 public function isBlockedFromEmailuser() {
4181 $this->getBlockedStatus();
4182 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
4186 * Get whether the user is allowed to create an account.
4189 public function isAllowedToCreateAccount() {
4190 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
4194 * Get this user's personal page title.
4196 * @return Title User's personal page title
4198 public function getUserPage() {
4199 return Title
::makeTitle( NS_USER
, $this->getName() );
4203 * Get this user's talk page title.
4205 * @return Title User's talk page title
4207 public function getTalkPage() {
4208 $title = $this->getUserPage();
4209 return $title->getTalkPage();
4213 * Determine whether the user is a newbie. Newbies are either
4214 * anonymous IPs, or the most recently created accounts.
4217 public function isNewbie() {
4218 return !$this->isAllowed( 'autoconfirmed' );
4222 * Check to see if the given clear-text password is one of the accepted passwords
4223 * @deprecated since 1.27, use AuthManager instead
4224 * @param string $password User password
4225 * @return bool True if the given password is correct, otherwise False
4227 public function checkPassword( $password ) {
4228 global $wgAuth, $wgLegacyEncoding, $wgDisableAuthManager;
4230 if ( $wgDisableAuthManager ) {
4233 // Some passwords will give a fatal Status, which means there is
4234 // some sort of technical or security reason for this password to
4235 // be completely invalid and should never be checked (e.g., T64685)
4236 if ( !$this->checkPasswordValidity( $password )->isOK() ) {
4240 // Certain authentication plugins do NOT want to save
4241 // domain passwords in a mysql database, so we should
4242 // check this (in case $wgAuth->strict() is false).
4243 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
4245 } elseif ( $wgAuth->strict() ) {
4246 // Auth plugin doesn't allow local authentication
4248 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
4249 // Auth plugin doesn't allow local authentication for this user name
4253 $passwordFactory = new PasswordFactory();
4254 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4255 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
4256 ?
wfGetDB( DB_MASTER
)
4257 : wfGetDB( DB_SLAVE
);
4260 $mPassword = $passwordFactory->newFromCiphertext( $db->selectField(
4261 'user', 'user_password', [ 'user_id' => $this->getId() ], __METHOD__
4263 } catch ( PasswordError
$e ) {
4264 wfDebug( 'Invalid password hash found in database.' );
4265 $mPassword = PasswordFactory
::newInvalidPassword();
4268 if ( !$mPassword->equals( $password ) ) {
4269 if ( $wgLegacyEncoding ) {
4270 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
4271 // Check for this with iconv
4272 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
4273 if ( $cp1252Password === $password ||
!$mPassword->equals( $cp1252Password ) ) {
4281 if ( $passwordFactory->needsUpdate( $mPassword ) && !wfReadOnly() ) {
4282 $this->setPasswordInternal( $password );
4287 $manager = AuthManager
::singleton();
4288 $reqs = AuthenticationRequest
::loadRequestsFromSubmission(
4289 $manager->getAuthenticationRequests( AuthManager
::ACTION_LOGIN
),
4291 'username' => $this->getName(),
4292 'password' => $password,
4295 $res = AuthManager
::singleton()->beginAuthentication( $reqs, 'null:' );
4296 switch ( $res->status
) {
4297 case AuthenticationResponse
::PASS
:
4299 case AuthenticationResponse
::FAIL
:
4300 // Hope it's not a PreAuthenticationProvider that failed...
4301 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
4302 ->info( __METHOD__
. ': Authentication failed: ' . $res->message
->plain() );
4305 throw new BadMethodCallException(
4306 'AuthManager returned a response unsupported by ' . __METHOD__
4313 * Check if the given clear-text password matches the temporary password
4314 * sent by e-mail for password reset operations.
4316 * @deprecated since 1.27, use AuthManager instead
4317 * @param string $plaintext
4318 * @return bool True if matches, false otherwise
4320 public function checkTemporaryPassword( $plaintext ) {
4321 global $wgNewPasswordExpiry, $wgDisableAuthManager;
4323 if ( $wgDisableAuthManager ) {
4326 $passwordFactory = new PasswordFactory();
4327 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4328 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
4329 ?
wfGetDB( DB_MASTER
)
4330 : wfGetDB( DB_SLAVE
);
4332 $row = $db->selectRow(
4334 [ 'user_newpassword', 'user_newpass_time' ],
4335 [ 'user_id' => $this->getId() ],
4339 $newPassword = $passwordFactory->newFromCiphertext( $row->user_newpassword
);
4340 } catch ( PasswordError
$e ) {
4341 wfDebug( 'Invalid password hash found in database.' );
4342 $newPassword = PasswordFactory
::newInvalidPassword();
4345 if ( $newPassword->equals( $plaintext ) ) {
4346 if ( is_null( $row->user_newpass_time
) ) {
4349 $expiry = wfTimestamp( TS_UNIX
, $row->user_newpass_time
) +
$wgNewPasswordExpiry;
4350 return ( time() < $expiry );
4355 // Can't check the temporary password individually.
4356 return $this->checkPassword( $plaintext );
4361 * Initialize (if necessary) and return a session token value
4362 * which can be used in edit forms to show that the user's
4363 * login credentials aren't being hijacked with a foreign form
4367 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4368 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4369 * @return MediaWiki\Session\Token The new edit token
4371 public function getEditTokenObject( $salt = '', $request = null ) {
4372 if ( $this->isAnon() ) {
4373 return new LoggedOutEditToken();
4377 $request = $this->getRequest();
4379 return $request->getSession()->getToken( $salt );
4383 * Initialize (if necessary) and return a session token value
4384 * which can be used in edit forms to show that the user's
4385 * login credentials aren't being hijacked with a foreign form
4389 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4390 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4391 * @return string The new edit token
4393 public function getEditToken( $salt = '', $request = null ) {
4394 return $this->getEditTokenObject( $salt, $request )->toString();
4398 * Get the embedded timestamp from a token.
4399 * @deprecated since 1.27, use \MediaWiki\Session\Token::getTimestamp instead.
4400 * @param string $val Input token
4403 public static function getEditTokenTimestamp( $val ) {
4404 wfDeprecated( __METHOD__
, '1.27' );
4405 return MediaWiki\Session\Token
::getTimestamp( $val );
4409 * Check given value against the token value stored in the session.
4410 * A match should confirm that the form was submitted from the
4411 * user's own login session, not a form submission from a third-party
4414 * @param string $val Input value to compare
4415 * @param string $salt Optional function-specific data for hashing
4416 * @param WebRequest|null $request Object to use or null to use $wgRequest
4417 * @param int $maxage Fail tokens older than this, in seconds
4418 * @return bool Whether the token matches
4420 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4421 return $this->getEditTokenObject( $salt, $request )->match( $val, $maxage );
4425 * Check given value against the token value stored in the session,
4426 * ignoring the suffix.
4428 * @param string $val Input value to compare
4429 * @param string $salt Optional function-specific data for hashing
4430 * @param WebRequest|null $request Object to use or null to use $wgRequest
4431 * @param int $maxage Fail tokens older than this, in seconds
4432 * @return bool Whether the token matches
4434 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4435 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . Token
::SUFFIX
;
4436 return $this->matchEditToken( $val, $salt, $request, $maxage );
4440 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4441 * mail to the user's given address.
4443 * @param string $type Message to send, either "created", "changed" or "set"
4446 public function sendConfirmationMail( $type = 'created' ) {
4448 $expiration = null; // gets passed-by-ref and defined in next line.
4449 $token = $this->confirmationToken( $expiration );
4450 $url = $this->confirmationTokenUrl( $token );
4451 $invalidateURL = $this->invalidationTokenUrl( $token );
4452 $this->saveSettings();
4454 if ( $type == 'created' ||
$type === false ) {
4455 $message = 'confirmemail_body';
4456 } elseif ( $type === true ) {
4457 $message = 'confirmemail_body_changed';
4459 // Messages: confirmemail_body_changed, confirmemail_body_set
4460 $message = 'confirmemail_body_' . $type;
4463 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4464 wfMessage( $message,
4465 $this->getRequest()->getIP(),
4468 $wgLang->userTimeAndDate( $expiration, $this ),
4470 $wgLang->userDate( $expiration, $this ),
4471 $wgLang->userTime( $expiration, $this ) )->text() );
4475 * Send an e-mail to this user's account. Does not check for
4476 * confirmed status or validity.
4478 * @param string $subject Message subject
4479 * @param string $body Message body
4480 * @param User|null $from Optional sending user; if unspecified, default
4481 * $wgPasswordSender will be used.
4482 * @param string $replyto Reply-To address
4485 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4486 global $wgPasswordSender;
4488 if ( $from instanceof User
) {
4489 $sender = MailAddress
::newFromUser( $from );
4491 $sender = new MailAddress( $wgPasswordSender,
4492 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4494 $to = MailAddress
::newFromUser( $this );
4496 return UserMailer
::send( $to, $sender, $subject, $body, [
4497 'replyTo' => $replyto,
4502 * Generate, store, and return a new e-mail confirmation code.
4503 * A hash (unsalted, since it's used as a key) is stored.
4505 * @note Call saveSettings() after calling this function to commit
4506 * this change to the database.
4508 * @param string &$expiration Accepts the expiration time
4509 * @return string New token
4511 protected function confirmationToken( &$expiration ) {
4512 global $wgUserEmailConfirmationTokenExpiry;
4514 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4515 $expiration = wfTimestamp( TS_MW
, $expires );
4517 $token = MWCryptRand
::generateHex( 32 );
4518 $hash = md5( $token );
4519 $this->mEmailToken
= $hash;
4520 $this->mEmailTokenExpires
= $expiration;
4525 * Return a URL the user can use to confirm their email address.
4526 * @param string $token Accepts the email confirmation token
4527 * @return string New token URL
4529 protected function confirmationTokenUrl( $token ) {
4530 return $this->getTokenUrl( 'ConfirmEmail', $token );
4534 * Return a URL the user can use to invalidate their email address.
4535 * @param string $token Accepts the email confirmation token
4536 * @return string New token URL
4538 protected function invalidationTokenUrl( $token ) {
4539 return $this->getTokenUrl( 'InvalidateEmail', $token );
4543 * Internal function to format the e-mail validation/invalidation URLs.
4544 * This uses a quickie hack to use the
4545 * hardcoded English names of the Special: pages, for ASCII safety.
4547 * @note Since these URLs get dropped directly into emails, using the
4548 * short English names avoids insanely long URL-encoded links, which
4549 * also sometimes can get corrupted in some browsers/mailers
4550 * (bug 6957 with Gmail and Internet Explorer).
4552 * @param string $page Special page
4553 * @param string $token Token
4554 * @return string Formatted URL
4556 protected function getTokenUrl( $page, $token ) {
4557 // Hack to bypass localization of 'Special:'
4558 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4559 return $title->getCanonicalURL();
4563 * Mark the e-mail address confirmed.
4565 * @note Call saveSettings() after calling this function to commit the change.
4569 public function confirmEmail() {
4570 // Check if it's already confirmed, so we don't touch the database
4571 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4572 if ( !$this->isEmailConfirmed() ) {
4573 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4574 Hooks
::run( 'ConfirmEmailComplete', [ $this ] );
4580 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4581 * address if it was already confirmed.
4583 * @note Call saveSettings() after calling this function to commit the change.
4584 * @return bool Returns true
4586 public function invalidateEmail() {
4588 $this->mEmailToken
= null;
4589 $this->mEmailTokenExpires
= null;
4590 $this->setEmailAuthenticationTimestamp( null );
4592 Hooks
::run( 'InvalidateEmailComplete', [ $this ] );
4597 * Set the e-mail authentication timestamp.
4598 * @param string $timestamp TS_MW timestamp
4600 public function setEmailAuthenticationTimestamp( $timestamp ) {
4602 $this->mEmailAuthenticated
= $timestamp;
4603 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
4607 * Is this user allowed to send e-mails within limits of current
4608 * site configuration?
4611 public function canSendEmail() {
4612 global $wgEnableEmail, $wgEnableUserEmail;
4613 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4616 $canSend = $this->isEmailConfirmed();
4617 Hooks
::run( 'UserCanSendEmail', [ &$this, &$canSend ] );
4622 * Is this user allowed to receive e-mails within limits of current
4623 * site configuration?
4626 public function canReceiveEmail() {
4627 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4631 * Is this user's e-mail address valid-looking and confirmed within
4632 * limits of the current site configuration?
4634 * @note If $wgEmailAuthentication is on, this may require the user to have
4635 * confirmed their address by returning a code or using a password
4636 * sent to the address from the wiki.
4640 public function isEmailConfirmed() {
4641 global $wgEmailAuthentication;
4644 if ( Hooks
::run( 'EmailConfirmed', [ &$this, &$confirmed ] ) ) {
4645 if ( $this->isAnon() ) {
4648 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4651 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4661 * Check whether there is an outstanding request for e-mail confirmation.
4664 public function isEmailConfirmationPending() {
4665 global $wgEmailAuthentication;
4666 return $wgEmailAuthentication &&
4667 !$this->isEmailConfirmed() &&
4668 $this->mEmailToken
&&
4669 $this->mEmailTokenExpires
> wfTimestamp();
4673 * Get the timestamp of account creation.
4675 * @return string|bool|null Timestamp of account creation, false for
4676 * non-existent/anonymous user accounts, or null if existing account
4677 * but information is not in database.
4679 public function getRegistration() {
4680 if ( $this->isAnon() ) {
4684 return $this->mRegistration
;
4688 * Get the timestamp of the first edit
4690 * @return string|bool Timestamp of first edit, or false for
4691 * non-existent/anonymous user accounts.
4693 public function getFirstEditTimestamp() {
4694 if ( $this->getId() == 0 ) {
4695 return false; // anons
4697 $dbr = wfGetDB( DB_SLAVE
);
4698 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4699 [ 'rev_user' => $this->getId() ],
4701 [ 'ORDER BY' => 'rev_timestamp ASC' ]
4704 return false; // no edits
4706 return wfTimestamp( TS_MW
, $time );
4710 * Get the permissions associated with a given list of groups
4712 * @param array $groups Array of Strings List of internal group names
4713 * @return array Array of Strings List of permission key names for given groups combined
4715 public static function getGroupPermissions( $groups ) {
4716 global $wgGroupPermissions, $wgRevokePermissions;
4718 // grant every granted permission first
4719 foreach ( $groups as $group ) {
4720 if ( isset( $wgGroupPermissions[$group] ) ) {
4721 $rights = array_merge( $rights,
4722 // array_filter removes empty items
4723 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4726 // now revoke the revoked permissions
4727 foreach ( $groups as $group ) {
4728 if ( isset( $wgRevokePermissions[$group] ) ) {
4729 $rights = array_diff( $rights,
4730 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4733 return array_unique( $rights );
4737 * Get all the groups who have a given permission
4739 * @param string $role Role to check
4740 * @return array Array of Strings List of internal group names with the given permission
4742 public static function getGroupsWithPermission( $role ) {
4743 global $wgGroupPermissions;
4744 $allowedGroups = [];
4745 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4746 if ( self
::groupHasPermission( $group, $role ) ) {
4747 $allowedGroups[] = $group;
4750 return $allowedGroups;
4754 * Check, if the given group has the given permission
4756 * If you're wanting to check whether all users have a permission, use
4757 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4761 * @param string $group Group to check
4762 * @param string $role Role to check
4765 public static function groupHasPermission( $group, $role ) {
4766 global $wgGroupPermissions, $wgRevokePermissions;
4767 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4768 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4772 * Check if all users may be assumed to have the given permission
4774 * We generally assume so if the right is granted to '*' and isn't revoked
4775 * on any group. It doesn't attempt to take grants or other extension
4776 * limitations on rights into account in the general case, though, as that
4777 * would require it to always return false and defeat the purpose.
4778 * Specifically, session-based rights restrictions (such as OAuth or bot
4779 * passwords) are applied based on the current session.
4782 * @param string $right Right to check
4785 public static function isEveryoneAllowed( $right ) {
4786 global $wgGroupPermissions, $wgRevokePermissions;
4789 // Use the cached results, except in unit tests which rely on
4790 // being able change the permission mid-request
4791 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4792 return $cache[$right];
4795 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4796 $cache[$right] = false;
4800 // If it's revoked anywhere, then everyone doesn't have it
4801 foreach ( $wgRevokePermissions as $rights ) {
4802 if ( isset( $rights[$right] ) && $rights[$right] ) {
4803 $cache[$right] = false;
4808 // Remove any rights that aren't allowed to the global-session user,
4809 // unless there are no sessions for this endpoint.
4810 if ( !defined( 'MW_NO_SESSION' ) ) {
4811 $allowedRights = SessionManager
::getGlobalSession()->getAllowedUserRights();
4812 if ( $allowedRights !== null && !in_array( $right, $allowedRights, true ) ) {
4813 $cache[$right] = false;
4818 // Allow extensions to say false
4819 if ( !Hooks
::run( 'UserIsEveryoneAllowed', [ $right ] ) ) {
4820 $cache[$right] = false;
4824 $cache[$right] = true;
4829 * Get the localized descriptive name for a group, if it exists
4831 * @param string $group Internal group name
4832 * @return string Localized descriptive group name
4834 public static function getGroupName( $group ) {
4835 $msg = wfMessage( "group-$group" );
4836 return $msg->isBlank() ?
$group : $msg->text();
4840 * Get the localized descriptive name for a member of a group, if it exists
4842 * @param string $group Internal group name
4843 * @param string $username Username for gender (since 1.19)
4844 * @return string Localized name for group member
4846 public static function getGroupMember( $group, $username = '#' ) {
4847 $msg = wfMessage( "group-$group-member", $username );
4848 return $msg->isBlank() ?
$group : $msg->text();
4852 * Return the set of defined explicit groups.
4853 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4854 * are not included, as they are defined automatically, not in the database.
4855 * @return array Array of internal group names
4857 public static function getAllGroups() {
4858 global $wgGroupPermissions, $wgRevokePermissions;
4860 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4861 self
::getImplicitGroups()
4866 * Get a list of all available permissions.
4867 * @return string[] Array of permission names
4869 public static function getAllRights() {
4870 if ( self
::$mAllRights === false ) {
4871 global $wgAvailableRights;
4872 if ( count( $wgAvailableRights ) ) {
4873 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
4875 self
::$mAllRights = self
::$mCoreRights;
4877 Hooks
::run( 'UserGetAllRights', [ &self
::$mAllRights ] );
4879 return self
::$mAllRights;
4883 * Get a list of implicit groups
4884 * @return array Array of Strings Array of internal group names
4886 public static function getImplicitGroups() {
4887 global $wgImplicitGroups;
4889 $groups = $wgImplicitGroups;
4890 # Deprecated, use $wgImplicitGroups instead
4891 Hooks
::run( 'UserGetImplicitGroups', [ &$groups ], '1.25' );
4897 * Get the title of a page describing a particular group
4899 * @param string $group Internal group name
4900 * @return Title|bool Title of the page if it exists, false otherwise
4902 public static function getGroupPage( $group ) {
4903 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4904 if ( $msg->exists() ) {
4905 $title = Title
::newFromText( $msg->text() );
4906 if ( is_object( $title ) ) {
4914 * Create a link to the group in HTML, if available;
4915 * else return the group name.
4917 * @param string $group Internal name of the group
4918 * @param string $text The text of the link
4919 * @return string HTML link to the group
4921 public static function makeGroupLinkHTML( $group, $text = '' ) {
4922 if ( $text == '' ) {
4923 $text = self
::getGroupName( $group );
4925 $title = self
::getGroupPage( $group );
4927 return Linker
::link( $title, htmlspecialchars( $text ) );
4929 return htmlspecialchars( $text );
4934 * Create a link to the group in Wikitext, if available;
4935 * else return the group name.
4937 * @param string $group Internal name of the group
4938 * @param string $text The text of the link
4939 * @return string Wikilink to the group
4941 public static function makeGroupLinkWiki( $group, $text = '' ) {
4942 if ( $text == '' ) {
4943 $text = self
::getGroupName( $group );
4945 $title = self
::getGroupPage( $group );
4947 $page = $title->getFullText();
4948 return "[[$page|$text]]";
4955 * Returns an array of the groups that a particular group can add/remove.
4957 * @param string $group The group to check for whether it can add/remove
4958 * @return array Array( 'add' => array( addablegroups ),
4959 * 'remove' => array( removablegroups ),
4960 * 'add-self' => array( addablegroups to self),
4961 * 'remove-self' => array( removable groups from self) )
4963 public static function changeableByGroup( $group ) {
4964 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4973 if ( empty( $wgAddGroups[$group] ) ) {
4974 // Don't add anything to $groups
4975 } elseif ( $wgAddGroups[$group] === true ) {
4976 // You get everything
4977 $groups['add'] = self
::getAllGroups();
4978 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4979 $groups['add'] = $wgAddGroups[$group];
4982 // Same thing for remove
4983 if ( empty( $wgRemoveGroups[$group] ) ) {
4985 } elseif ( $wgRemoveGroups[$group] === true ) {
4986 $groups['remove'] = self
::getAllGroups();
4987 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4988 $groups['remove'] = $wgRemoveGroups[$group];
4991 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4992 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4993 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4994 if ( is_int( $key ) ) {
4995 $wgGroupsAddToSelf['user'][] = $value;
5000 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
5001 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
5002 if ( is_int( $key ) ) {
5003 $wgGroupsRemoveFromSelf['user'][] = $value;
5008 // Now figure out what groups the user can add to him/herself
5009 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
5011 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
5012 // No idea WHY this would be used, but it's there
5013 $groups['add-self'] = User
::getAllGroups();
5014 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
5015 $groups['add-self'] = $wgGroupsAddToSelf[$group];
5018 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
5020 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
5021 $groups['remove-self'] = User
::getAllGroups();
5022 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
5023 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
5030 * Returns an array of groups that this user can add and remove
5031 * @return array Array( 'add' => array( addablegroups ),
5032 * 'remove' => array( removablegroups ),
5033 * 'add-self' => array( addablegroups to self),
5034 * 'remove-self' => array( removable groups from self) )
5036 public function changeableGroups() {
5037 if ( $this->isAllowed( 'userrights' ) ) {
5038 // This group gives the right to modify everything (reverse-
5039 // compatibility with old "userrights lets you change
5041 // Using array_merge to make the groups reindexed
5042 $all = array_merge( User
::getAllGroups() );
5051 // Okay, it's not so simple, we will have to go through the arrays
5058 $addergroups = $this->getEffectiveGroups();
5060 foreach ( $addergroups as $addergroup ) {
5061 $groups = array_merge_recursive(
5062 $groups, $this->changeableByGroup( $addergroup )
5064 $groups['add'] = array_unique( $groups['add'] );
5065 $groups['remove'] = array_unique( $groups['remove'] );
5066 $groups['add-self'] = array_unique( $groups['add-self'] );
5067 $groups['remove-self'] = array_unique( $groups['remove-self'] );
5073 * Deferred version of incEditCountImmediate()
5075 public function incEditCount() {
5076 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle( function() {
5077 $this->incEditCountImmediate();
5082 * Increment the user's edit-count field.
5083 * Will have no effect for anonymous users.
5086 public function incEditCountImmediate() {
5087 if ( $this->isAnon() ) {
5091 $dbw = wfGetDB( DB_MASTER
);
5092 // No rows will be "affected" if user_editcount is NULL
5095 [ 'user_editcount=user_editcount+1' ],
5096 [ 'user_id' => $this->getId(), 'user_editcount IS NOT NULL' ],
5099 // Lazy initialization check...
5100 if ( $dbw->affectedRows() == 0 ) {
5101 // Now here's a goddamn hack...
5102 $dbr = wfGetDB( DB_SLAVE
);
5103 if ( $dbr !== $dbw ) {
5104 // If we actually have a slave server, the count is
5105 // at least one behind because the current transaction
5106 // has not been committed and replicated.
5107 $this->initEditCount( 1 );
5109 // But if DB_SLAVE is selecting the master, then the
5110 // count we just read includes the revision that was
5111 // just added in the working transaction.
5112 $this->initEditCount();
5115 // Edit count in user cache too
5116 $this->invalidateCache();
5120 * Initialize user_editcount from data out of the revision table
5122 * @param int $add Edits to add to the count from the revision table
5123 * @return int Number of edits
5125 protected function initEditCount( $add = 0 ) {
5126 // Pull from a slave to be less cruel to servers
5127 // Accuracy isn't the point anyway here
5128 $dbr = wfGetDB( DB_SLAVE
);
5129 $count = (int)$dbr->selectField(
5132 [ 'rev_user' => $this->getId() ],
5135 $count = $count +
$add;
5137 $dbw = wfGetDB( DB_MASTER
);
5140 [ 'user_editcount' => $count ],
5141 [ 'user_id' => $this->getId() ],
5149 * Get the description of a given right
5151 * @param string $right Right to query
5152 * @return string Localized description of the right
5154 public static function getRightDescription( $right ) {
5155 $key = "right-$right";
5156 $msg = wfMessage( $key );
5157 return $msg->isBlank() ?
$right : $msg->text();
5161 * Make a new-style password hash
5163 * @param string $password Plain-text password
5164 * @param bool|string $salt Optional salt, may be random or the user ID.
5165 * If unspecified or false, will generate one automatically
5166 * @return string Password hash
5167 * @deprecated since 1.24, use Password class
5169 public static function crypt( $password, $salt = false ) {
5170 wfDeprecated( __METHOD__
, '1.24' );
5171 $passwordFactory = new PasswordFactory();
5172 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
5173 $hash = $passwordFactory->newFromPlaintext( $password );
5174 return $hash->toString();
5178 * Compare a password hash with a plain-text password. Requires the user
5179 * ID if there's a chance that the hash is an old-style hash.
5181 * @param string $hash Password hash
5182 * @param string $password Plain-text password to compare
5183 * @param string|bool $userId User ID for old-style password salt
5186 * @deprecated since 1.24, use Password class
5188 public static function comparePasswords( $hash, $password, $userId = false ) {
5189 wfDeprecated( __METHOD__
, '1.24' );
5191 // Check for *really* old password hashes that don't even have a type
5192 // The old hash format was just an md5 hex hash, with no type information
5193 if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) {
5194 global $wgPasswordSalt;
5195 if ( $wgPasswordSalt ) {
5196 $password = ":B:{$userId}:{$hash}";
5198 $password = ":A:{$hash}";
5202 $passwordFactory = new PasswordFactory();
5203 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
5204 $hash = $passwordFactory->newFromCiphertext( $hash );
5205 return $hash->equals( $password );
5209 * Add a newuser log entry for this user.
5210 * Before 1.19 the return value was always true.
5212 * @deprecated since 1.27, AuthManager handles logging
5213 * @param string|bool $action Account creation type.
5214 * - String, one of the following values:
5215 * - 'create' for an anonymous user creating an account for himself.
5216 * This will force the action's performer to be the created user itself,
5217 * no matter the value of $wgUser
5218 * - 'create2' for a logged in user creating an account for someone else
5219 * - 'byemail' when the created user will receive its password by e-mail
5220 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
5221 * - Boolean means whether the account was created by e-mail (deprecated):
5222 * - true will be converted to 'byemail'
5223 * - false will be converted to 'create' if this object is the same as
5224 * $wgUser and to 'create2' otherwise
5225 * @param string $reason User supplied reason
5226 * @return int|bool True if not $wgNewUserLog or not $wgDisableAuthManager;
5227 * otherwise ID of log item or 0 on failure
5229 public function addNewUserLogEntry( $action = false, $reason = '' ) {
5230 global $wgUser, $wgNewUserLog, $wgDisableAuthManager;
5231 if ( !$wgDisableAuthManager ||
empty( $wgNewUserLog ) ) {
5232 return true; // disabled
5235 if ( $action === true ) {
5236 $action = 'byemail';
5237 } elseif ( $action === false ) {
5238 if ( $this->equals( $wgUser ) ) {
5241 $action = 'create2';
5245 if ( $action === 'create' ||
$action === 'autocreate' ) {
5248 $performer = $wgUser;
5251 $logEntry = new ManualLogEntry( 'newusers', $action );
5252 $logEntry->setPerformer( $performer );
5253 $logEntry->setTarget( $this->getUserPage() );
5254 $logEntry->setComment( $reason );
5255 $logEntry->setParameters( [
5256 '4::userid' => $this->getId(),
5258 $logid = $logEntry->insert();
5260 if ( $action !== 'autocreate' ) {
5261 $logEntry->publish( $logid );
5268 * Add an autocreate newuser log entry for this user
5269 * Used by things like CentralAuth and perhaps other authplugins.
5270 * Consider calling addNewUserLogEntry() directly instead.
5272 * @deprecated since 1.27, AuthManager handles logging
5275 public function addNewUserLogEntryAutoCreate() {
5276 $this->addNewUserLogEntry( 'autocreate' );
5282 * Load the user options either from cache, the database or an array
5284 * @param array $data Rows for the current user out of the user_properties table
5286 protected function loadOptions( $data = null ) {
5291 if ( $this->mOptionsLoaded
) {
5295 $this->mOptions
= self
::getDefaultOptions();
5297 if ( !$this->getId() ) {
5298 // For unlogged-in users, load language/variant options from request.
5299 // There's no need to do it for logged-in users: they can set preferences,
5300 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5301 // so don't override user's choice (especially when the user chooses site default).
5302 $variant = $wgContLang->getDefaultVariant();
5303 $this->mOptions
['variant'] = $variant;
5304 $this->mOptions
['language'] = $variant;
5305 $this->mOptionsLoaded
= true;
5309 // Maybe load from the object
5310 if ( !is_null( $this->mOptionOverrides
) ) {
5311 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5312 foreach ( $this->mOptionOverrides
as $key => $value ) {
5313 $this->mOptions
[$key] = $value;
5316 if ( !is_array( $data ) ) {
5317 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5318 // Load from database
5319 $dbr = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
5320 ?
wfGetDB( DB_MASTER
)
5321 : wfGetDB( DB_SLAVE
);
5323 $res = $dbr->select(
5325 [ 'up_property', 'up_value' ],
5326 [ 'up_user' => $this->getId() ],
5330 $this->mOptionOverrides
= [];
5332 foreach ( $res as $row ) {
5333 $data[$row->up_property
] = $row->up_value
;
5336 foreach ( $data as $property => $value ) {
5337 $this->mOptionOverrides
[$property] = $value;
5338 $this->mOptions
[$property] = $value;
5342 $this->mOptionsLoaded
= true;
5344 Hooks
::run( 'UserLoadOptions', [ $this, &$this->mOptions
] );
5348 * Saves the non-default options for this user, as previously set e.g. via
5349 * setOption(), in the database's "user_properties" (preferences) table.
5350 * Usually used via saveSettings().
5352 protected function saveOptions() {
5353 $this->loadOptions();
5355 // Not using getOptions(), to keep hidden preferences in database
5356 $saveOptions = $this->mOptions
;
5358 // Allow hooks to abort, for instance to save to a global profile.
5359 // Reset options to default state before saving.
5360 if ( !Hooks
::run( 'UserSaveOptions', [ $this, &$saveOptions ] ) ) {
5364 $userId = $this->getId();
5366 $insert_rows = []; // all the new preference rows
5367 foreach ( $saveOptions as $key => $value ) {
5368 // Don't bother storing default values
5369 $defaultOption = self
::getDefaultOption( $key );
5370 if ( ( $defaultOption === null && $value !== false && $value !== null )
5371 ||
$value != $defaultOption
5374 'up_user' => $userId,
5375 'up_property' => $key,
5376 'up_value' => $value,
5381 $dbw = wfGetDB( DB_MASTER
);
5383 $res = $dbw->select( 'user_properties',
5384 [ 'up_property', 'up_value' ], [ 'up_user' => $userId ], __METHOD__
);
5386 // Find prior rows that need to be removed or updated. These rows will
5387 // all be deleted (the later so that INSERT IGNORE applies the new values).
5389 foreach ( $res as $row ) {
5390 if ( !isset( $saveOptions[$row->up_property
] )
5391 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
5393 $keysDelete[] = $row->up_property
;
5397 if ( count( $keysDelete ) ) {
5398 // Do the DELETE by PRIMARY KEY for prior rows.
5399 // In the past a very large portion of calls to this function are for setting
5400 // 'rememberpassword' for new accounts (a preference that has since been removed).
5401 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5402 // caused gap locks on [max user ID,+infinity) which caused high contention since
5403 // updates would pile up on each other as they are for higher (newer) user IDs.
5404 // It might not be necessary these days, but it shouldn't hurt either.
5405 $dbw->delete( 'user_properties',
5406 [ 'up_user' => $userId, 'up_property' => $keysDelete ], __METHOD__
);
5408 // Insert the new preference rows
5409 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, [ 'IGNORE' ] );
5413 * Lazily instantiate and return a factory object for making passwords
5415 * @deprecated since 1.27, create a PasswordFactory directly instead
5416 * @return PasswordFactory
5418 public static function getPasswordFactory() {
5419 wfDeprecated( __METHOD__
, '1.27' );
5420 $ret = new PasswordFactory();
5421 $ret->init( RequestContext
::getMain()->getConfig() );
5426 * Provide an array of HTML5 attributes to put on an input element
5427 * intended for the user to enter a new password. This may include
5428 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
5430 * Do *not* use this when asking the user to enter his current password!
5431 * Regardless of configuration, users may have invalid passwords for whatever
5432 * reason (e.g., they were set before requirements were tightened up).
5433 * Only use it when asking for a new password, like on account creation or
5436 * Obviously, you still need to do server-side checking.
5438 * NOTE: A combination of bugs in various browsers means that this function
5439 * actually just returns array() unconditionally at the moment. May as
5440 * well keep it around for when the browser bugs get fixed, though.
5442 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
5444 * @deprecated since 1.27
5445 * @return array Array of HTML attributes suitable for feeding to
5446 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
5447 * That will get confused by the boolean attribute syntax used.)
5449 public static function passwordChangeInputAttribs() {
5450 global $wgMinimalPasswordLength;
5452 if ( $wgMinimalPasswordLength == 0 ) {
5456 # Note that the pattern requirement will always be satisfied if the
5457 # input is empty, so we need required in all cases.
5459 # @todo FIXME: Bug 23769: This needs to not claim the password is required
5460 # if e-mail confirmation is being used. Since HTML5 input validation
5461 # is b0rked anyway in some browsers, just return nothing. When it's
5462 # re-enabled, fix this code to not output required for e-mail
5464 # $ret = array( 'required' );
5467 # We can't actually do this right now, because Opera 9.6 will print out
5468 # the entered password visibly in its error message! When other
5469 # browsers add support for this attribute, or Opera fixes its support,
5470 # we can add support with a version check to avoid doing this on Opera
5471 # versions where it will be a problem. Reported to Opera as
5472 # DSK-262266, but they don't have a public bug tracker for us to follow.
5474 if ( $wgMinimalPasswordLength > 1 ) {
5475 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
5476 $ret['title'] = wfMessage( 'passwordtooshort' )
5477 ->numParams( $wgMinimalPasswordLength )->text();
5485 * Return the list of user fields that should be selected to create
5486 * a new user object.
5489 public static function selectFields() {
5497 'user_email_authenticated',
5499 'user_email_token_expires',
5500 'user_registration',
5506 * Factory function for fatal permission-denied errors
5509 * @param string $permission User right required
5512 static function newFatalPermissionDeniedStatus( $permission ) {
5515 $groups = array_map(
5516 [ 'User', 'makeGroupLinkWiki' ],
5517 User
::getGroupsWithPermission( $permission )
5521 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5523 return Status
::newFatal( 'badaccess-group0' );
5528 * Get a new instance of this user that was loaded from the master via a locking read
5530 * Use this instead of the main context User when updating that user. This avoids races
5531 * where that user was loaded from a slave or even the master but without proper locks.
5533 * @return User|null Returns null if the user was not found in the DB
5536 public function getInstanceForUpdate() {
5537 if ( !$this->getId() ) {
5538 return null; // anon
5541 $user = self
::newFromId( $this->getId() );
5542 if ( !$user->loadFromId( self
::READ_EXCLUSIVE
) ) {
5550 * Checks if two user objects point to the same user.
5556 public function equals( User
$user ) {
5557 return $this->getName() === $user->getName();