3 * Implements the User class for the %MediaWiki software.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use MediaWiki\MediaWikiServices
;
24 use MediaWiki\Session\SessionManager
;
25 use MediaWiki\Session\Token
;
26 use MediaWiki\Auth\AuthManager
;
27 use MediaWiki\Auth\AuthenticationResponse
;
28 use MediaWiki\Auth\AuthenticationRequest
;
31 * String Some punctuation to prevent editing from broken text-mangling proxies.
32 * @deprecated since 1.27, use \MediaWiki\Session\Token::SUFFIX
35 define( 'EDIT_TOKEN_SUFFIX', Token
::SUFFIX
);
38 * The User object encapsulates all of the user-specific settings (user_id,
39 * name, rights, email address, options, last login time). Client
40 * classes use the getXXX() functions to access these fields. These functions
41 * do all the work of determining whether the user is logged in,
42 * whether the requested option can be satisfied from cookies or
43 * whether a database query is needed. Most of the settings needed
44 * for rendering normal pages are set in the cookie to minimize use
47 class User
implements IDBAccessObject
{
49 * @const int Number of characters in user_token field.
51 const TOKEN_LENGTH
= 32;
54 * @const string An invalid value for user_token
56 const INVALID_TOKEN
= '*** INVALID ***';
59 * Global constant made accessible as class constants so that autoloader
61 * @deprecated since 1.27, use \MediaWiki\Session\Token::SUFFIX
63 const EDIT_TOKEN_SUFFIX
= EDIT_TOKEN_SUFFIX
;
66 * @const int Serialized record version.
71 * Exclude user options that are set to their default value.
74 const GETOPTIONS_EXCLUDE_DEFAULTS
= 1;
79 const CHECK_USER_RIGHTS
= true;
84 const IGNORE_USER_RIGHTS
= false;
87 * Array of Strings List of member variables which are saved to the
88 * shared cache (memcached). Any operation which changes the
89 * corresponding database fields must call a cache-clearing function.
92 protected static $mCacheVars = [
100 'mEmailAuthenticated',
102 'mEmailTokenExpires',
107 // user_properties table
112 * Array of Strings Core rights.
113 * Each of these should have a corresponding message of the form
117 protected static $mCoreRights = [
148 'editusercssjs', # deprecated
161 'move-categorypages',
162 'move-rootuserpages',
166 'override-export-depth',
189 'userrights-interwiki',
197 * String Cached results of getAllRights()
199 protected static $mAllRights = false;
201 /** Cache variables */
212 /** @var string TS_MW timestamp from the DB */
214 /** @var string TS_MW timestamp from cache */
215 protected $mQuickTouched;
219 public $mEmailAuthenticated;
221 protected $mEmailToken;
223 protected $mEmailTokenExpires;
225 protected $mRegistration;
227 protected $mEditCount;
231 protected $mOptionOverrides;
235 * Bool Whether the cache variables have been loaded.
238 public $mOptionsLoaded;
241 * Array with already loaded items or true if all items have been loaded.
243 protected $mLoadedItems = [];
247 * String Initialization data source if mLoadedItems!==true. May be one of:
248 * - 'defaults' anonymous user initialised from class defaults
249 * - 'name' initialise from mName
250 * - 'id' initialise from mId
251 * - 'session' log in from session if possible
253 * Use the User::newFrom*() family of functions to set this.
258 * Lazy-initialized variables, invalidated with clearInstanceCache
262 protected $mDatePreference;
270 protected $mBlockreason;
272 protected $mEffectiveGroups;
274 protected $mImplicitGroups;
276 protected $mFormerGroups;
278 protected $mGlobalBlock;
295 protected $mAllowUsertalk;
298 private $mBlockedFromCreateAccount = false;
300 /** @var integer User::READ_* constant bitfield used to load data */
301 protected $queryFlagsUsed = self
::READ_NORMAL
;
303 public static $idCacheByName = [];
306 * Lightweight constructor for an anonymous user.
307 * Use the User::newFrom* factory functions for other kinds of users.
311 * @see newFromConfirmationCode()
312 * @see newFromSession()
315 public function __construct() {
316 $this->clearInstanceCache( 'defaults' );
322 public function __toString() {
323 return $this->getName();
327 * Test if it's safe to load this User object.
329 * You should typically check this before using $wgUser or
330 * RequestContext::getUser in a method that might be called before the
331 * system has been fully initialized. If the object is unsafe, you should
332 * use an anonymous user:
334 * $user = $wgUser->isSafeToLoad() ? $wgUser : new User;
340 public function isSafeToLoad() {
341 global $wgFullyInitialised;
343 // The user is safe to load if:
344 // * MW_NO_SESSION is undefined AND $wgFullyInitialised is true (safe to use session data)
345 // * mLoadedItems === true (already loaded)
346 // * mFrom !== 'session' (sessions not involved at all)
348 return ( !defined( 'MW_NO_SESSION' ) && $wgFullyInitialised ) ||
349 $this->mLoadedItems
=== true ||
$this->mFrom
!== 'session';
353 * Load the user table data for this object from the source given by mFrom.
355 * @param integer $flags User::READ_* constant bitfield
357 public function load( $flags = self
::READ_NORMAL
) {
358 global $wgFullyInitialised;
360 if ( $this->mLoadedItems
=== true ) {
364 // Set it now to avoid infinite recursion in accessors
365 $oldLoadedItems = $this->mLoadedItems
;
366 $this->mLoadedItems
= true;
367 $this->queryFlagsUsed
= $flags;
369 // If this is called too early, things are likely to break.
370 if ( !$wgFullyInitialised && $this->mFrom
=== 'session' ) {
371 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
372 ->warning( 'User::loadFromSession called before the end of Setup.php', [
373 'exception' => new Exception( 'User::loadFromSession called before the end of Setup.php' ),
375 $this->loadDefaults();
376 $this->mLoadedItems
= $oldLoadedItems;
380 switch ( $this->mFrom
) {
382 $this->loadDefaults();
385 // Make sure this thread sees its own changes
386 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
387 $flags |
= self
::READ_LATEST
;
388 $this->queryFlagsUsed
= $flags;
391 $this->mId
= self
::idFromName( $this->mName
, $flags );
393 // Nonexistent user placeholder object
394 $this->loadDefaults( $this->mName
);
396 $this->loadFromId( $flags );
400 $this->loadFromId( $flags );
403 if ( !$this->loadFromSession() ) {
404 // Loading from session failed. Load defaults.
405 $this->loadDefaults();
407 Hooks
::run( 'UserLoadAfterLoadFromSession', [ $this ] );
410 throw new UnexpectedValueException(
411 "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
416 * Load user table data, given mId has already been set.
417 * @param integer $flags User::READ_* constant bitfield
418 * @return bool False if the ID does not exist, true otherwise
420 public function loadFromId( $flags = self
::READ_NORMAL
) {
421 if ( $this->mId
== 0 ) {
422 // Anonymous users are not in the database (don't need cache)
423 $this->loadDefaults();
427 // Try cache (unless this needs data from the master DB).
428 // NOTE: if this thread called saveSettings(), the cache was cleared.
429 $latest = DBAccessObjectUtils
::hasFlags( $flags, self
::READ_LATEST
);
431 if ( !$this->loadFromDatabase( $flags ) ) {
432 // Can't load from ID
436 $this->loadFromCache();
439 $this->mLoadedItems
= true;
440 $this->queryFlagsUsed
= $flags;
447 * @param string $wikiId
448 * @param integer $userId
450 public static function purge( $wikiId, $userId ) {
451 $cache = ObjectCache
::getMainWANInstance();
452 $key = $cache->makeGlobalKey( 'user', 'id', $wikiId, $userId );
453 $cache->delete( $key );
458 * @param WANObjectCache $cache
461 protected function getCacheKey( WANObjectCache
$cache ) {
462 return $cache->makeGlobalKey( 'user', 'id', wfWikiID(), $this->mId
);
466 * Load user data from shared cache, given mId has already been set.
471 protected function loadFromCache() {
472 $cache = ObjectCache
::getMainWANInstance();
473 $data = $cache->getWithSetCallback(
474 $this->getCacheKey( $cache ),
476 function ( $oldValue, &$ttl, array &$setOpts ) {
477 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_SLAVE
) );
478 wfDebug( "User: cache miss for user {$this->mId}\n" );
480 $this->loadFromDatabase( self
::READ_NORMAL
);
482 $this->loadOptions();
485 foreach ( self
::$mCacheVars as $name ) {
486 $data[$name] = $this->$name;
492 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'version' => self
::VERSION
]
495 // Restore from cache
496 foreach ( self
::$mCacheVars as $name ) {
497 $this->$name = $data[$name];
503 /** @name newFrom*() static factory methods */
507 * Static factory method for creation from username.
509 * This is slightly less efficient than newFromId(), so use newFromId() if
510 * you have both an ID and a name handy.
512 * @param string $name Username, validated by Title::newFromText()
513 * @param string|bool $validate Validate username. Takes the same parameters as
514 * User::getCanonicalName(), except that true is accepted as an alias
515 * for 'valid', for BC.
517 * @return User|bool User object, or false if the username is invalid
518 * (e.g. if it contains illegal characters or is an IP address). If the
519 * username is not present in the database, the result will be a user object
520 * with a name, zero user ID and default settings.
522 public static function newFromName( $name, $validate = 'valid' ) {
523 if ( $validate === true ) {
526 $name = self
::getCanonicalName( $name, $validate );
527 if ( $name === false ) {
530 // Create unloaded user object
534 $u->setItemLoaded( 'name' );
540 * Static factory method for creation from a given user ID.
542 * @param int $id Valid user ID
543 * @return User The corresponding User object
545 public static function newFromId( $id ) {
549 $u->setItemLoaded( 'id' );
554 * Factory method to fetch whichever user has a given email confirmation code.
555 * This code is generated when an account is created or its e-mail address
558 * If the code is invalid or has expired, returns NULL.
560 * @param string $code Confirmation code
561 * @param int $flags User::READ_* bitfield
564 public static function newFromConfirmationCode( $code, $flags = 0 ) {
565 $db = ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
566 ?
wfGetDB( DB_MASTER
)
567 : wfGetDB( DB_SLAVE
);
569 $id = $db->selectField(
573 'user_email_token' => md5( $code ),
574 'user_email_token_expires > ' . $db->addQuotes( $db->timestamp() ),
578 return $id ? User
::newFromId( $id ) : null;
582 * Create a new user object using data from session. If the login
583 * credentials are invalid, the result is an anonymous user.
585 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
588 public static function newFromSession( WebRequest
$request = null ) {
590 $user->mFrom
= 'session';
591 $user->mRequest
= $request;
596 * Create a new user object from a user row.
597 * The row should have the following fields from the user table in it:
598 * - either user_name or user_id to load further data if needed (or both)
600 * - all other fields (email, etc.)
601 * It is useless to provide the remaining fields if either user_id,
602 * user_name and user_real_name are not provided because the whole row
603 * will be loaded once more from the database when accessing them.
605 * @param stdClass $row A row from the user table
606 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
609 public static function newFromRow( $row, $data = null ) {
611 $user->loadFromRow( $row, $data );
616 * Static factory method for creation of a "system" user from username.
618 * A "system" user is an account that's used to attribute logged actions
619 * taken by MediaWiki itself, as opposed to a bot or human user. Examples
620 * might include the 'Maintenance script' or 'Conversion script' accounts
621 * used by various scripts in the maintenance/ directory or accounts such
622 * as 'MediaWiki message delivery' used by the MassMessage extension.
624 * This can optionally create the user if it doesn't exist, and "steal" the
625 * account if it does exist.
627 * "Stealing" an existing user is intended to make it impossible for normal
628 * authentication processes to use the account, effectively disabling the
629 * account for normal use:
630 * - Email is invalidated, to prevent account recovery by emailing a
631 * temporary password and to disassociate the account from the existing
633 * - The token is set to a magic invalid value, to kill existing sessions
634 * and to prevent $this->setToken() calls from resetting the token to a
636 * - SessionManager is instructed to prevent new sessions for the user, to
637 * do things like deauthorizing OAuth consumers.
638 * - AuthManager is instructed to revoke access, to invalidate or remove
639 * passwords and other credentials.
641 * @param string $name Username
642 * @param array $options Options are:
643 * - validate: As for User::getCanonicalName(), default 'valid'
644 * - create: Whether to create the user if it doesn't already exist, default true
645 * - steal: Whether to "disable" the account for normal use if it already
646 * exists, default false
650 public static function newSystemUser( $name, $options = [] ) {
652 'validate' => 'valid',
657 $name = self
::getCanonicalName( $name, $options['validate'] );
658 if ( $name === false ) {
662 $fields = self
::selectFields();
664 $dbw = wfGetDB( DB_MASTER
);
665 $row = $dbw->selectRow(
668 [ 'user_name' => $name ],
672 // No user. Create it?
673 return $options['create'] ? self
::createNew( $name ) : null;
675 $user = self
::newFromRow( $row );
677 // A user is considered to exist as a non-system user if it can
678 // authenticate, or has an email set, or has a non-invalid token.
679 if ( $user->mEmail ||
$user->mToken
!== self
::INVALID_TOKEN ||
680 AuthManager
::singleton()->userCanAuthenticate( $name )
682 // User exists. Steal it?
683 if ( !$options['steal'] ) {
687 AuthManager
::singleton()->revokeAccessForUser( $name );
689 $user->invalidateEmail();
690 $user->mToken
= self
::INVALID_TOKEN
;
691 $user->saveSettings();
692 SessionManager
::singleton()->preventSessionsForUser( $user->getName() );
701 * Get the username corresponding to a given user ID
702 * @param int $id User ID
703 * @return string|bool The corresponding username
705 public static function whoIs( $id ) {
706 return UserCache
::singleton()->getProp( $id, 'name' );
710 * Get the real name of a user given their user ID
712 * @param int $id User ID
713 * @return string|bool The corresponding user's real name
715 public static function whoIsReal( $id ) {
716 return UserCache
::singleton()->getProp( $id, 'real_name' );
720 * Get database id given a user name
721 * @param string $name Username
722 * @param integer $flags User::READ_* constant bitfield
723 * @return int|null The corresponding user's ID, or null if user is nonexistent
725 public static function idFromName( $name, $flags = self
::READ_NORMAL
) {
726 $nt = Title
::makeTitleSafe( NS_USER
, $name );
727 if ( is_null( $nt ) ) {
732 if ( !( $flags & self
::READ_LATEST
) && isset( self
::$idCacheByName[$name] ) ) {
733 return self
::$idCacheByName[$name];
736 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
737 $db = wfGetDB( $index );
742 [ 'user_name' => $nt->getText() ],
747 if ( $s === false ) {
750 $result = $s->user_id
;
753 self
::$idCacheByName[$name] = $result;
755 if ( count( self
::$idCacheByName ) > 1000 ) {
756 self
::$idCacheByName = [];
763 * Reset the cache used in idFromName(). For use in tests.
765 public static function resetIdByNameCache() {
766 self
::$idCacheByName = [];
770 * Does the string match an anonymous IP address?
772 * This function exists for username validation, in order to reject
773 * usernames which are similar in form to IP addresses. Strings such
774 * as 300.300.300.300 will return true because it looks like an IP
775 * address, despite not being strictly valid.
777 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
778 * address because the usemod software would "cloak" anonymous IP
779 * addresses like this, if we allowed accounts like this to be created
780 * new users could get the old edits of these anonymous users.
782 * @param string $name Name to match
785 public static function isIP( $name ) {
786 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
787 || IP
::isIPv6( $name );
791 * Is the input a valid username?
793 * Checks if the input is a valid username, we don't want an empty string,
794 * an IP address, anything that contains slashes (would mess up subpages),
795 * is longer than the maximum allowed username size or doesn't begin with
798 * @param string $name Name to match
801 public static function isValidUserName( $name ) {
802 global $wgContLang, $wgMaxNameChars;
805 || User
::isIP( $name )
806 ||
strpos( $name, '/' ) !== false
807 ||
strlen( $name ) > $wgMaxNameChars
808 ||
$name != $wgContLang->ucfirst( $name )
813 // Ensure that the name can't be misresolved as a different title,
814 // such as with extra namespace keys at the start.
815 $parsed = Title
::newFromText( $name );
816 if ( is_null( $parsed )
817 ||
$parsed->getNamespace()
818 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
822 // Check an additional blacklist of troublemaker characters.
823 // Should these be merged into the title char list?
824 $unicodeBlacklist = '/[' .
825 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
826 '\x{00a0}' . # non-breaking space
827 '\x{2000}-\x{200f}' . # various whitespace
828 '\x{2028}-\x{202f}' . # breaks and control chars
829 '\x{3000}' . # ideographic space
830 '\x{e000}-\x{f8ff}' . # private use
832 if ( preg_match( $unicodeBlacklist, $name ) ) {
840 * Usernames which fail to pass this function will be blocked
841 * from user login and new account registrations, but may be used
842 * internally by batch processes.
844 * If an account already exists in this form, login will be blocked
845 * by a failure to pass this function.
847 * @param string $name Name to match
850 public static function isUsableName( $name ) {
851 global $wgReservedUsernames;
852 // Must be a valid username, obviously ;)
853 if ( !self
::isValidUserName( $name ) ) {
857 static $reservedUsernames = false;
858 if ( !$reservedUsernames ) {
859 $reservedUsernames = $wgReservedUsernames;
860 Hooks
::run( 'UserGetReservedNames', [ &$reservedUsernames ] );
863 // Certain names may be reserved for batch processes.
864 foreach ( $reservedUsernames as $reserved ) {
865 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
866 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
868 if ( $reserved == $name ) {
876 * Return the users who are members of the given group(s). In case of multiple groups,
877 * users who are members of at least one of them are returned.
879 * @param string|array $groups A single group name or an array of group names
880 * @param int $limit Max number of users to return. The actual limit will never exceed 5000
881 * records; larger values are ignored.
882 * @param int $after ID the user to start after
883 * @return UserArrayFromResult
885 public static function findUsersByGroup( $groups, $limit = 5000, $after = null ) {
886 if ( $groups === [] ) {
887 return UserArrayFromResult
::newFromIDs( [] );
890 $groups = array_unique( (array)$groups );
891 $limit = min( 5000, $limit );
893 $conds = [ 'ug_group' => $groups ];
894 if ( $after !== null ) {
895 $conds[] = 'ug_user > ' . (int)$after;
898 $dbr = wfGetDB( DB_SLAVE
);
899 $ids = $dbr->selectFieldValues(
906 'ORDER BY' => 'ug_user',
910 return UserArray
::newFromIDs( $ids );
914 * Usernames which fail to pass this function will be blocked
915 * from new account registrations, but may be used internally
916 * either by batch processes or by user accounts which have
917 * already been created.
919 * Additional blacklisting may be added here rather than in
920 * isValidUserName() to avoid disrupting existing accounts.
922 * @param string $name String to match
925 public static function isCreatableName( $name ) {
926 global $wgInvalidUsernameCharacters;
928 // Ensure that the username isn't longer than 235 bytes, so that
929 // (at least for the builtin skins) user javascript and css files
930 // will work. (bug 23080)
931 if ( strlen( $name ) > 235 ) {
932 wfDebugLog( 'username', __METHOD__
.
933 ": '$name' invalid due to length" );
937 // Preg yells if you try to give it an empty string
938 if ( $wgInvalidUsernameCharacters !== '' ) {
939 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
940 wfDebugLog( 'username', __METHOD__
.
941 ": '$name' invalid due to wgInvalidUsernameCharacters" );
946 return self
::isUsableName( $name );
950 * Is the input a valid password for this user?
952 * @param string $password Desired password
955 public function isValidPassword( $password ) {
956 // simple boolean wrapper for getPasswordValidity
957 return $this->getPasswordValidity( $password ) === true;
961 * Given unvalidated password input, return error message on failure.
963 * @param string $password Desired password
964 * @return bool|string|array True on success, string or array of error message on failure
966 public function getPasswordValidity( $password ) {
967 $result = $this->checkPasswordValidity( $password );
968 if ( $result->isGood() ) {
972 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
973 $messages[] = $error['message'];
975 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
976 $messages[] = $warning['message'];
978 if ( count( $messages ) === 1 ) {
986 * Check if this is a valid password for this user
988 * Create a Status object based on the password's validity.
989 * The Status should be set to fatal if the user should not
990 * be allowed to log in, and should have any errors that
991 * would block changing the password.
993 * If the return value of this is not OK, the password
994 * should not be checked. If the return value is not Good,
995 * the password can be checked, but the user should not be
996 * able to set their password to this.
998 * @param string $password Desired password
999 * @param string $purpose one of 'login', 'create', 'reset'
1003 public function checkPasswordValidity( $password, $purpose = 'login' ) {
1004 global $wgPasswordPolicy;
1006 $upp = new UserPasswordPolicy(
1007 $wgPasswordPolicy['policies'],
1008 $wgPasswordPolicy['checks']
1011 $status = Status
::newGood();
1012 $result = false; // init $result to false for the internal checks
1014 if ( !Hooks
::run( 'isValidPassword', [ $password, &$result, $this ] ) ) {
1015 $status->error( $result );
1019 if ( $result === false ) {
1020 $status->merge( $upp->checkUserPassword( $this, $password, $purpose ) );
1022 } elseif ( $result === true ) {
1025 $status->error( $result );
1026 return $status; // the isValidPassword hook set a string $result and returned true
1031 * Given unvalidated user input, return a canonical username, or false if
1032 * the username is invalid.
1033 * @param string $name User input
1034 * @param string|bool $validate Type of validation to use:
1035 * - false No validation
1036 * - 'valid' Valid for batch processes
1037 * - 'usable' Valid for batch processes and login
1038 * - 'creatable' Valid for batch processes, login and account creation
1040 * @throws InvalidArgumentException
1041 * @return bool|string
1043 public static function getCanonicalName( $name, $validate = 'valid' ) {
1044 // Force usernames to capital
1046 $name = $wgContLang->ucfirst( $name );
1048 # Reject names containing '#'; these will be cleaned up
1049 # with title normalisation, but then it's too late to
1051 if ( strpos( $name, '#' ) !== false ) {
1055 // Clean up name according to title rules,
1056 // but only when validation is requested (bug 12654)
1057 $t = ( $validate !== false ) ?
1058 Title
::newFromText( $name, NS_USER
) : Title
::makeTitle( NS_USER
, $name );
1059 // Check for invalid titles
1060 if ( is_null( $t ) ||
$t->getNamespace() !== NS_USER ||
$t->isExternal() ) {
1064 // Reject various classes of invalid names
1065 $name = AuthManager
::callLegacyAuthPlugin(
1066 'getCanonicalName', [ $t->getText() ], $t->getText()
1069 switch ( $validate ) {
1073 if ( !User
::isValidUserName( $name ) ) {
1078 if ( !User
::isUsableName( $name ) ) {
1083 if ( !User
::isCreatableName( $name ) ) {
1088 throw new InvalidArgumentException(
1089 'Invalid parameter value for $validate in ' . __METHOD__
);
1095 * Count the number of edits of a user
1097 * @param int $uid User ID to check
1098 * @return int The user's edit count
1100 * @deprecated since 1.21 in favour of User::getEditCount
1102 public static function edits( $uid ) {
1103 wfDeprecated( __METHOD__
, '1.21' );
1104 $user = self
::newFromId( $uid );
1105 return $user->getEditCount();
1109 * Return a random password.
1111 * @deprecated since 1.27, use PasswordFactory::generateRandomPasswordString()
1112 * @return string New random password
1114 public static function randomPassword() {
1115 global $wgMinimalPasswordLength;
1116 return PasswordFactory
::generateRandomPasswordString( $wgMinimalPasswordLength );
1120 * Set cached properties to default.
1122 * @note This no longer clears uncached lazy-initialised properties;
1123 * the constructor does that instead.
1125 * @param string|bool $name
1127 public function loadDefaults( $name = false ) {
1129 $this->mName
= $name;
1130 $this->mRealName
= '';
1132 $this->mOptionOverrides
= null;
1133 $this->mOptionsLoaded
= false;
1135 $loggedOut = $this->mRequest
&& !defined( 'MW_NO_SESSION' )
1136 ?
$this->mRequest
->getSession()->getLoggedOutTimestamp() : 0;
1137 if ( $loggedOut !== 0 ) {
1138 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1140 $this->mTouched
= '1'; # Allow any pages to be cached
1143 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1144 $this->mEmailAuthenticated
= null;
1145 $this->mEmailToken
= '';
1146 $this->mEmailTokenExpires
= null;
1147 $this->mRegistration
= wfTimestamp( TS_MW
);
1148 $this->mGroups
= [];
1150 Hooks
::run( 'UserLoadDefaults', [ $this, $name ] );
1154 * Return whether an item has been loaded.
1156 * @param string $item Item to check. Current possibilities:
1160 * @param string $all 'all' to check if the whole object has been loaded
1161 * or any other string to check if only the item is available (e.g.
1165 public function isItemLoaded( $item, $all = 'all' ) {
1166 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1167 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1171 * Set that an item has been loaded
1173 * @param string $item
1175 protected function setItemLoaded( $item ) {
1176 if ( is_array( $this->mLoadedItems
) ) {
1177 $this->mLoadedItems
[$item] = true;
1182 * Load user data from the session.
1184 * @return bool True if the user is logged in, false otherwise.
1186 private function loadFromSession() {
1189 Hooks
::run( 'UserLoadFromSession', [ $this, &$result ], '1.27' );
1190 if ( $result !== null ) {
1194 // MediaWiki\Session\Session already did the necessary authentication of the user
1195 // returned here, so just use it if applicable.
1196 $session = $this->getRequest()->getSession();
1197 $user = $session->getUser();
1198 if ( $user->isLoggedIn() ) {
1199 $this->loadFromUserObject( $user );
1200 // Other code expects these to be set in the session, so set them.
1201 $session->set( 'wsUserID', $this->getId() );
1202 $session->set( 'wsUserName', $this->getName() );
1203 $session->set( 'wsToken', $this->getToken() );
1211 * Load user and user_group data from the database.
1212 * $this->mId must be set, this is how the user is identified.
1214 * @param integer $flags User::READ_* constant bitfield
1215 * @return bool True if the user exists, false if the user is anonymous
1217 public function loadFromDatabase( $flags = self
::READ_LATEST
) {
1219 $this->mId
= intval( $this->mId
);
1221 if ( !$this->mId
) {
1222 // Anonymous users are not in the database
1223 $this->loadDefaults();
1227 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
1228 $db = wfGetDB( $index );
1230 $s = $db->selectRow(
1232 self
::selectFields(),
1233 [ 'user_id' => $this->mId
],
1238 $this->queryFlagsUsed
= $flags;
1239 Hooks
::run( 'UserLoadFromDatabase', [ $this, &$s ] );
1241 if ( $s !== false ) {
1242 // Initialise user table data
1243 $this->loadFromRow( $s );
1244 $this->mGroups
= null; // deferred
1245 $this->getEditCount(); // revalidation for nulls
1250 $this->loadDefaults();
1256 * Initialize this object from a row from the user table.
1258 * @param stdClass $row Row from the user table to load.
1259 * @param array $data Further user data to load into the object
1261 * user_groups Array with groups out of the user_groups table
1262 * user_properties Array with properties out of the user_properties table
1264 protected function loadFromRow( $row, $data = null ) {
1267 $this->mGroups
= null; // deferred
1269 if ( isset( $row->user_name
) ) {
1270 $this->mName
= $row->user_name
;
1271 $this->mFrom
= 'name';
1272 $this->setItemLoaded( 'name' );
1277 if ( isset( $row->user_real_name
) ) {
1278 $this->mRealName
= $row->user_real_name
;
1279 $this->setItemLoaded( 'realname' );
1284 if ( isset( $row->user_id
) ) {
1285 $this->mId
= intval( $row->user_id
);
1286 $this->mFrom
= 'id';
1287 $this->setItemLoaded( 'id' );
1292 if ( isset( $row->user_id
) && isset( $row->user_name
) ) {
1293 self
::$idCacheByName[$row->user_name
] = $row->user_id
;
1296 if ( isset( $row->user_editcount
) ) {
1297 $this->mEditCount
= $row->user_editcount
;
1302 if ( isset( $row->user_touched
) ) {
1303 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1308 if ( isset( $row->user_token
) ) {
1309 // The definition for the column is binary(32), so trim the NULs
1310 // that appends. The previous definition was char(32), so trim
1312 $this->mToken
= rtrim( $row->user_token
, " \0" );
1313 if ( $this->mToken
=== '' ) {
1314 $this->mToken
= null;
1320 if ( isset( $row->user_email
) ) {
1321 $this->mEmail
= $row->user_email
;
1322 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1323 $this->mEmailToken
= $row->user_email_token
;
1324 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1325 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1331 $this->mLoadedItems
= true;
1334 if ( is_array( $data ) ) {
1335 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1336 $this->mGroups
= $data['user_groups'];
1338 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1339 $this->loadOptions( $data['user_properties'] );
1345 * Load the data for this user object from another user object.
1349 protected function loadFromUserObject( $user ) {
1351 foreach ( self
::$mCacheVars as $var ) {
1352 $this->$var = $user->$var;
1357 * Load the groups from the database if they aren't already loaded.
1359 private function loadGroups() {
1360 if ( is_null( $this->mGroups
) ) {
1361 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
1362 ?
wfGetDB( DB_MASTER
)
1363 : wfGetDB( DB_SLAVE
);
1364 $res = $db->select( 'user_groups',
1366 [ 'ug_user' => $this->mId
],
1368 $this->mGroups
= [];
1369 foreach ( $res as $row ) {
1370 $this->mGroups
[] = $row->ug_group
;
1376 * Add the user to the group if he/she meets given criteria.
1378 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1379 * possible to remove manually via Special:UserRights. In such case it
1380 * will not be re-added automatically. The user will also not lose the
1381 * group if they no longer meet the criteria.
1383 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1385 * @return array Array of groups the user has been promoted to.
1387 * @see $wgAutopromoteOnce
1389 public function addAutopromoteOnceGroups( $event ) {
1390 global $wgAutopromoteOnceLogInRC;
1392 if ( wfReadOnly() ||
!$this->getId() ) {
1396 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1397 if ( !count( $toPromote ) ) {
1401 if ( !$this->checkAndSetTouched() ) {
1402 return []; // raced out (bug T48834)
1405 $oldGroups = $this->getGroups(); // previous groups
1406 foreach ( $toPromote as $group ) {
1407 $this->addGroup( $group );
1409 // update groups in external authentication database
1410 Hooks
::run( 'UserGroupsChanged', [ $this, $toPromote, [], false, false ] );
1411 AuthManager
::callLegacyAuthPlugin( 'updateExternalDBGroups', [ $this, $toPromote ] );
1413 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1415 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1416 $logEntry->setPerformer( $this );
1417 $logEntry->setTarget( $this->getUserPage() );
1418 $logEntry->setParameters( [
1419 '4::oldgroups' => $oldGroups,
1420 '5::newgroups' => $newGroups,
1422 $logid = $logEntry->insert();
1423 if ( $wgAutopromoteOnceLogInRC ) {
1424 $logEntry->publish( $logid );
1431 * Builds update conditions. Additional conditions may be added to $conditions to
1432 * protected against race conditions using a compare-and-set (CAS) mechanism
1433 * based on comparing $this->mTouched with the user_touched field.
1435 * @param DatabaseBase $db
1436 * @param array $conditions WHERE conditions for use with DatabaseBase::update
1437 * @return array WHERE conditions for use with DatabaseBase::update
1439 protected function makeUpdateConditions( DatabaseBase
$db, array $conditions ) {
1440 if ( $this->mTouched
) {
1441 // CAS check: only update if the row wasn't changed sicne it was loaded.
1442 $conditions['user_touched'] = $db->timestamp( $this->mTouched
);
1449 * Bump user_touched if it didn't change since this object was loaded
1451 * On success, the mTouched field is updated.
1452 * The user serialization cache is always cleared.
1454 * @return bool Whether user_touched was actually updated
1457 protected function checkAndSetTouched() {
1460 if ( !$this->mId
) {
1461 return false; // anon
1464 // Get a new user_touched that is higher than the old one
1465 $newTouched = $this->newTouchedTimestamp();
1467 $dbw = wfGetDB( DB_MASTER
);
1468 $dbw->update( 'user',
1469 [ 'user_touched' => $dbw->timestamp( $newTouched ) ],
1470 $this->makeUpdateConditions( $dbw, [
1471 'user_id' => $this->mId
,
1475 $success = ( $dbw->affectedRows() > 0 );
1478 $this->mTouched
= $newTouched;
1479 $this->clearSharedCache();
1481 // Clears on failure too since that is desired if the cache is stale
1482 $this->clearSharedCache( 'refresh' );
1489 * Clear various cached data stored in this object. The cache of the user table
1490 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1492 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1493 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1495 public function clearInstanceCache( $reloadFrom = false ) {
1496 $this->mNewtalk
= -1;
1497 $this->mDatePreference
= null;
1498 $this->mBlockedby
= -1; # Unset
1499 $this->mHash
= false;
1500 $this->mRights
= null;
1501 $this->mEffectiveGroups
= null;
1502 $this->mImplicitGroups
= null;
1503 $this->mGroups
= null;
1504 $this->mOptions
= null;
1505 $this->mOptionsLoaded
= false;
1506 $this->mEditCount
= null;
1508 if ( $reloadFrom ) {
1509 $this->mLoadedItems
= [];
1510 $this->mFrom
= $reloadFrom;
1515 * Combine the language default options with any site-specific options
1516 * and add the default language variants.
1518 * @return array Array of String options
1520 public static function getDefaultOptions() {
1521 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1523 static $defOpt = null;
1524 static $defOptLang = null;
1526 if ( $defOpt !== null && $defOptLang === $wgContLang->getCode() ) {
1527 // $wgContLang does not change (and should not change) mid-request,
1528 // but the unit tests change it anyway, and expect this method to
1529 // return values relevant to the current $wgContLang.
1533 $defOpt = $wgDefaultUserOptions;
1534 // Default language setting
1535 $defOptLang = $wgContLang->getCode();
1536 $defOpt['language'] = $defOptLang;
1537 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1538 $defOpt[$langCode == $wgContLang->getCode() ?
'variant' : "variant-$langCode"] = $langCode;
1540 $namespaces = MediaWikiServices
::getInstance()->getSearchEngineConfig()->searchableNamespaces();
1541 foreach ( $namespaces as $nsnum => $nsname ) {
1542 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1544 $defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1546 Hooks
::run( 'UserGetDefaultOptions', [ &$defOpt ] );
1552 * Get a given default option value.
1554 * @param string $opt Name of option to retrieve
1555 * @return string Default option value
1557 public static function getDefaultOption( $opt ) {
1558 $defOpts = self
::getDefaultOptions();
1559 if ( isset( $defOpts[$opt] ) ) {
1560 return $defOpts[$opt];
1567 * Get blocking information
1568 * @param bool $bFromSlave Whether to check the slave database first.
1569 * To improve performance, non-critical checks are done against slaves.
1570 * Check when actually saving should be done against master.
1572 private function getBlockedStatus( $bFromSlave = true ) {
1573 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1575 if ( -1 != $this->mBlockedby
) {
1579 wfDebug( __METHOD__
. ": checking...\n" );
1581 // Initialize data...
1582 // Otherwise something ends up stomping on $this->mBlockedby when
1583 // things get lazy-loaded later, causing false positive block hits
1584 // due to -1 !== 0. Probably session-related... Nothing should be
1585 // overwriting mBlockedby, surely?
1588 # We only need to worry about passing the IP address to the Block generator if the
1589 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1590 # know which IP address they're actually coming from
1592 if ( !$this->isAllowed( 'ipblock-exempt' ) ) {
1593 // $wgUser->getName() only works after the end of Setup.php. Until
1594 // then, assume it's a logged-out user.
1595 $globalUserName = $wgUser->isSafeToLoad()
1596 ?
$wgUser->getName()
1597 : IP
::sanitizeIP( $wgUser->getRequest()->getIP() );
1598 if ( $this->getName() === $globalUserName ) {
1599 $ip = $this->getRequest()->getIP();
1604 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1607 if ( !$block instanceof Block
&& $ip !== null && !in_array( $ip, $wgProxyWhitelist ) ) {
1609 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1611 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1612 $block->mReason
= wfMessage( 'proxyblockreason' )->text();
1613 $block->setTarget( $ip );
1614 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1616 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1617 $block->mReason
= wfMessage( 'sorbsreason' )->text();
1618 $block->setTarget( $ip );
1622 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1623 if ( !$block instanceof Block
1624 && $wgApplyIpBlocksToXff
1626 && !in_array( $ip, $wgProxyWhitelist )
1628 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1629 $xff = array_map( 'trim', explode( ',', $xff ) );
1630 $xff = array_diff( $xff, [ $ip ] );
1631 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1632 $block = Block
::chooseBlock( $xffblocks, $xff );
1633 if ( $block instanceof Block
) {
1634 # Mangle the reason to alert the user that the block
1635 # originated from matching the X-Forwarded-For header.
1636 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->text();
1640 if ( $block instanceof Block
) {
1641 wfDebug( __METHOD__
. ": Found block.\n" );
1642 $this->mBlock
= $block;
1643 $this->mBlockedby
= $block->getByName();
1644 $this->mBlockreason
= $block->mReason
;
1645 $this->mHideName
= $block->mHideName
;
1646 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1648 $this->mBlockedby
= '';
1649 $this->mHideName
= 0;
1650 $this->mAllowUsertalk
= false;
1654 Hooks
::run( 'GetBlockedStatus', [ &$this ] );
1659 * Whether the given IP is in a DNS blacklist.
1661 * @param string $ip IP to check
1662 * @param bool $checkWhitelist Whether to check the whitelist first
1663 * @return bool True if blacklisted.
1665 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1666 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1668 if ( !$wgEnableDnsBlacklist ) {
1672 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1676 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1680 * Whether the given IP is in a given DNS blacklist.
1682 * @param string $ip IP to check
1683 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1684 * @return bool True if blacklisted.
1686 public function inDnsBlacklist( $ip, $bases ) {
1689 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1690 if ( IP
::isIPv4( $ip ) ) {
1691 // Reverse IP, bug 21255
1692 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1694 foreach ( (array)$bases as $base ) {
1696 // If we have an access key, use that too (ProjectHoneypot, etc.)
1698 if ( is_array( $base ) ) {
1699 if ( count( $base ) >= 2 ) {
1700 // Access key is 1, base URL is 0
1701 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1703 $host = "$ipReversed.{$base[0]}";
1705 $basename = $base[0];
1707 $host = "$ipReversed.$base";
1711 $ipList = gethostbynamel( $host );
1714 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
1718 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
1727 * Check if an IP address is in the local proxy list
1733 public static function isLocallyBlockedProxy( $ip ) {
1734 global $wgProxyList;
1736 if ( !$wgProxyList ) {
1740 if ( !is_array( $wgProxyList ) ) {
1741 // Load from the specified file
1742 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1745 if ( !is_array( $wgProxyList ) ) {
1747 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1749 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1750 // Old-style flipped proxy list
1759 * Is this user subject to rate limiting?
1761 * @return bool True if rate limited
1763 public function isPingLimitable() {
1764 global $wgRateLimitsExcludedIPs;
1765 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1766 // No other good way currently to disable rate limits
1767 // for specific IPs. :P
1768 // But this is a crappy hack and should die.
1771 return !$this->isAllowed( 'noratelimit' );
1775 * Primitive rate limits: enforce maximum actions per time period
1776 * to put a brake on flooding.
1778 * The method generates both a generic profiling point and a per action one
1779 * (suffix being "-$action".
1781 * @note When using a shared cache like memcached, IP-address
1782 * last-hit counters will be shared across wikis.
1784 * @param string $action Action to enforce; 'edit' if unspecified
1785 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1786 * @return bool True if a rate limiter was tripped
1788 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1789 // Call the 'PingLimiter' hook
1791 if ( !Hooks
::run( 'PingLimiter', [ &$this, $action, &$result, $incrBy ] ) ) {
1795 global $wgRateLimits;
1796 if ( !isset( $wgRateLimits[$action] ) ) {
1800 // Some groups shouldn't trigger the ping limiter, ever
1801 if ( !$this->isPingLimitable() ) {
1805 $limits = $wgRateLimits[$action];
1807 $id = $this->getId();
1809 $isNewbie = $this->isNewbie();
1813 if ( isset( $limits['anon'] ) ) {
1814 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1817 // limits for logged-in users
1818 if ( isset( $limits['user'] ) ) {
1819 $userLimit = $limits['user'];
1821 // limits for newbie logged-in users
1822 if ( $isNewbie && isset( $limits['newbie'] ) ) {
1823 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1827 // limits for anons and for newbie logged-in users
1830 if ( isset( $limits['ip'] ) ) {
1831 $ip = $this->getRequest()->getIP();
1832 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1834 // subnet-based limits
1835 if ( isset( $limits['subnet'] ) ) {
1836 $ip = $this->getRequest()->getIP();
1837 $subnet = IP
::getSubnet( $ip );
1838 if ( $subnet !== false ) {
1839 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1844 // Check for group-specific permissions
1845 // If more than one group applies, use the group with the highest limit ratio (max/period)
1846 foreach ( $this->getGroups() as $group ) {
1847 if ( isset( $limits[$group] ) ) {
1848 if ( $userLimit === false
1849 ||
$limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1851 $userLimit = $limits[$group];
1856 // Set the user limit key
1857 if ( $userLimit !== false ) {
1858 list( $max, $period ) = $userLimit;
1859 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
1860 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1863 // ip-based limits for all ping-limitable users
1864 if ( isset( $limits['ip-all'] ) ) {
1865 $ip = $this->getRequest()->getIP();
1866 // ignore if user limit is more permissive
1867 if ( $isNewbie ||
$userLimit === false
1868 ||
$limits['ip-all'][0] / $limits['ip-all'][1] > $userLimit[0] / $userLimit[1] ) {
1869 $keys["mediawiki:limiter:$action:ip-all:$ip"] = $limits['ip-all'];
1873 // subnet-based limits for all ping-limitable users
1874 if ( isset( $limits['subnet-all'] ) ) {
1875 $ip = $this->getRequest()->getIP();
1876 $subnet = IP
::getSubnet( $ip );
1877 if ( $subnet !== false ) {
1878 // ignore if user limit is more permissive
1879 if ( $isNewbie ||
$userLimit === false
1880 ||
$limits['ip-all'][0] / $limits['ip-all'][1]
1881 > $userLimit[0] / $userLimit[1] ) {
1882 $keys["mediawiki:limiter:$action:subnet-all:$subnet"] = $limits['subnet-all'];
1887 $cache = ObjectCache
::getLocalClusterInstance();
1890 foreach ( $keys as $key => $limit ) {
1891 list( $max, $period ) = $limit;
1892 $summary = "(limit $max in {$period}s)";
1893 $count = $cache->get( $key );
1896 if ( $count >= $max ) {
1897 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1898 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1901 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1904 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1905 if ( $incrBy > 0 ) {
1906 $cache->add( $key, 0, intval( $period ) ); // first ping
1909 if ( $incrBy > 0 ) {
1910 $cache->incr( $key, $incrBy );
1918 * Check if user is blocked
1920 * @param bool $bFromSlave Whether to check the slave database instead of
1921 * the master. Hacked from false due to horrible probs on site.
1922 * @return bool True if blocked, false otherwise
1924 public function isBlocked( $bFromSlave = true ) {
1925 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
1929 * Get the block affecting the user, or null if the user is not blocked
1931 * @param bool $bFromSlave Whether to check the slave database instead of the master
1932 * @return Block|null
1934 public function getBlock( $bFromSlave = true ) {
1935 $this->getBlockedStatus( $bFromSlave );
1936 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
1940 * Check if user is blocked from editing a particular article
1942 * @param Title $title Title to check
1943 * @param bool $bFromSlave Whether to check the slave database instead of the master
1946 public function isBlockedFrom( $title, $bFromSlave = false ) {
1947 global $wgBlockAllowsUTEdit;
1949 $blocked = $this->isBlocked( $bFromSlave );
1950 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
1951 // If a user's name is suppressed, they cannot make edits anywhere
1952 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName()
1953 && $title->getNamespace() == NS_USER_TALK
) {
1955 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
1958 Hooks
::run( 'UserIsBlockedFrom', [ $this, $title, &$blocked, &$allowUsertalk ] );
1964 * If user is blocked, return the name of the user who placed the block
1965 * @return string Name of blocker
1967 public function blockedBy() {
1968 $this->getBlockedStatus();
1969 return $this->mBlockedby
;
1973 * If user is blocked, return the specified reason for the block
1974 * @return string Blocking reason
1976 public function blockedFor() {
1977 $this->getBlockedStatus();
1978 return $this->mBlockreason
;
1982 * If user is blocked, return the ID for the block
1983 * @return int Block ID
1985 public function getBlockId() {
1986 $this->getBlockedStatus();
1987 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
1991 * Check if user is blocked on all wikis.
1992 * Do not use for actual edit permission checks!
1993 * This is intended for quick UI checks.
1995 * @param string $ip IP address, uses current client if none given
1996 * @return bool True if blocked, false otherwise
1998 public function isBlockedGlobally( $ip = '' ) {
1999 return $this->getGlobalBlock( $ip ) instanceof Block
;
2003 * Check if user is blocked on all wikis.
2004 * Do not use for actual edit permission checks!
2005 * This is intended for quick UI checks.
2007 * @param string $ip IP address, uses current client if none given
2008 * @return Block|null Block object if blocked, null otherwise
2009 * @throws FatalError
2010 * @throws MWException
2012 public function getGlobalBlock( $ip = '' ) {
2013 if ( $this->mGlobalBlock
!== null ) {
2014 return $this->mGlobalBlock ?
: null;
2016 // User is already an IP?
2017 if ( IP
::isIPAddress( $this->getName() ) ) {
2018 $ip = $this->getName();
2020 $ip = $this->getRequest()->getIP();
2024 Hooks
::run( 'UserIsBlockedGlobally', [ &$this, $ip, &$blocked, &$block ] );
2026 if ( $blocked && $block === null ) {
2027 // back-compat: UserIsBlockedGlobally didn't have $block param first
2029 $block->setTarget( $ip );
2032 $this->mGlobalBlock
= $blocked ?
$block : false;
2033 return $this->mGlobalBlock ?
: null;
2037 * Check if user account is locked
2039 * @return bool True if locked, false otherwise
2041 public function isLocked() {
2042 if ( $this->mLocked
!== null ) {
2043 return $this->mLocked
;
2045 $authUser = AuthManager
::callLegacyAuthPlugin( 'getUserInstance', [ &$this ], null );
2046 $this->mLocked
= $authUser && $authUser->isLocked();
2047 Hooks
::run( 'UserIsLocked', [ $this, &$this->mLocked
] );
2048 return $this->mLocked
;
2052 * Check if user account is hidden
2054 * @return bool True if hidden, false otherwise
2056 public function isHidden() {
2057 if ( $this->mHideName
!== null ) {
2058 return $this->mHideName
;
2060 $this->getBlockedStatus();
2061 if ( !$this->mHideName
) {
2062 $authUser = AuthManager
::callLegacyAuthPlugin( 'getUserInstance', [ &$this ], null );
2063 $this->mHideName
= $authUser && $authUser->isHidden();
2064 Hooks
::run( 'UserIsHidden', [ $this, &$this->mHideName
] );
2066 return $this->mHideName
;
2070 * Get the user's ID.
2071 * @return int The user's ID; 0 if the user is anonymous or nonexistent
2073 public function getId() {
2074 if ( $this->mId
=== null && $this->mName
!== null && User
::isIP( $this->mName
) ) {
2075 // Special case, we know the user is anonymous
2077 } elseif ( !$this->isItemLoaded( 'id' ) ) {
2078 // Don't load if this was initialized from an ID
2082 return (int)$this->mId
;
2086 * Set the user and reload all fields according to a given ID
2087 * @param int $v User ID to reload
2089 public function setId( $v ) {
2091 $this->clearInstanceCache( 'id' );
2095 * Get the user name, or the IP of an anonymous user
2096 * @return string User's name or IP address
2098 public function getName() {
2099 if ( $this->isItemLoaded( 'name', 'only' ) ) {
2100 // Special case optimisation
2101 return $this->mName
;
2104 if ( $this->mName
=== false ) {
2106 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
2108 return $this->mName
;
2113 * Set the user name.
2115 * This does not reload fields from the database according to the given
2116 * name. Rather, it is used to create a temporary "nonexistent user" for
2117 * later addition to the database. It can also be used to set the IP
2118 * address for an anonymous user to something other than the current
2121 * @note User::newFromName() has roughly the same function, when the named user
2123 * @param string $str New user name to set
2125 public function setName( $str ) {
2127 $this->mName
= $str;
2131 * Get the user's name escaped by underscores.
2132 * @return string Username escaped by underscores.
2134 public function getTitleKey() {
2135 return str_replace( ' ', '_', $this->getName() );
2139 * Check if the user has new messages.
2140 * @return bool True if the user has new messages
2142 public function getNewtalk() {
2145 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2146 if ( $this->mNewtalk
=== -1 ) {
2147 $this->mNewtalk
= false; # reset talk page status
2149 // Check memcached separately for anons, who have no
2150 // entire User object stored in there.
2151 if ( !$this->mId
) {
2152 global $wgDisableAnonTalk;
2153 if ( $wgDisableAnonTalk ) {
2154 // Anon newtalk disabled by configuration.
2155 $this->mNewtalk
= false;
2157 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
2160 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2164 return (bool)$this->mNewtalk
;
2168 * Return the data needed to construct links for new talk page message
2169 * alerts. If there are new messages, this will return an associative array
2170 * with the following data:
2171 * wiki: The database name of the wiki
2172 * link: Root-relative link to the user's talk page
2173 * rev: The last talk page revision that the user has seen or null. This
2174 * is useful for building diff links.
2175 * If there are no new messages, it returns an empty array.
2176 * @note This function was designed to accomodate multiple talk pages, but
2177 * currently only returns a single link and revision.
2180 public function getNewMessageLinks() {
2182 if ( !Hooks
::run( 'UserRetrieveNewTalks', [ &$this, &$talks ] ) ) {
2184 } elseif ( !$this->getNewtalk() ) {
2187 $utp = $this->getTalkPage();
2188 $dbr = wfGetDB( DB_SLAVE
);
2189 // Get the "last viewed rev" timestamp from the oldest message notification
2190 $timestamp = $dbr->selectField( 'user_newtalk',
2191 'MIN(user_last_timestamp)',
2192 $this->isAnon() ?
[ 'user_ip' => $this->getName() ] : [ 'user_id' => $this->getId() ],
2194 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2195 return [ [ 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ] ];
2199 * Get the revision ID for the last talk page revision viewed by the talk
2201 * @return int|null Revision ID or null
2203 public function getNewMessageRevisionId() {
2204 $newMessageRevisionId = null;
2205 $newMessageLinks = $this->getNewMessageLinks();
2206 if ( $newMessageLinks ) {
2207 // Note: getNewMessageLinks() never returns more than a single link
2208 // and it is always for the same wiki, but we double-check here in
2209 // case that changes some time in the future.
2210 if ( count( $newMessageLinks ) === 1
2211 && $newMessageLinks[0]['wiki'] === wfWikiID()
2212 && $newMessageLinks[0]['rev']
2214 /** @var Revision $newMessageRevision */
2215 $newMessageRevision = $newMessageLinks[0]['rev'];
2216 $newMessageRevisionId = $newMessageRevision->getId();
2219 return $newMessageRevisionId;
2223 * Internal uncached check for new messages
2226 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2227 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2228 * @return bool True if the user has new messages
2230 protected function checkNewtalk( $field, $id ) {
2231 $dbr = wfGetDB( DB_SLAVE
);
2233 $ok = $dbr->selectField( 'user_newtalk', $field, [ $field => $id ], __METHOD__
);
2235 return $ok !== false;
2239 * Add or update the new messages flag
2240 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2241 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2242 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2243 * @return bool True if successful, false otherwise
2245 protected function updateNewtalk( $field, $id, $curRev = null ) {
2246 // Get timestamp of the talk page revision prior to the current one
2247 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2248 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2249 // Mark the user as having new messages since this revision
2250 $dbw = wfGetDB( DB_MASTER
);
2251 $dbw->insert( 'user_newtalk',
2252 [ $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ],
2255 if ( $dbw->affectedRows() ) {
2256 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2259 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2265 * Clear the new messages flag for the given user
2266 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2267 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2268 * @return bool True if successful, false otherwise
2270 protected function deleteNewtalk( $field, $id ) {
2271 $dbw = wfGetDB( DB_MASTER
);
2272 $dbw->delete( 'user_newtalk',
2275 if ( $dbw->affectedRows() ) {
2276 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2279 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2285 * Update the 'You have new messages!' status.
2286 * @param bool $val Whether the user has new messages
2287 * @param Revision $curRev New, as yet unseen revision of the user talk
2288 * page. Ignored if null or !$val.
2290 public function setNewtalk( $val, $curRev = null ) {
2291 if ( wfReadOnly() ) {
2296 $this->mNewtalk
= $val;
2298 if ( $this->isAnon() ) {
2300 $id = $this->getName();
2303 $id = $this->getId();
2307 $changed = $this->updateNewtalk( $field, $id, $curRev );
2309 $changed = $this->deleteNewtalk( $field, $id );
2313 $this->invalidateCache();
2318 * Generate a current or new-future timestamp to be stored in the
2319 * user_touched field when we update things.
2320 * @return string Timestamp in TS_MW format
2322 private function newTouchedTimestamp() {
2323 global $wgClockSkewFudge;
2325 $time = wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2326 if ( $this->mTouched
&& $time <= $this->mTouched
) {
2327 $time = wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $this->mTouched
) +
1 );
2334 * Clear user data from memcached
2336 * Use after applying updates to the database; caller's
2337 * responsibility to update user_touched if appropriate.
2339 * Called implicitly from invalidateCache() and saveSettings().
2341 * @param string $mode Use 'refresh' to clear now; otherwise before DB commit
2343 public function clearSharedCache( $mode = 'changed' ) {
2344 if ( !$this->getId() ) {
2348 $cache = ObjectCache
::getMainWANInstance();
2349 $key = $this->getCacheKey( $cache );
2350 if ( $mode === 'refresh' ) {
2351 $cache->delete( $key, 1 );
2353 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle(
2354 function() use ( $cache, $key ) {
2355 $cache->delete( $key );
2362 * Immediately touch the user data cache for this account
2364 * Calls touch() and removes account data from memcached
2366 public function invalidateCache() {
2368 $this->clearSharedCache();
2372 * Update the "touched" timestamp for the user
2374 * This is useful on various login/logout events when making sure that
2375 * a browser or proxy that has multiple tenants does not suffer cache
2376 * pollution where the new user sees the old users content. The value
2377 * of getTouched() is checked when determining 304 vs 200 responses.
2378 * Unlike invalidateCache(), this preserves the User object cache and
2379 * avoids database writes.
2383 public function touch() {
2384 $id = $this->getId();
2386 $key = wfMemcKey( 'user-quicktouched', 'id', $id );
2387 ObjectCache
::getMainWANInstance()->touchCheckKey( $key );
2388 $this->mQuickTouched
= null;
2393 * Validate the cache for this account.
2394 * @param string $timestamp A timestamp in TS_MW format
2397 public function validateCache( $timestamp ) {
2398 return ( $timestamp >= $this->getTouched() );
2402 * Get the user touched timestamp
2404 * Use this value only to validate caches via inequalities
2405 * such as in the case of HTTP If-Modified-Since response logic
2407 * @return string TS_MW Timestamp
2409 public function getTouched() {
2413 if ( $this->mQuickTouched
=== null ) {
2414 $key = wfMemcKey( 'user-quicktouched', 'id', $this->mId
);
2415 $cache = ObjectCache
::getMainWANInstance();
2417 $this->mQuickTouched
= wfTimestamp( TS_MW
, $cache->getCheckKeyTime( $key ) );
2420 return max( $this->mTouched
, $this->mQuickTouched
);
2423 return $this->mTouched
;
2427 * Get the user_touched timestamp field (time of last DB updates)
2428 * @return string TS_MW Timestamp
2431 public function getDBTouched() {
2434 return $this->mTouched
;
2438 * @deprecated Removed in 1.27.
2442 public function getPassword() {
2443 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2447 * @deprecated Removed in 1.27.
2451 public function getTemporaryPassword() {
2452 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2456 * Set the password and reset the random token.
2457 * Calls through to authentication plugin if necessary;
2458 * will have no effect if the auth plugin refuses to
2459 * pass the change through or if the legal password
2462 * As a special case, setting the password to null
2463 * wipes it, so the account cannot be logged in until
2464 * a new password is set, for instance via e-mail.
2466 * @deprecated since 1.27, use AuthManager instead
2467 * @param string $str New password to set
2468 * @throws PasswordError On failure
2471 public function setPassword( $str ) {
2472 return $this->setPasswordInternal( $str );
2476 * Set the password and reset the random token unconditionally.
2478 * @deprecated since 1.27, use AuthManager instead
2479 * @param string|null $str New password to set or null to set an invalid
2480 * password hash meaning that the user will not be able to log in
2481 * through the web interface.
2483 public function setInternalPassword( $str ) {
2484 $this->setPasswordInternal( $str );
2488 * Actually set the password and such
2489 * @since 1.27 cannot set a password for a user not in the database
2490 * @param string|null $str New password to set or null to set an invalid
2491 * password hash meaning that the user will not be able to log in
2492 * through the web interface.
2493 * @return bool Success
2495 private function setPasswordInternal( $str ) {
2496 $manager = AuthManager
::singleton();
2498 // If the user doesn't exist yet, fail
2499 if ( !$manager->userExists( $this->getName() ) ) {
2500 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2503 $status = $this->changeAuthenticationData( [
2504 'username' => $this->getName(),
2508 if ( !$status->isGood() ) {
2509 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
2510 ->info( __METHOD__
. ': Password change rejected: '
2511 . $status->getWikiText( null, null, 'en' ) );
2515 $this->setOption( 'watchlisttoken', false );
2516 SessionManager
::singleton()->invalidateSessionsForUser( $this );
2522 * Changes credentials of the user.
2524 * This is a convenience wrapper around AuthManager::changeAuthenticationData.
2525 * Note that this can return a status that isOK() but not isGood() on certain types of failures,
2526 * e.g. when no provider handled the change.
2528 * @param array $data A set of authentication data in fieldname => value format. This is the
2529 * same data you would pass the changeauthenticationdata API - 'username', 'password' etc.
2533 public function changeAuthenticationData( array $data ) {
2534 $manager = AuthManager
::singleton();
2535 $reqs = $manager->getAuthenticationRequests( AuthManager
::ACTION_CHANGE
, $this );
2536 $reqs = AuthenticationRequest
::loadRequestsFromSubmission( $reqs, $data );
2538 $status = Status
::newGood( 'ignored' );
2539 foreach ( $reqs as $req ) {
2540 $status->merge( $manager->allowsAuthenticationDataChange( $req ), true );
2542 if ( $status->getValue() === 'ignored' ) {
2543 $status->warning( 'authenticationdatachange-ignored' );
2546 if ( $status->isGood() ) {
2547 foreach ( $reqs as $req ) {
2548 $manager->changeAuthenticationData( $req );
2555 * Get the user's current token.
2556 * @param bool $forceCreation Force the generation of a new token if the
2557 * user doesn't have one (default=true for backwards compatibility).
2558 * @return string|null Token
2560 public function getToken( $forceCreation = true ) {
2561 global $wgAuthenticationTokenVersion;
2564 if ( !$this->mToken
&& $forceCreation ) {
2568 if ( !$this->mToken
) {
2569 // The user doesn't have a token, return null to indicate that.
2571 } elseif ( $this->mToken
=== self
::INVALID_TOKEN
) {
2572 // We return a random value here so existing token checks are very
2574 return MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2575 } elseif ( $wgAuthenticationTokenVersion === null ) {
2576 // $wgAuthenticationTokenVersion not in use, so return the raw secret
2577 return $this->mToken
;
2579 // $wgAuthenticationTokenVersion in use, so hmac it.
2580 $ret = MWCryptHash
::hmac( $wgAuthenticationTokenVersion, $this->mToken
, false );
2582 // The raw hash can be overly long. Shorten it up.
2583 $len = max( 32, self
::TOKEN_LENGTH
);
2584 if ( strlen( $ret ) < $len ) {
2585 // Should never happen, even md5 is 128 bits
2586 throw new \
UnexpectedValueException( 'Hmac returned less than 128 bits' );
2588 return substr( $ret, -$len );
2593 * Set the random token (used for persistent authentication)
2594 * Called from loadDefaults() among other places.
2596 * @param string|bool $token If specified, set the token to this value
2598 public function setToken( $token = false ) {
2600 if ( $this->mToken
=== self
::INVALID_TOKEN
) {
2601 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
2602 ->debug( __METHOD__
. ": Ignoring attempt to set token for system user \"$this\"" );
2603 } elseif ( !$token ) {
2604 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2606 $this->mToken
= $token;
2611 * Set the password for a password reminder or new account email
2613 * @deprecated Removed in 1.27. Use PasswordReset instead.
2614 * @param string $str New password to set or null to set an invalid
2615 * password hash meaning that the user will not be able to use it
2616 * @param bool $throttle If true, reset the throttle timestamp to the present
2618 public function setNewpassword( $str, $throttle = true ) {
2619 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2623 * Has password reminder email been sent within the last
2624 * $wgPasswordReminderResendTime hours?
2625 * @deprecated Removed in 1.27. See above.
2628 public function isPasswordReminderThrottled() {
2629 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2633 * Get the user's e-mail address
2634 * @return string User's email address
2636 public function getEmail() {
2638 Hooks
::run( 'UserGetEmail', [ $this, &$this->mEmail
] );
2639 return $this->mEmail
;
2643 * Get the timestamp of the user's e-mail authentication
2644 * @return string TS_MW timestamp
2646 public function getEmailAuthenticationTimestamp() {
2648 Hooks
::run( 'UserGetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
2649 return $this->mEmailAuthenticated
;
2653 * Set the user's e-mail address
2654 * @param string $str New e-mail address
2656 public function setEmail( $str ) {
2658 if ( $str == $this->mEmail
) {
2661 $this->invalidateEmail();
2662 $this->mEmail
= $str;
2663 Hooks
::run( 'UserSetEmail', [ $this, &$this->mEmail
] );
2667 * Set the user's e-mail address and a confirmation mail if needed.
2670 * @param string $str New e-mail address
2673 public function setEmailWithConfirmation( $str ) {
2674 global $wgEnableEmail, $wgEmailAuthentication;
2676 if ( !$wgEnableEmail ) {
2677 return Status
::newFatal( 'emaildisabled' );
2680 $oldaddr = $this->getEmail();
2681 if ( $str === $oldaddr ) {
2682 return Status
::newGood( true );
2685 $type = $oldaddr != '' ?
'changed' : 'set';
2686 $notificationResult = null;
2688 if ( $wgEmailAuthentication ) {
2689 // Send the user an email notifying the user of the change in registered
2690 // email address on their previous email address
2691 if ( $type == 'changed' ) {
2692 $change = $str != '' ?
'changed' : 'removed';
2693 $notificationResult = $this->sendMail(
2694 wfMessage( 'notificationemail_subject_' . $change )->text(),
2695 wfMessage( 'notificationemail_body_' . $change,
2696 $this->getRequest()->getIP(),
2703 $this->setEmail( $str );
2705 if ( $str !== '' && $wgEmailAuthentication ) {
2706 // Send a confirmation request to the new address if needed
2707 $result = $this->sendConfirmationMail( $type );
2709 if ( $notificationResult !== null ) {
2710 $result->merge( $notificationResult );
2713 if ( $result->isGood() ) {
2714 // Say to the caller that a confirmation and notification mail has been sent
2715 $result->value
= 'eauth';
2718 $result = Status
::newGood( true );
2725 * Get the user's real name
2726 * @return string User's real name
2728 public function getRealName() {
2729 if ( !$this->isItemLoaded( 'realname' ) ) {
2733 return $this->mRealName
;
2737 * Set the user's real name
2738 * @param string $str New real name
2740 public function setRealName( $str ) {
2742 $this->mRealName
= $str;
2746 * Get the user's current setting for a given option.
2748 * @param string $oname The option to check
2749 * @param string $defaultOverride A default value returned if the option does not exist
2750 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2751 * @return string User's current value for the option
2752 * @see getBoolOption()
2753 * @see getIntOption()
2755 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2756 global $wgHiddenPrefs;
2757 $this->loadOptions();
2759 # We want 'disabled' preferences to always behave as the default value for
2760 # users, even if they have set the option explicitly in their settings (ie they
2761 # set it, and then it was disabled removing their ability to change it). But
2762 # we don't want to erase the preferences in the database in case the preference
2763 # is re-enabled again. So don't touch $mOptions, just override the returned value
2764 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2765 return self
::getDefaultOption( $oname );
2768 if ( array_key_exists( $oname, $this->mOptions
) ) {
2769 return $this->mOptions
[$oname];
2771 return $defaultOverride;
2776 * Get all user's options
2778 * @param int $flags Bitwise combination of:
2779 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2780 * to the default value. (Since 1.25)
2783 public function getOptions( $flags = 0 ) {
2784 global $wgHiddenPrefs;
2785 $this->loadOptions();
2786 $options = $this->mOptions
;
2788 # We want 'disabled' preferences to always behave as the default value for
2789 # users, even if they have set the option explicitly in their settings (ie they
2790 # set it, and then it was disabled removing their ability to change it). But
2791 # we don't want to erase the preferences in the database in case the preference
2792 # is re-enabled again. So don't touch $mOptions, just override the returned value
2793 foreach ( $wgHiddenPrefs as $pref ) {
2794 $default = self
::getDefaultOption( $pref );
2795 if ( $default !== null ) {
2796 $options[$pref] = $default;
2800 if ( $flags & self
::GETOPTIONS_EXCLUDE_DEFAULTS
) {
2801 $options = array_diff_assoc( $options, self
::getDefaultOptions() );
2808 * Get the user's current setting for a given option, as a boolean value.
2810 * @param string $oname The option to check
2811 * @return bool User's current value for the option
2814 public function getBoolOption( $oname ) {
2815 return (bool)$this->getOption( $oname );
2819 * Get the user's current setting for a given option, as an integer value.
2821 * @param string $oname The option to check
2822 * @param int $defaultOverride A default value returned if the option does not exist
2823 * @return int User's current value for the option
2826 public function getIntOption( $oname, $defaultOverride = 0 ) {
2827 $val = $this->getOption( $oname );
2829 $val = $defaultOverride;
2831 return intval( $val );
2835 * Set the given option for a user.
2837 * You need to call saveSettings() to actually write to the database.
2839 * @param string $oname The option to set
2840 * @param mixed $val New value to set
2842 public function setOption( $oname, $val ) {
2843 $this->loadOptions();
2845 // Explicitly NULL values should refer to defaults
2846 if ( is_null( $val ) ) {
2847 $val = self
::getDefaultOption( $oname );
2850 $this->mOptions
[$oname] = $val;
2854 * Get a token stored in the preferences (like the watchlist one),
2855 * resetting it if it's empty (and saving changes).
2857 * @param string $oname The option name to retrieve the token from
2858 * @return string|bool User's current value for the option, or false if this option is disabled.
2859 * @see resetTokenFromOption()
2861 * @deprecated since 1.26 Applications should use the OAuth extension
2863 public function getTokenFromOption( $oname ) {
2864 global $wgHiddenPrefs;
2866 $id = $this->getId();
2867 if ( !$id ||
in_array( $oname, $wgHiddenPrefs ) ) {
2871 $token = $this->getOption( $oname );
2873 // Default to a value based on the user token to avoid space
2874 // wasted on storing tokens for all users. When this option
2875 // is set manually by the user, only then is it stored.
2876 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
2883 * Reset a token stored in the preferences (like the watchlist one).
2884 * *Does not* save user's preferences (similarly to setOption()).
2886 * @param string $oname The option name to reset the token in
2887 * @return string|bool New token value, or false if this option is disabled.
2888 * @see getTokenFromOption()
2891 public function resetTokenFromOption( $oname ) {
2892 global $wgHiddenPrefs;
2893 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2897 $token = MWCryptRand
::generateHex( 40 );
2898 $this->setOption( $oname, $token );
2903 * Return a list of the types of user options currently returned by
2904 * User::getOptionKinds().
2906 * Currently, the option kinds are:
2907 * - 'registered' - preferences which are registered in core MediaWiki or
2908 * by extensions using the UserGetDefaultOptions hook.
2909 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2910 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2911 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2912 * be used by user scripts.
2913 * - 'special' - "preferences" that are not accessible via User::getOptions
2914 * or User::setOptions.
2915 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2916 * These are usually legacy options, removed in newer versions.
2918 * The API (and possibly others) use this function to determine the possible
2919 * option types for validation purposes, so make sure to update this when a
2920 * new option kind is added.
2922 * @see User::getOptionKinds
2923 * @return array Option kinds
2925 public static function listOptionKinds() {
2928 'registered-multiselect',
2929 'registered-checkmatrix',
2937 * Return an associative array mapping preferences keys to the kind of a preference they're
2938 * used for. Different kinds are handled differently when setting or reading preferences.
2940 * See User::listOptionKinds for the list of valid option types that can be provided.
2942 * @see User::listOptionKinds
2943 * @param IContextSource $context
2944 * @param array $options Assoc. array with options keys to check as keys.
2945 * Defaults to $this->mOptions.
2946 * @return array The key => kind mapping data
2948 public function getOptionKinds( IContextSource
$context, $options = null ) {
2949 $this->loadOptions();
2950 if ( $options === null ) {
2951 $options = $this->mOptions
;
2954 $prefs = Preferences
::getPreferences( $this, $context );
2957 // Pull out the "special" options, so they don't get converted as
2958 // multiselect or checkmatrix.
2959 $specialOptions = array_fill_keys( Preferences
::getSaveBlacklist(), true );
2960 foreach ( $specialOptions as $name => $value ) {
2961 unset( $prefs[$name] );
2964 // Multiselect and checkmatrix options are stored in the database with
2965 // one key per option, each having a boolean value. Extract those keys.
2966 $multiselectOptions = [];
2967 foreach ( $prefs as $name => $info ) {
2968 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2969 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2970 $opts = HTMLFormField
::flattenOptions( $info['options'] );
2971 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2973 foreach ( $opts as $value ) {
2974 $multiselectOptions["$prefix$value"] = true;
2977 unset( $prefs[$name] );
2980 $checkmatrixOptions = [];
2981 foreach ( $prefs as $name => $info ) {
2982 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2983 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2984 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
2985 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
2986 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2988 foreach ( $columns as $column ) {
2989 foreach ( $rows as $row ) {
2990 $checkmatrixOptions["$prefix$column-$row"] = true;
2994 unset( $prefs[$name] );
2998 // $value is ignored
2999 foreach ( $options as $key => $value ) {
3000 if ( isset( $prefs[$key] ) ) {
3001 $mapping[$key] = 'registered';
3002 } elseif ( isset( $multiselectOptions[$key] ) ) {
3003 $mapping[$key] = 'registered-multiselect';
3004 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
3005 $mapping[$key] = 'registered-checkmatrix';
3006 } elseif ( isset( $specialOptions[$key] ) ) {
3007 $mapping[$key] = 'special';
3008 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
3009 $mapping[$key] = 'userjs';
3011 $mapping[$key] = 'unused';
3019 * Reset certain (or all) options to the site defaults
3021 * The optional parameter determines which kinds of preferences will be reset.
3022 * Supported values are everything that can be reported by getOptionKinds()
3023 * and 'all', which forces a reset of *all* preferences and overrides everything else.
3025 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
3026 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
3027 * for backwards-compatibility.
3028 * @param IContextSource|null $context Context source used when $resetKinds
3029 * does not contain 'all', passed to getOptionKinds().
3030 * Defaults to RequestContext::getMain() when null.
3032 public function resetOptions(
3033 $resetKinds = [ 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ],
3034 IContextSource
$context = null
3037 $defaultOptions = self
::getDefaultOptions();
3039 if ( !is_array( $resetKinds ) ) {
3040 $resetKinds = [ $resetKinds ];
3043 if ( in_array( 'all', $resetKinds ) ) {
3044 $newOptions = $defaultOptions;
3046 if ( $context === null ) {
3047 $context = RequestContext
::getMain();
3050 $optionKinds = $this->getOptionKinds( $context );
3051 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
3054 // Use default values for the options that should be deleted, and
3055 // copy old values for the ones that shouldn't.
3056 foreach ( $this->mOptions
as $key => $value ) {
3057 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
3058 if ( array_key_exists( $key, $defaultOptions ) ) {
3059 $newOptions[$key] = $defaultOptions[$key];
3062 $newOptions[$key] = $value;
3067 Hooks
::run( 'UserResetAllOptions', [ $this, &$newOptions, $this->mOptions
, $resetKinds ] );
3069 $this->mOptions
= $newOptions;
3070 $this->mOptionsLoaded
= true;
3074 * Get the user's preferred date format.
3075 * @return string User's preferred date format
3077 public function getDatePreference() {
3078 // Important migration for old data rows
3079 if ( is_null( $this->mDatePreference
) ) {
3081 $value = $this->getOption( 'date' );
3082 $map = $wgLang->getDatePreferenceMigrationMap();
3083 if ( isset( $map[$value] ) ) {
3084 $value = $map[$value];
3086 $this->mDatePreference
= $value;
3088 return $this->mDatePreference
;
3092 * Determine based on the wiki configuration and the user's options,
3093 * whether this user must be over HTTPS no matter what.
3097 public function requiresHTTPS() {
3098 global $wgSecureLogin;
3099 if ( !$wgSecureLogin ) {
3102 $https = $this->getBoolOption( 'prefershttps' );
3103 Hooks
::run( 'UserRequiresHTTPS', [ $this, &$https ] );
3105 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
3112 * Get the user preferred stub threshold
3116 public function getStubThreshold() {
3117 global $wgMaxArticleSize; # Maximum article size, in Kb
3118 $threshold = $this->getIntOption( 'stubthreshold' );
3119 if ( $threshold > $wgMaxArticleSize * 1024 ) {
3120 // If they have set an impossible value, disable the preference
3121 // so we can use the parser cache again.
3128 * Get the permissions this user has.
3129 * @return array Array of String permission names
3131 public function getRights() {
3132 if ( is_null( $this->mRights
) ) {
3133 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
3135 // Deny any rights denied by the user's session, unless this
3136 // endpoint has no sessions.
3137 if ( !defined( 'MW_NO_SESSION' ) ) {
3138 $allowedRights = $this->getRequest()->getSession()->getAllowedUserRights();
3139 if ( $allowedRights !== null ) {
3140 $this->mRights
= array_intersect( $this->mRights
, $allowedRights );
3144 Hooks
::run( 'UserGetRights', [ $this, &$this->mRights
] );
3145 // Force reindexation of rights when a hook has unset one of them
3146 $this->mRights
= array_values( array_unique( $this->mRights
) );
3148 return $this->mRights
;
3152 * Get the list of explicit group memberships this user has.
3153 * The implicit * and user groups are not included.
3154 * @return array Array of String internal group names
3156 public function getGroups() {
3158 $this->loadGroups();
3159 return $this->mGroups
;
3163 * Get the list of implicit group memberships this user has.
3164 * This includes all explicit groups, plus 'user' if logged in,
3165 * '*' for all accounts, and autopromoted groups
3166 * @param bool $recache Whether to avoid the cache
3167 * @return array Array of String internal group names
3169 public function getEffectiveGroups( $recache = false ) {
3170 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
3171 $this->mEffectiveGroups
= array_unique( array_merge(
3172 $this->getGroups(), // explicit groups
3173 $this->getAutomaticGroups( $recache ) // implicit groups
3175 // Hook for additional groups
3176 Hooks
::run( 'UserEffectiveGroups', [ &$this, &$this->mEffectiveGroups
] );
3177 // Force reindexation of groups when a hook has unset one of them
3178 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
3180 return $this->mEffectiveGroups
;
3184 * Get the list of implicit group memberships this user has.
3185 * This includes 'user' if logged in, '*' for all accounts,
3186 * and autopromoted groups
3187 * @param bool $recache Whether to avoid the cache
3188 * @return array Array of String internal group names
3190 public function getAutomaticGroups( $recache = false ) {
3191 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
3192 $this->mImplicitGroups
= [ '*' ];
3193 if ( $this->getId() ) {
3194 $this->mImplicitGroups
[] = 'user';
3196 $this->mImplicitGroups
= array_unique( array_merge(
3197 $this->mImplicitGroups
,
3198 Autopromote
::getAutopromoteGroups( $this )
3202 // Assure data consistency with rights/groups,
3203 // as getEffectiveGroups() depends on this function
3204 $this->mEffectiveGroups
= null;
3207 return $this->mImplicitGroups
;
3211 * Returns the groups the user has belonged to.
3213 * The user may still belong to the returned groups. Compare with getGroups().
3215 * The function will not return groups the user had belonged to before MW 1.17
3217 * @return array Names of the groups the user has belonged to.
3219 public function getFormerGroups() {
3222 if ( is_null( $this->mFormerGroups
) ) {
3223 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3224 ?
wfGetDB( DB_MASTER
)
3225 : wfGetDB( DB_SLAVE
);
3226 $res = $db->select( 'user_former_groups',
3228 [ 'ufg_user' => $this->mId
],
3230 $this->mFormerGroups
= [];
3231 foreach ( $res as $row ) {
3232 $this->mFormerGroups
[] = $row->ufg_group
;
3236 return $this->mFormerGroups
;
3240 * Get the user's edit count.
3241 * @return int|null Null for anonymous users
3243 public function getEditCount() {
3244 if ( !$this->getId() ) {
3248 if ( $this->mEditCount
=== null ) {
3249 /* Populate the count, if it has not been populated yet */
3250 $dbr = wfGetDB( DB_SLAVE
);
3251 // check if the user_editcount field has been initialized
3252 $count = $dbr->selectField(
3253 'user', 'user_editcount',
3254 [ 'user_id' => $this->mId
],
3258 if ( $count === null ) {
3259 // it has not been initialized. do so.
3260 $count = $this->initEditCount();
3262 $this->mEditCount
= $count;
3264 return (int)$this->mEditCount
;
3268 * Add the user to the given group.
3269 * This takes immediate effect.
3270 * @param string $group Name of the group to add
3273 public function addGroup( $group ) {
3276 if ( !Hooks
::run( 'UserAddGroup', [ $this, &$group ] ) ) {
3280 $dbw = wfGetDB( DB_MASTER
);
3281 if ( $this->getId() ) {
3282 $dbw->insert( 'user_groups',
3284 'ug_user' => $this->getId(),
3285 'ug_group' => $group,
3291 $this->loadGroups();
3292 $this->mGroups
[] = $group;
3293 // In case loadGroups was not called before, we now have the right twice.
3294 // Get rid of the duplicate.
3295 $this->mGroups
= array_unique( $this->mGroups
);
3297 // Refresh the groups caches, and clear the rights cache so it will be
3298 // refreshed on the next call to $this->getRights().
3299 $this->getEffectiveGroups( true );
3300 $this->mRights
= null;
3302 $this->invalidateCache();
3308 * Remove the user from the given group.
3309 * This takes immediate effect.
3310 * @param string $group Name of the group to remove
3313 public function removeGroup( $group ) {
3315 if ( !Hooks
::run( 'UserRemoveGroup', [ $this, &$group ] ) ) {
3319 $dbw = wfGetDB( DB_MASTER
);
3320 $dbw->delete( 'user_groups',
3322 'ug_user' => $this->getId(),
3323 'ug_group' => $group,
3326 // Remember that the user was in this group
3327 $dbw->insert( 'user_former_groups',
3329 'ufg_user' => $this->getId(),
3330 'ufg_group' => $group,
3336 $this->loadGroups();
3337 $this->mGroups
= array_diff( $this->mGroups
, [ $group ] );
3339 // Refresh the groups caches, and clear the rights cache so it will be
3340 // refreshed on the next call to $this->getRights().
3341 $this->getEffectiveGroups( true );
3342 $this->mRights
= null;
3344 $this->invalidateCache();
3350 * Get whether the user is logged in
3353 public function isLoggedIn() {
3354 return $this->getId() != 0;
3358 * Get whether the user is anonymous
3361 public function isAnon() {
3362 return !$this->isLoggedIn();
3366 * @return bool Whether this user is flagged as being a bot role account
3369 public function isBot() {
3370 if ( in_array( 'bot', $this->getGroups() ) && $this->isAllowed( 'bot' ) ) {
3375 Hooks
::run( "UserIsBot", [ $this, &$isBot ] );
3381 * Check if user is allowed to access a feature / make an action
3383 * @param string ... Permissions to test
3384 * @return bool True if user is allowed to perform *any* of the given actions
3386 public function isAllowedAny() {
3387 $permissions = func_get_args();
3388 foreach ( $permissions as $permission ) {
3389 if ( $this->isAllowed( $permission ) ) {
3398 * @param string ... Permissions to test
3399 * @return bool True if the user is allowed to perform *all* of the given actions
3401 public function isAllowedAll() {
3402 $permissions = func_get_args();
3403 foreach ( $permissions as $permission ) {
3404 if ( !$this->isAllowed( $permission ) ) {
3412 * Internal mechanics of testing a permission
3413 * @param string $action
3416 public function isAllowed( $action = '' ) {
3417 if ( $action === '' ) {
3418 return true; // In the spirit of DWIM
3420 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3421 // by misconfiguration: 0 == 'foo'
3422 return in_array( $action, $this->getRights(), true );
3426 * Check whether to enable recent changes patrol features for this user
3427 * @return bool True or false
3429 public function useRCPatrol() {
3430 global $wgUseRCPatrol;
3431 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3435 * Check whether to enable new pages patrol features for this user
3436 * @return bool True or false
3438 public function useNPPatrol() {
3439 global $wgUseRCPatrol, $wgUseNPPatrol;
3441 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3442 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3447 * Check whether to enable new files patrol features for this user
3448 * @return bool True or false
3450 public function useFilePatrol() {
3451 global $wgUseRCPatrol, $wgUseFilePatrol;
3453 ( $wgUseRCPatrol ||
$wgUseFilePatrol )
3454 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3459 * Get the WebRequest object to use with this object
3461 * @return WebRequest
3463 public function getRequest() {
3464 if ( $this->mRequest
) {
3465 return $this->mRequest
;
3473 * Check the watched status of an article.
3474 * @since 1.22 $checkRights parameter added
3475 * @param Title $title Title of the article to look at
3476 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3477 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3480 public function isWatched( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3481 if ( $title->isWatchable() && ( !$checkRights ||
$this->isAllowed( 'viewmywatchlist' ) ) ) {
3482 return MediaWikiServices
::getInstance()->getWatchedItemStore()->isWatched( $this, $title );
3489 * @since 1.22 $checkRights parameter added
3490 * @param Title $title Title of the article to look at
3491 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3492 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3494 public function addWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3495 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3496 MediaWikiServices
::getInstance()->getWatchedItemStore()->addWatchBatchForUser(
3498 [ $title->getSubjectPage(), $title->getTalkPage() ]
3501 $this->invalidateCache();
3505 * Stop watching an article.
3506 * @since 1.22 $checkRights parameter added
3507 * @param Title $title Title of the article to look at
3508 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3509 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3511 public function removeWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3512 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3513 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
3514 $store->removeWatch( $this, $title->getSubjectPage() );
3515 $store->removeWatch( $this, $title->getTalkPage() );
3517 $this->invalidateCache();
3521 * Clear the user's notification timestamp for the given title.
3522 * If e-notif e-mails are on, they will receive notification mails on
3523 * the next change of the page if it's watched etc.
3524 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3525 * @param Title $title Title of the article to look at
3526 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3528 public function clearNotification( &$title, $oldid = 0 ) {
3529 global $wgUseEnotif, $wgShowUpdatedMarker;
3531 // Do nothing if the database is locked to writes
3532 if ( wfReadOnly() ) {
3536 // Do nothing if not allowed to edit the watchlist
3537 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3541 // If we're working on user's talk page, we should update the talk page message indicator
3542 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3543 if ( !Hooks
::run( 'UserClearNewTalkNotification', [ &$this, $oldid ] ) ) {
3547 // Try to update the DB post-send and only if needed...
3548 DeferredUpdates
::addCallableUpdate( function() use ( $title, $oldid ) {
3549 if ( !$this->getNewtalk() ) {
3550 return; // no notifications to clear
3553 // Delete the last notifications (they stack up)
3554 $this->setNewtalk( false );
3556 // If there is a new, unseen, revision, use its timestamp
3558 ?
$title->getNextRevisionID( $oldid, Title
::GAID_FOR_UPDATE
)
3561 $this->setNewtalk( true, Revision
::newFromId( $nextid ) );
3566 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3570 if ( $this->isAnon() ) {
3571 // Nothing else to do...
3575 // Only update the timestamp if the page is being watched.
3576 // The query to find out if it is watched is cached both in memcached and per-invocation,
3577 // and when it does have to be executed, it can be on a slave
3578 // If this is the user's newtalk page, we always update the timestamp
3580 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3584 MediaWikiServices
::getInstance()->getWatchedItemStore()
3585 ->resetNotificationTimestamp( $this, $title, $force, $oldid );
3589 * Resets all of the given user's page-change notification timestamps.
3590 * If e-notif e-mails are on, they will receive notification mails on
3591 * the next change of any watched page.
3592 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3594 public function clearAllNotifications() {
3595 if ( wfReadOnly() ) {
3599 // Do nothing if not allowed to edit the watchlist
3600 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3604 global $wgUseEnotif, $wgShowUpdatedMarker;
3605 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3606 $this->setNewtalk( false );
3609 $id = $this->getId();
3611 $dbw = wfGetDB( DB_MASTER
);
3612 $dbw->update( 'watchlist',
3613 [ /* SET */ 'wl_notificationtimestamp' => null ],
3614 [ /* WHERE */ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ],
3617 // We also need to clear here the "you have new message" notification for the own user_talk page;
3618 // it's cleared one page view later in WikiPage::doViewUpdates().
3623 * Set a cookie on the user's client. Wrapper for
3624 * WebResponse::setCookie
3625 * @deprecated since 1.27
3626 * @param string $name Name of the cookie to set
3627 * @param string $value Value to set
3628 * @param int $exp Expiration time, as a UNIX time value;
3629 * if 0 or not specified, use the default $wgCookieExpiration
3630 * @param bool $secure
3631 * true: Force setting the secure attribute when setting the cookie
3632 * false: Force NOT setting the secure attribute when setting the cookie
3633 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3634 * @param array $params Array of options sent passed to WebResponse::setcookie()
3635 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3638 protected function setCookie(
3639 $name, $value, $exp = 0, $secure = null, $params = [], $request = null
3641 wfDeprecated( __METHOD__
, '1.27' );
3642 if ( $request === null ) {
3643 $request = $this->getRequest();
3645 $params['secure'] = $secure;
3646 $request->response()->setCookie( $name, $value, $exp, $params );
3650 * Clear a cookie on the user's client
3651 * @deprecated since 1.27
3652 * @param string $name Name of the cookie to clear
3653 * @param bool $secure
3654 * true: Force setting the secure attribute when setting the cookie
3655 * false: Force NOT setting the secure attribute when setting the cookie
3656 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3657 * @param array $params Array of options sent passed to WebResponse::setcookie()
3659 protected function clearCookie( $name, $secure = null, $params = [] ) {
3660 wfDeprecated( __METHOD__
, '1.27' );
3661 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3665 * Set an extended login cookie on the user's client. The expiry of the cookie
3666 * is controlled by the $wgExtendedLoginCookieExpiration configuration
3669 * @see User::setCookie
3671 * @deprecated since 1.27
3672 * @param string $name Name of the cookie to set
3673 * @param string $value Value to set
3674 * @param bool $secure
3675 * true: Force setting the secure attribute when setting the cookie
3676 * false: Force NOT setting the secure attribute when setting the cookie
3677 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3679 protected function setExtendedLoginCookie( $name, $value, $secure ) {
3680 global $wgExtendedLoginCookieExpiration, $wgCookieExpiration;
3682 wfDeprecated( __METHOD__
, '1.27' );
3685 $exp +
= $wgExtendedLoginCookieExpiration !== null
3686 ?
$wgExtendedLoginCookieExpiration
3687 : $wgCookieExpiration;
3689 $this->setCookie( $name, $value, $exp, $secure );
3693 * Persist this user's session (e.g. set cookies)
3695 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3697 * @param bool $secure Whether to force secure/insecure cookies or use default
3698 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3700 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3702 if ( 0 == $this->mId
) {
3706 $session = $this->getRequest()->getSession();
3707 if ( $request && $session->getRequest() !== $request ) {
3708 $session = $session->sessionWithRequest( $request );
3710 $delay = $session->delaySave();
3712 if ( !$session->getUser()->equals( $this ) ) {
3713 if ( !$session->canSetUser() ) {
3714 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3715 ->warning( __METHOD__
.
3716 ": Cannot save user \"$this\" to a user \"{$session->getUser()}\"'s immutable session"
3720 $session->setUser( $this );
3723 $session->setRememberUser( $rememberMe );
3724 if ( $secure !== null ) {
3725 $session->setForceHTTPS( $secure );
3728 $session->persist();
3730 ScopedCallback
::consume( $delay );
3734 * Log this user out.
3736 public function logout() {
3737 if ( Hooks
::run( 'UserLogout', [ &$this ] ) ) {
3743 * Clear the user's session, and reset the instance cache.
3746 public function doLogout() {
3747 $session = $this->getRequest()->getSession();
3748 if ( !$session->canSetUser() ) {
3749 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3750 ->warning( __METHOD__
. ": Cannot log out of an immutable session" );
3751 $error = 'immutable';
3752 } elseif ( !$session->getUser()->equals( $this ) ) {
3753 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3754 ->warning( __METHOD__
.
3755 ": Cannot log user \"$this\" out of a user \"{$session->getUser()}\"'s session"
3757 // But we still may as well make this user object anon
3758 $this->clearInstanceCache( 'defaults' );
3759 $error = 'wronguser';
3761 $this->clearInstanceCache( 'defaults' );
3762 $delay = $session->delaySave();
3763 $session->unpersist(); // Clear cookies (T127436)
3764 $session->setLoggedOutTimestamp( time() );
3765 $session->setUser( new User
);
3766 $session->set( 'wsUserID', 0 ); // Other code expects this
3767 $session->resetAllTokens();
3768 ScopedCallback
::consume( $delay );
3771 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authmanager' )->info( 'Logout', [
3772 'event' => 'logout',
3773 'successful' => $error === false,
3774 'status' => $error ?
: 'success',
3779 * Save this user's settings into the database.
3780 * @todo Only rarely do all these fields need to be set!
3782 public function saveSettings() {
3783 if ( wfReadOnly() ) {
3784 // @TODO: caller should deal with this instead!
3785 // This should really just be an exception.
3786 MWExceptionHandler
::logException( new DBExpectedError(
3788 "Could not update user with ID '{$this->mId}'; DB is read-only."
3794 if ( 0 == $this->mId
) {
3798 // Get a new user_touched that is higher than the old one.
3799 // This will be used for a CAS check as a last-resort safety
3800 // check against race conditions and slave lag.
3801 $newTouched = $this->newTouchedTimestamp();
3803 $dbw = wfGetDB( DB_MASTER
);
3804 $dbw->update( 'user',
3806 'user_name' => $this->mName
,
3807 'user_real_name' => $this->mRealName
,
3808 'user_email' => $this->mEmail
,
3809 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3810 'user_touched' => $dbw->timestamp( $newTouched ),
3811 'user_token' => strval( $this->mToken
),
3812 'user_email_token' => $this->mEmailToken
,
3813 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
3814 ], $this->makeUpdateConditions( $dbw, [ /* WHERE */
3815 'user_id' => $this->mId
,
3819 if ( !$dbw->affectedRows() ) {
3820 // Maybe the problem was a missed cache update; clear it to be safe
3821 $this->clearSharedCache( 'refresh' );
3822 // User was changed in the meantime or loaded with stale data
3823 $from = ( $this->queryFlagsUsed
& self
::READ_LATEST
) ?
'master' : 'slave';
3824 throw new MWException(
3825 "CAS update failed on user_touched for user ID '{$this->mId}' (read from $from);" .
3826 " the version of the user to be saved is older than the current version."
3830 $this->mTouched
= $newTouched;
3831 $this->saveOptions();
3833 Hooks
::run( 'UserSaveSettings', [ $this ] );
3834 $this->clearSharedCache();
3835 $this->getUserPage()->invalidateCache();
3839 * If only this user's username is known, and it exists, return the user ID.
3841 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
3844 public function idForName( $flags = 0 ) {
3845 $s = trim( $this->getName() );
3850 $db = ( ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
)
3851 ?
wfGetDB( DB_MASTER
)
3852 : wfGetDB( DB_SLAVE
);
3854 $options = ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
)
3855 ?
[ 'LOCK IN SHARE MODE' ]
3858 $id = $db->selectField( 'user',
3859 'user_id', [ 'user_name' => $s ], __METHOD__
, $options );
3865 * Add a user to the database, return the user object
3867 * @param string $name Username to add
3868 * @param array $params Array of Strings Non-default parameters to save to
3869 * the database as user_* fields:
3870 * - email: The user's email address.
3871 * - email_authenticated: The email authentication timestamp.
3872 * - real_name: The user's real name.
3873 * - options: An associative array of non-default options.
3874 * - token: Random authentication token. Do not set.
3875 * - registration: Registration timestamp. Do not set.
3877 * @return User|null User object, or null if the username already exists.
3879 public static function createNew( $name, $params = [] ) {
3880 foreach ( [ 'password', 'newpassword', 'newpass_time', 'password_expires' ] as $field ) {
3881 if ( isset( $params[$field] ) ) {
3882 wfDeprecated( __METHOD__
. " with param '$field'", '1.27' );
3883 unset( $params[$field] );
3889 $user->setToken(); // init token
3890 if ( isset( $params['options'] ) ) {
3891 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
3892 unset( $params['options'] );
3894 $dbw = wfGetDB( DB_MASTER
);
3895 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3897 $noPass = PasswordFactory
::newInvalidPassword()->toString();
3900 'user_id' => $seqVal,
3901 'user_name' => $name,
3902 'user_password' => $noPass,
3903 'user_newpassword' => $noPass,
3904 'user_email' => $user->mEmail
,
3905 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
3906 'user_real_name' => $user->mRealName
,
3907 'user_token' => strval( $user->mToken
),
3908 'user_registration' => $dbw->timestamp( $user->mRegistration
),
3909 'user_editcount' => 0,
3910 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
3912 foreach ( $params as $name => $value ) {
3913 $fields["user_$name"] = $value;
3915 $dbw->insert( 'user', $fields, __METHOD__
, [ 'IGNORE' ] );
3916 if ( $dbw->affectedRows() ) {
3917 $newUser = User
::newFromId( $dbw->insertId() );
3925 * Add this existing user object to the database. If the user already
3926 * exists, a fatal status object is returned, and the user object is
3927 * initialised with the data from the database.
3929 * Previously, this function generated a DB error due to a key conflict
3930 * if the user already existed. Many extension callers use this function
3931 * in code along the lines of:
3933 * $user = User::newFromName( $name );
3934 * if ( !$user->isLoggedIn() ) {
3935 * $user->addToDatabase();
3937 * // do something with $user...
3939 * However, this was vulnerable to a race condition (bug 16020). By
3940 * initialising the user object if the user exists, we aim to support this
3941 * calling sequence as far as possible.
3943 * Note that if the user exists, this function will acquire a write lock,
3944 * so it is still advisable to make the call conditional on isLoggedIn(),
3945 * and to commit the transaction after calling.
3947 * @throws MWException
3950 public function addToDatabase() {
3952 if ( !$this->mToken
) {
3953 $this->setToken(); // init token
3956 $this->mTouched
= $this->newTouchedTimestamp();
3958 $noPass = PasswordFactory
::newInvalidPassword()->toString();
3960 $dbw = wfGetDB( DB_MASTER
);
3961 $inWrite = $dbw->writesOrCallbacksPending();
3962 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3963 $dbw->insert( 'user',
3965 'user_id' => $seqVal,
3966 'user_name' => $this->mName
,
3967 'user_password' => $noPass,
3968 'user_newpassword' => $noPass,
3969 'user_email' => $this->mEmail
,
3970 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3971 'user_real_name' => $this->mRealName
,
3972 'user_token' => strval( $this->mToken
),
3973 'user_registration' => $dbw->timestamp( $this->mRegistration
),
3974 'user_editcount' => 0,
3975 'user_touched' => $dbw->timestamp( $this->mTouched
),
3979 if ( !$dbw->affectedRows() ) {
3980 // The queries below cannot happen in the same REPEATABLE-READ snapshot.
3981 // Handle this by COMMIT, if possible, or by LOCK IN SHARE MODE otherwise.
3983 // Can't commit due to pending writes that may need atomicity.
3984 // This may cause some lock contention unlike the case below.
3985 $options = [ 'LOCK IN SHARE MODE' ];
3986 $flags = self
::READ_LOCKING
;
3988 // Often, this case happens early in views before any writes when
3989 // using CentralAuth. It's should be OK to commit and break the snapshot.
3990 $dbw->commit( __METHOD__
, 'flush' );
3992 $flags = self
::READ_LATEST
;
3994 $this->mId
= $dbw->selectField( 'user', 'user_id',
3995 [ 'user_name' => $this->mName
], __METHOD__
, $options );
3998 if ( $this->loadFromDatabase( $flags ) ) {
4003 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
4004 "to insert user '{$this->mName}' row, but it was not present in select!" );
4006 return Status
::newFatal( 'userexists' );
4008 $this->mId
= $dbw->insertId();
4009 self
::$idCacheByName[$this->mName
] = $this->mId
;
4011 // Clear instance cache other than user table data, which is already accurate
4012 $this->clearInstanceCache();
4014 $this->saveOptions();
4015 return Status
::newGood();
4019 * If this user is logged-in and blocked,
4020 * block any IP address they've successfully logged in from.
4021 * @return bool A block was spread
4023 public function spreadAnyEditBlock() {
4024 if ( $this->isLoggedIn() && $this->isBlocked() ) {
4025 return $this->spreadBlock();
4032 * If this (non-anonymous) user is blocked,
4033 * block the IP address they've successfully logged in from.
4034 * @return bool A block was spread
4036 protected function spreadBlock() {
4037 wfDebug( __METHOD__
. "()\n" );
4039 if ( $this->mId
== 0 ) {
4043 $userblock = Block
::newFromTarget( $this->getName() );
4044 if ( !$userblock ) {
4048 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
4052 * Get whether the user is explicitly blocked from account creation.
4053 * @return bool|Block
4055 public function isBlockedFromCreateAccount() {
4056 $this->getBlockedStatus();
4057 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
4058 return $this->mBlock
;
4061 # bug 13611: if the IP address the user is trying to create an account from is
4062 # blocked with createaccount disabled, prevent new account creation there even
4063 # when the user is logged in
4064 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
4065 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
4067 return $this->mBlockedFromCreateAccount
instanceof Block
4068 && $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
4069 ?
$this->mBlockedFromCreateAccount
4074 * Get whether the user is blocked from using Special:Emailuser.
4077 public function isBlockedFromEmailuser() {
4078 $this->getBlockedStatus();
4079 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
4083 * Get whether the user is allowed to create an account.
4086 public function isAllowedToCreateAccount() {
4087 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
4091 * Get this user's personal page title.
4093 * @return Title User's personal page title
4095 public function getUserPage() {
4096 return Title
::makeTitle( NS_USER
, $this->getName() );
4100 * Get this user's talk page title.
4102 * @return Title User's talk page title
4104 public function getTalkPage() {
4105 $title = $this->getUserPage();
4106 return $title->getTalkPage();
4110 * Determine whether the user is a newbie. Newbies are either
4111 * anonymous IPs, or the most recently created accounts.
4114 public function isNewbie() {
4115 return !$this->isAllowed( 'autoconfirmed' );
4119 * Check to see if the given clear-text password is one of the accepted passwords
4120 * @deprecated since 1.27, use AuthManager instead
4121 * @param string $password User password
4122 * @return bool True if the given password is correct, otherwise False
4124 public function checkPassword( $password ) {
4125 $manager = AuthManager
::singleton();
4126 $reqs = AuthenticationRequest
::loadRequestsFromSubmission(
4127 $manager->getAuthenticationRequests( AuthManager
::ACTION_LOGIN
),
4129 'username' => $this->getName(),
4130 'password' => $password,
4133 $res = AuthManager
::singleton()->beginAuthentication( $reqs, 'null:' );
4134 switch ( $res->status
) {
4135 case AuthenticationResponse
::PASS
:
4137 case AuthenticationResponse
::FAIL
:
4138 // Hope it's not a PreAuthenticationProvider that failed...
4139 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
4140 ->info( __METHOD__
. ': Authentication failed: ' . $res->message
->plain() );
4143 throw new BadMethodCallException(
4144 'AuthManager returned a response unsupported by ' . __METHOD__
4150 * Check if the given clear-text password matches the temporary password
4151 * sent by e-mail for password reset operations.
4153 * @deprecated since 1.27, use AuthManager instead
4154 * @param string $plaintext
4155 * @return bool True if matches, false otherwise
4157 public function checkTemporaryPassword( $plaintext ) {
4158 // Can't check the temporary password individually.
4159 return $this->checkPassword( $plaintext );
4163 * Initialize (if necessary) and return a session token value
4164 * which can be used in edit forms to show that the user's
4165 * login credentials aren't being hijacked with a foreign form
4169 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4170 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4171 * @return MediaWiki\Session\Token The new edit token
4173 public function getEditTokenObject( $salt = '', $request = null ) {
4174 if ( $this->isAnon() ) {
4175 return new LoggedOutEditToken();
4179 $request = $this->getRequest();
4181 return $request->getSession()->getToken( $salt );
4185 * Initialize (if necessary) and return a session token value
4186 * which can be used in edit forms to show that the user's
4187 * login credentials aren't being hijacked with a foreign form
4191 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4192 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4193 * @return string The new edit token
4195 public function getEditToken( $salt = '', $request = null ) {
4196 return $this->getEditTokenObject( $salt, $request )->toString();
4200 * Get the embedded timestamp from a token.
4201 * @deprecated since 1.27, use \MediaWiki\Session\Token::getTimestamp instead.
4202 * @param string $val Input token
4205 public static function getEditTokenTimestamp( $val ) {
4206 wfDeprecated( __METHOD__
, '1.27' );
4207 return MediaWiki\Session\Token
::getTimestamp( $val );
4211 * Check given value against the token value stored in the session.
4212 * A match should confirm that the form was submitted from the
4213 * user's own login session, not a form submission from a third-party
4216 * @param string $val Input value to compare
4217 * @param string $salt Optional function-specific data for hashing
4218 * @param WebRequest|null $request Object to use or null to use $wgRequest
4219 * @param int $maxage Fail tokens older than this, in seconds
4220 * @return bool Whether the token matches
4222 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4223 return $this->getEditTokenObject( $salt, $request )->match( $val, $maxage );
4227 * Check given value against the token value stored in the session,
4228 * ignoring the suffix.
4230 * @param string $val Input value to compare
4231 * @param string $salt Optional function-specific data for hashing
4232 * @param WebRequest|null $request Object to use or null to use $wgRequest
4233 * @param int $maxage Fail tokens older than this, in seconds
4234 * @return bool Whether the token matches
4236 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4237 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . Token
::SUFFIX
;
4238 return $this->matchEditToken( $val, $salt, $request, $maxage );
4242 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4243 * mail to the user's given address.
4245 * @param string $type Message to send, either "created", "changed" or "set"
4248 public function sendConfirmationMail( $type = 'created' ) {
4250 $expiration = null; // gets passed-by-ref and defined in next line.
4251 $token = $this->confirmationToken( $expiration );
4252 $url = $this->confirmationTokenUrl( $token );
4253 $invalidateURL = $this->invalidationTokenUrl( $token );
4254 $this->saveSettings();
4256 if ( $type == 'created' ||
$type === false ) {
4257 $message = 'confirmemail_body';
4258 } elseif ( $type === true ) {
4259 $message = 'confirmemail_body_changed';
4261 // Messages: confirmemail_body_changed, confirmemail_body_set
4262 $message = 'confirmemail_body_' . $type;
4265 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4266 wfMessage( $message,
4267 $this->getRequest()->getIP(),
4270 $wgLang->userTimeAndDate( $expiration, $this ),
4272 $wgLang->userDate( $expiration, $this ),
4273 $wgLang->userTime( $expiration, $this ) )->text() );
4277 * Send an e-mail to this user's account. Does not check for
4278 * confirmed status or validity.
4280 * @param string $subject Message subject
4281 * @param string $body Message body
4282 * @param User|null $from Optional sending user; if unspecified, default
4283 * $wgPasswordSender will be used.
4284 * @param string $replyto Reply-To address
4287 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4288 global $wgPasswordSender;
4290 if ( $from instanceof User
) {
4291 $sender = MailAddress
::newFromUser( $from );
4293 $sender = new MailAddress( $wgPasswordSender,
4294 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4296 $to = MailAddress
::newFromUser( $this );
4298 return UserMailer
::send( $to, $sender, $subject, $body, [
4299 'replyTo' => $replyto,
4304 * Generate, store, and return a new e-mail confirmation code.
4305 * A hash (unsalted, since it's used as a key) is stored.
4307 * @note Call saveSettings() after calling this function to commit
4308 * this change to the database.
4310 * @param string &$expiration Accepts the expiration time
4311 * @return string New token
4313 protected function confirmationToken( &$expiration ) {
4314 global $wgUserEmailConfirmationTokenExpiry;
4316 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4317 $expiration = wfTimestamp( TS_MW
, $expires );
4319 $token = MWCryptRand
::generateHex( 32 );
4320 $hash = md5( $token );
4321 $this->mEmailToken
= $hash;
4322 $this->mEmailTokenExpires
= $expiration;
4327 * Return a URL the user can use to confirm their email address.
4328 * @param string $token Accepts the email confirmation token
4329 * @return string New token URL
4331 protected function confirmationTokenUrl( $token ) {
4332 return $this->getTokenUrl( 'ConfirmEmail', $token );
4336 * Return a URL the user can use to invalidate their email address.
4337 * @param string $token Accepts the email confirmation token
4338 * @return string New token URL
4340 protected function invalidationTokenUrl( $token ) {
4341 return $this->getTokenUrl( 'InvalidateEmail', $token );
4345 * Internal function to format the e-mail validation/invalidation URLs.
4346 * This uses a quickie hack to use the
4347 * hardcoded English names of the Special: pages, for ASCII safety.
4349 * @note Since these URLs get dropped directly into emails, using the
4350 * short English names avoids insanely long URL-encoded links, which
4351 * also sometimes can get corrupted in some browsers/mailers
4352 * (bug 6957 with Gmail and Internet Explorer).
4354 * @param string $page Special page
4355 * @param string $token Token
4356 * @return string Formatted URL
4358 protected function getTokenUrl( $page, $token ) {
4359 // Hack to bypass localization of 'Special:'
4360 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4361 return $title->getCanonicalURL();
4365 * Mark the e-mail address confirmed.
4367 * @note Call saveSettings() after calling this function to commit the change.
4371 public function confirmEmail() {
4372 // Check if it's already confirmed, so we don't touch the database
4373 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4374 if ( !$this->isEmailConfirmed() ) {
4375 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4376 Hooks
::run( 'ConfirmEmailComplete', [ $this ] );
4382 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4383 * address if it was already confirmed.
4385 * @note Call saveSettings() after calling this function to commit the change.
4386 * @return bool Returns true
4388 public function invalidateEmail() {
4390 $this->mEmailToken
= null;
4391 $this->mEmailTokenExpires
= null;
4392 $this->setEmailAuthenticationTimestamp( null );
4394 Hooks
::run( 'InvalidateEmailComplete', [ $this ] );
4399 * Set the e-mail authentication timestamp.
4400 * @param string $timestamp TS_MW timestamp
4402 public function setEmailAuthenticationTimestamp( $timestamp ) {
4404 $this->mEmailAuthenticated
= $timestamp;
4405 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
4409 * Is this user allowed to send e-mails within limits of current
4410 * site configuration?
4413 public function canSendEmail() {
4414 global $wgEnableEmail, $wgEnableUserEmail;
4415 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4418 $canSend = $this->isEmailConfirmed();
4419 Hooks
::run( 'UserCanSendEmail', [ &$this, &$canSend ] );
4424 * Is this user allowed to receive e-mails within limits of current
4425 * site configuration?
4428 public function canReceiveEmail() {
4429 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4433 * Is this user's e-mail address valid-looking and confirmed within
4434 * limits of the current site configuration?
4436 * @note If $wgEmailAuthentication is on, this may require the user to have
4437 * confirmed their address by returning a code or using a password
4438 * sent to the address from the wiki.
4442 public function isEmailConfirmed() {
4443 global $wgEmailAuthentication;
4446 if ( Hooks
::run( 'EmailConfirmed', [ &$this, &$confirmed ] ) ) {
4447 if ( $this->isAnon() ) {
4450 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4453 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4463 * Check whether there is an outstanding request for e-mail confirmation.
4466 public function isEmailConfirmationPending() {
4467 global $wgEmailAuthentication;
4468 return $wgEmailAuthentication &&
4469 !$this->isEmailConfirmed() &&
4470 $this->mEmailToken
&&
4471 $this->mEmailTokenExpires
> wfTimestamp();
4475 * Get the timestamp of account creation.
4477 * @return string|bool|null Timestamp of account creation, false for
4478 * non-existent/anonymous user accounts, or null if existing account
4479 * but information is not in database.
4481 public function getRegistration() {
4482 if ( $this->isAnon() ) {
4486 return $this->mRegistration
;
4490 * Get the timestamp of the first edit
4492 * @return string|bool Timestamp of first edit, or false for
4493 * non-existent/anonymous user accounts.
4495 public function getFirstEditTimestamp() {
4496 if ( $this->getId() == 0 ) {
4497 return false; // anons
4499 $dbr = wfGetDB( DB_SLAVE
);
4500 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4501 [ 'rev_user' => $this->getId() ],
4503 [ 'ORDER BY' => 'rev_timestamp ASC' ]
4506 return false; // no edits
4508 return wfTimestamp( TS_MW
, $time );
4512 * Get the permissions associated with a given list of groups
4514 * @param array $groups Array of Strings List of internal group names
4515 * @return array Array of Strings List of permission key names for given groups combined
4517 public static function getGroupPermissions( $groups ) {
4518 global $wgGroupPermissions, $wgRevokePermissions;
4520 // grant every granted permission first
4521 foreach ( $groups as $group ) {
4522 if ( isset( $wgGroupPermissions[$group] ) ) {
4523 $rights = array_merge( $rights,
4524 // array_filter removes empty items
4525 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4528 // now revoke the revoked permissions
4529 foreach ( $groups as $group ) {
4530 if ( isset( $wgRevokePermissions[$group] ) ) {
4531 $rights = array_diff( $rights,
4532 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4535 return array_unique( $rights );
4539 * Get all the groups who have a given permission
4541 * @param string $role Role to check
4542 * @return array Array of Strings List of internal group names with the given permission
4544 public static function getGroupsWithPermission( $role ) {
4545 global $wgGroupPermissions;
4546 $allowedGroups = [];
4547 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4548 if ( self
::groupHasPermission( $group, $role ) ) {
4549 $allowedGroups[] = $group;
4552 return $allowedGroups;
4556 * Check, if the given group has the given permission
4558 * If you're wanting to check whether all users have a permission, use
4559 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4563 * @param string $group Group to check
4564 * @param string $role Role to check
4567 public static function groupHasPermission( $group, $role ) {
4568 global $wgGroupPermissions, $wgRevokePermissions;
4569 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4570 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4574 * Check if all users may be assumed to have the given permission
4576 * We generally assume so if the right is granted to '*' and isn't revoked
4577 * on any group. It doesn't attempt to take grants or other extension
4578 * limitations on rights into account in the general case, though, as that
4579 * would require it to always return false and defeat the purpose.
4580 * Specifically, session-based rights restrictions (such as OAuth or bot
4581 * passwords) are applied based on the current session.
4584 * @param string $right Right to check
4587 public static function isEveryoneAllowed( $right ) {
4588 global $wgGroupPermissions, $wgRevokePermissions;
4591 // Use the cached results, except in unit tests which rely on
4592 // being able change the permission mid-request
4593 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4594 return $cache[$right];
4597 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4598 $cache[$right] = false;
4602 // If it's revoked anywhere, then everyone doesn't have it
4603 foreach ( $wgRevokePermissions as $rights ) {
4604 if ( isset( $rights[$right] ) && $rights[$right] ) {
4605 $cache[$right] = false;
4610 // Remove any rights that aren't allowed to the global-session user,
4611 // unless there are no sessions for this endpoint.
4612 if ( !defined( 'MW_NO_SESSION' ) ) {
4613 $allowedRights = SessionManager
::getGlobalSession()->getAllowedUserRights();
4614 if ( $allowedRights !== null && !in_array( $right, $allowedRights, true ) ) {
4615 $cache[$right] = false;
4620 // Allow extensions to say false
4621 if ( !Hooks
::run( 'UserIsEveryoneAllowed', [ $right ] ) ) {
4622 $cache[$right] = false;
4626 $cache[$right] = true;
4631 * Get the localized descriptive name for a group, if it exists
4633 * @param string $group Internal group name
4634 * @return string Localized descriptive group name
4636 public static function getGroupName( $group ) {
4637 $msg = wfMessage( "group-$group" );
4638 return $msg->isBlank() ?
$group : $msg->text();
4642 * Get the localized descriptive name for a member of a group, if it exists
4644 * @param string $group Internal group name
4645 * @param string $username Username for gender (since 1.19)
4646 * @return string Localized name for group member
4648 public static function getGroupMember( $group, $username = '#' ) {
4649 $msg = wfMessage( "group-$group-member", $username );
4650 return $msg->isBlank() ?
$group : $msg->text();
4654 * Return the set of defined explicit groups.
4655 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4656 * are not included, as they are defined automatically, not in the database.
4657 * @return array Array of internal group names
4659 public static function getAllGroups() {
4660 global $wgGroupPermissions, $wgRevokePermissions;
4662 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4663 self
::getImplicitGroups()
4668 * Get a list of all available permissions.
4669 * @return string[] Array of permission names
4671 public static function getAllRights() {
4672 if ( self
::$mAllRights === false ) {
4673 global $wgAvailableRights;
4674 if ( count( $wgAvailableRights ) ) {
4675 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
4677 self
::$mAllRights = self
::$mCoreRights;
4679 Hooks
::run( 'UserGetAllRights', [ &self
::$mAllRights ] );
4681 return self
::$mAllRights;
4685 * Get a list of implicit groups
4686 * @return array Array of Strings Array of internal group names
4688 public static function getImplicitGroups() {
4689 global $wgImplicitGroups;
4691 $groups = $wgImplicitGroups;
4692 # Deprecated, use $wgImplicitGroups instead
4693 Hooks
::run( 'UserGetImplicitGroups', [ &$groups ], '1.25' );
4699 * Get the title of a page describing a particular group
4701 * @param string $group Internal group name
4702 * @return Title|bool Title of the page if it exists, false otherwise
4704 public static function getGroupPage( $group ) {
4705 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4706 if ( $msg->exists() ) {
4707 $title = Title
::newFromText( $msg->text() );
4708 if ( is_object( $title ) ) {
4716 * Create a link to the group in HTML, if available;
4717 * else return the group name.
4719 * @param string $group Internal name of the group
4720 * @param string $text The text of the link
4721 * @return string HTML link to the group
4723 public static function makeGroupLinkHTML( $group, $text = '' ) {
4724 if ( $text == '' ) {
4725 $text = self
::getGroupName( $group );
4727 $title = self
::getGroupPage( $group );
4729 return Linker
::link( $title, htmlspecialchars( $text ) );
4731 return htmlspecialchars( $text );
4736 * Create a link to the group in Wikitext, if available;
4737 * else return the group name.
4739 * @param string $group Internal name of the group
4740 * @param string $text The text of the link
4741 * @return string Wikilink to the group
4743 public static function makeGroupLinkWiki( $group, $text = '' ) {
4744 if ( $text == '' ) {
4745 $text = self
::getGroupName( $group );
4747 $title = self
::getGroupPage( $group );
4749 $page = $title->getFullText();
4750 return "[[$page|$text]]";
4757 * Returns an array of the groups that a particular group can add/remove.
4759 * @param string $group The group to check for whether it can add/remove
4760 * @return array Array( 'add' => array( addablegroups ),
4761 * 'remove' => array( removablegroups ),
4762 * 'add-self' => array( addablegroups to self),
4763 * 'remove-self' => array( removable groups from self) )
4765 public static function changeableByGroup( $group ) {
4766 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4775 if ( empty( $wgAddGroups[$group] ) ) {
4776 // Don't add anything to $groups
4777 } elseif ( $wgAddGroups[$group] === true ) {
4778 // You get everything
4779 $groups['add'] = self
::getAllGroups();
4780 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4781 $groups['add'] = $wgAddGroups[$group];
4784 // Same thing for remove
4785 if ( empty( $wgRemoveGroups[$group] ) ) {
4787 } elseif ( $wgRemoveGroups[$group] === true ) {
4788 $groups['remove'] = self
::getAllGroups();
4789 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4790 $groups['remove'] = $wgRemoveGroups[$group];
4793 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4794 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4795 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4796 if ( is_int( $key ) ) {
4797 $wgGroupsAddToSelf['user'][] = $value;
4802 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
4803 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4804 if ( is_int( $key ) ) {
4805 $wgGroupsRemoveFromSelf['user'][] = $value;
4810 // Now figure out what groups the user can add to him/herself
4811 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4813 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4814 // No idea WHY this would be used, but it's there
4815 $groups['add-self'] = User
::getAllGroups();
4816 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4817 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4820 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4822 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4823 $groups['remove-self'] = User
::getAllGroups();
4824 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4825 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4832 * Returns an array of groups that this user can add and remove
4833 * @return array Array( 'add' => array( addablegroups ),
4834 * 'remove' => array( removablegroups ),
4835 * 'add-self' => array( addablegroups to self),
4836 * 'remove-self' => array( removable groups from self) )
4838 public function changeableGroups() {
4839 if ( $this->isAllowed( 'userrights' ) ) {
4840 // This group gives the right to modify everything (reverse-
4841 // compatibility with old "userrights lets you change
4843 // Using array_merge to make the groups reindexed
4844 $all = array_merge( User
::getAllGroups() );
4853 // Okay, it's not so simple, we will have to go through the arrays
4860 $addergroups = $this->getEffectiveGroups();
4862 foreach ( $addergroups as $addergroup ) {
4863 $groups = array_merge_recursive(
4864 $groups, $this->changeableByGroup( $addergroup )
4866 $groups['add'] = array_unique( $groups['add'] );
4867 $groups['remove'] = array_unique( $groups['remove'] );
4868 $groups['add-self'] = array_unique( $groups['add-self'] );
4869 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4875 * Deferred version of incEditCountImmediate()
4877 public function incEditCount() {
4878 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle( function() {
4879 $this->incEditCountImmediate();
4884 * Increment the user's edit-count field.
4885 * Will have no effect for anonymous users.
4888 public function incEditCountImmediate() {
4889 if ( $this->isAnon() ) {
4893 $dbw = wfGetDB( DB_MASTER
);
4894 // No rows will be "affected" if user_editcount is NULL
4897 [ 'user_editcount=user_editcount+1' ],
4898 [ 'user_id' => $this->getId(), 'user_editcount IS NOT NULL' ],
4901 // Lazy initialization check...
4902 if ( $dbw->affectedRows() == 0 ) {
4903 // Now here's a goddamn hack...
4904 $dbr = wfGetDB( DB_SLAVE
);
4905 if ( $dbr !== $dbw ) {
4906 // If we actually have a slave server, the count is
4907 // at least one behind because the current transaction
4908 // has not been committed and replicated.
4909 $this->mEditCount
= $this->initEditCount( 1 );
4911 // But if DB_SLAVE is selecting the master, then the
4912 // count we just read includes the revision that was
4913 // just added in the working transaction.
4914 $this->mEditCount
= $this->initEditCount();
4917 if ( $this->mEditCount
=== null ) {
4918 $this->getEditCount();
4919 $dbr = wfGetDB( DB_SLAVE
);
4920 $this->mEditCount +
= ( $dbr !== $dbw ) ?
1 : 0;
4922 $this->mEditCount++
;
4925 // Edit count in user cache too
4926 $this->invalidateCache();
4930 * Initialize user_editcount from data out of the revision table
4932 * @param int $add Edits to add to the count from the revision table
4933 * @return int Number of edits
4935 protected function initEditCount( $add = 0 ) {
4936 // Pull from a slave to be less cruel to servers
4937 // Accuracy isn't the point anyway here
4938 $dbr = wfGetDB( DB_SLAVE
);
4939 $count = (int)$dbr->selectField(
4942 [ 'rev_user' => $this->getId() ],
4945 $count = $count +
$add;
4947 $dbw = wfGetDB( DB_MASTER
);
4950 [ 'user_editcount' => $count ],
4951 [ 'user_id' => $this->getId() ],
4959 * Get the description of a given right
4961 * @param string $right Right to query
4962 * @return string Localized description of the right
4964 public static function getRightDescription( $right ) {
4965 $key = "right-$right";
4966 $msg = wfMessage( $key );
4967 return $msg->isBlank() ?
$right : $msg->text();
4971 * Make a new-style password hash
4973 * @param string $password Plain-text password
4974 * @param bool|string $salt Optional salt, may be random or the user ID.
4975 * If unspecified or false, will generate one automatically
4976 * @return string Password hash
4977 * @deprecated since 1.24, use Password class
4979 public static function crypt( $password, $salt = false ) {
4980 wfDeprecated( __METHOD__
, '1.24' );
4981 $passwordFactory = new PasswordFactory();
4982 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4983 $hash = $passwordFactory->newFromPlaintext( $password );
4984 return $hash->toString();
4988 * Compare a password hash with a plain-text password. Requires the user
4989 * ID if there's a chance that the hash is an old-style hash.
4991 * @param string $hash Password hash
4992 * @param string $password Plain-text password to compare
4993 * @param string|bool $userId User ID for old-style password salt
4996 * @deprecated since 1.24, use Password class
4998 public static function comparePasswords( $hash, $password, $userId = false ) {
4999 wfDeprecated( __METHOD__
, '1.24' );
5001 // Check for *really* old password hashes that don't even have a type
5002 // The old hash format was just an md5 hex hash, with no type information
5003 if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) {
5004 global $wgPasswordSalt;
5005 if ( $wgPasswordSalt ) {
5006 $password = ":B:{$userId}:{$hash}";
5008 $password = ":A:{$hash}";
5012 $passwordFactory = new PasswordFactory();
5013 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
5014 $hash = $passwordFactory->newFromCiphertext( $hash );
5015 return $hash->equals( $password );
5019 * Add a newuser log entry for this user.
5020 * Before 1.19 the return value was always true.
5022 * @deprecated since 1.27, AuthManager handles logging
5023 * @param string|bool $action Account creation type.
5024 * - String, one of the following values:
5025 * - 'create' for an anonymous user creating an account for himself.
5026 * This will force the action's performer to be the created user itself,
5027 * no matter the value of $wgUser
5028 * - 'create2' for a logged in user creating an account for someone else
5029 * - 'byemail' when the created user will receive its password by e-mail
5030 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
5031 * - Boolean means whether the account was created by e-mail (deprecated):
5032 * - true will be converted to 'byemail'
5033 * - false will be converted to 'create' if this object is the same as
5034 * $wgUser and to 'create2' otherwise
5035 * @param string $reason User supplied reason
5038 public function addNewUserLogEntry( $action = false, $reason = '' ) {
5039 return true; // disabled
5043 * Add an autocreate newuser log entry for this user
5044 * Used by things like CentralAuth and perhaps other authplugins.
5045 * Consider calling addNewUserLogEntry() directly instead.
5047 * @deprecated since 1.27, AuthManager handles logging
5050 public function addNewUserLogEntryAutoCreate() {
5051 $this->addNewUserLogEntry( 'autocreate' );
5057 * Load the user options either from cache, the database or an array
5059 * @param array $data Rows for the current user out of the user_properties table
5061 protected function loadOptions( $data = null ) {
5066 if ( $this->mOptionsLoaded
) {
5070 $this->mOptions
= self
::getDefaultOptions();
5072 if ( !$this->getId() ) {
5073 // For unlogged-in users, load language/variant options from request.
5074 // There's no need to do it for logged-in users: they can set preferences,
5075 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5076 // so don't override user's choice (especially when the user chooses site default).
5077 $variant = $wgContLang->getDefaultVariant();
5078 $this->mOptions
['variant'] = $variant;
5079 $this->mOptions
['language'] = $variant;
5080 $this->mOptionsLoaded
= true;
5084 // Maybe load from the object
5085 if ( !is_null( $this->mOptionOverrides
) ) {
5086 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5087 foreach ( $this->mOptionOverrides
as $key => $value ) {
5088 $this->mOptions
[$key] = $value;
5091 if ( !is_array( $data ) ) {
5092 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5093 // Load from database
5094 $dbr = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
5095 ?
wfGetDB( DB_MASTER
)
5096 : wfGetDB( DB_SLAVE
);
5098 $res = $dbr->select(
5100 [ 'up_property', 'up_value' ],
5101 [ 'up_user' => $this->getId() ],
5105 $this->mOptionOverrides
= [];
5107 foreach ( $res as $row ) {
5108 $data[$row->up_property
] = $row->up_value
;
5111 foreach ( $data as $property => $value ) {
5112 $this->mOptionOverrides
[$property] = $value;
5113 $this->mOptions
[$property] = $value;
5117 $this->mOptionsLoaded
= true;
5119 Hooks
::run( 'UserLoadOptions', [ $this, &$this->mOptions
] );
5123 * Saves the non-default options for this user, as previously set e.g. via
5124 * setOption(), in the database's "user_properties" (preferences) table.
5125 * Usually used via saveSettings().
5127 protected function saveOptions() {
5128 $this->loadOptions();
5130 // Not using getOptions(), to keep hidden preferences in database
5131 $saveOptions = $this->mOptions
;
5133 // Allow hooks to abort, for instance to save to a global profile.
5134 // Reset options to default state before saving.
5135 if ( !Hooks
::run( 'UserSaveOptions', [ $this, &$saveOptions ] ) ) {
5139 $userId = $this->getId();
5141 $insert_rows = []; // all the new preference rows
5142 foreach ( $saveOptions as $key => $value ) {
5143 // Don't bother storing default values
5144 $defaultOption = self
::getDefaultOption( $key );
5145 if ( ( $defaultOption === null && $value !== false && $value !== null )
5146 ||
$value != $defaultOption
5149 'up_user' => $userId,
5150 'up_property' => $key,
5151 'up_value' => $value,
5156 $dbw = wfGetDB( DB_MASTER
);
5158 $res = $dbw->select( 'user_properties',
5159 [ 'up_property', 'up_value' ], [ 'up_user' => $userId ], __METHOD__
);
5161 // Find prior rows that need to be removed or updated. These rows will
5162 // all be deleted (the later so that INSERT IGNORE applies the new values).
5164 foreach ( $res as $row ) {
5165 if ( !isset( $saveOptions[$row->up_property
] )
5166 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
5168 $keysDelete[] = $row->up_property
;
5172 if ( count( $keysDelete ) ) {
5173 // Do the DELETE by PRIMARY KEY for prior rows.
5174 // In the past a very large portion of calls to this function are for setting
5175 // 'rememberpassword' for new accounts (a preference that has since been removed).
5176 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5177 // caused gap locks on [max user ID,+infinity) which caused high contention since
5178 // updates would pile up on each other as they are for higher (newer) user IDs.
5179 // It might not be necessary these days, but it shouldn't hurt either.
5180 $dbw->delete( 'user_properties',
5181 [ 'up_user' => $userId, 'up_property' => $keysDelete ], __METHOD__
);
5183 // Insert the new preference rows
5184 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, [ 'IGNORE' ] );
5188 * Lazily instantiate and return a factory object for making passwords
5190 * @deprecated since 1.27, create a PasswordFactory directly instead
5191 * @return PasswordFactory
5193 public static function getPasswordFactory() {
5194 wfDeprecated( __METHOD__
, '1.27' );
5195 $ret = new PasswordFactory();
5196 $ret->init( RequestContext
::getMain()->getConfig() );
5201 * Provide an array of HTML5 attributes to put on an input element
5202 * intended for the user to enter a new password. This may include
5203 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
5205 * Do *not* use this when asking the user to enter his current password!
5206 * Regardless of configuration, users may have invalid passwords for whatever
5207 * reason (e.g., they were set before requirements were tightened up).
5208 * Only use it when asking for a new password, like on account creation or
5211 * Obviously, you still need to do server-side checking.
5213 * NOTE: A combination of bugs in various browsers means that this function
5214 * actually just returns array() unconditionally at the moment. May as
5215 * well keep it around for when the browser bugs get fixed, though.
5217 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
5219 * @deprecated since 1.27
5220 * @return array Array of HTML attributes suitable for feeding to
5221 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
5222 * That will get confused by the boolean attribute syntax used.)
5224 public static function passwordChangeInputAttribs() {
5225 global $wgMinimalPasswordLength;
5227 if ( $wgMinimalPasswordLength == 0 ) {
5231 # Note that the pattern requirement will always be satisfied if the
5232 # input is empty, so we need required in all cases.
5234 # @todo FIXME: Bug 23769: This needs to not claim the password is required
5235 # if e-mail confirmation is being used. Since HTML5 input validation
5236 # is b0rked anyway in some browsers, just return nothing. When it's
5237 # re-enabled, fix this code to not output required for e-mail
5239 # $ret = array( 'required' );
5242 # We can't actually do this right now, because Opera 9.6 will print out
5243 # the entered password visibly in its error message! When other
5244 # browsers add support for this attribute, or Opera fixes its support,
5245 # we can add support with a version check to avoid doing this on Opera
5246 # versions where it will be a problem. Reported to Opera as
5247 # DSK-262266, but they don't have a public bug tracker for us to follow.
5249 if ( $wgMinimalPasswordLength > 1 ) {
5250 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
5251 $ret['title'] = wfMessage( 'passwordtooshort' )
5252 ->numParams( $wgMinimalPasswordLength )->text();
5260 * Return the list of user fields that should be selected to create
5261 * a new user object.
5264 public static function selectFields() {
5272 'user_email_authenticated',
5274 'user_email_token_expires',
5275 'user_registration',
5281 * Factory function for fatal permission-denied errors
5284 * @param string $permission User right required
5287 static function newFatalPermissionDeniedStatus( $permission ) {
5290 $groups = array_map(
5291 [ 'User', 'makeGroupLinkWiki' ],
5292 User
::getGroupsWithPermission( $permission )
5296 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5298 return Status
::newFatal( 'badaccess-group0' );
5303 * Get a new instance of this user that was loaded from the master via a locking read
5305 * Use this instead of the main context User when updating that user. This avoids races
5306 * where that user was loaded from a slave or even the master but without proper locks.
5308 * @return User|null Returns null if the user was not found in the DB
5311 public function getInstanceForUpdate() {
5312 if ( !$this->getId() ) {
5313 return null; // anon
5316 $user = self
::newFromId( $this->getId() );
5317 if ( !$user->loadFromId( self
::READ_EXCLUSIVE
) ) {
5325 * Checks if two user objects point to the same user.
5331 public function equals( User
$user ) {
5332 return $this->getName() === $user->getName();