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
;
29 use Wikimedia\ScopedCallback
;
32 * String Some punctuation to prevent editing from broken text-mangling proxies.
33 * @deprecated since 1.27, use \MediaWiki\Session\Token::SUFFIX
36 define( 'EDIT_TOKEN_SUFFIX', Token
::SUFFIX
);
39 * The User object encapsulates all of the user-specific settings (user_id,
40 * name, rights, email address, options, last login time). Client
41 * classes use the getXXX() functions to access these fields. These functions
42 * do all the work of determining whether the user is logged in,
43 * whether the requested option can be satisfied from cookies or
44 * whether a database query is needed. Most of the settings needed
45 * for rendering normal pages are set in the cookie to minimize use
48 class User
implements IDBAccessObject
{
50 * @const int Number of characters in user_token field.
52 const TOKEN_LENGTH
= 32;
55 * @const string An invalid value for user_token
57 const INVALID_TOKEN
= '*** INVALID ***';
60 * Global constant made accessible as class constants so that autoloader
62 * @deprecated since 1.27, use \MediaWiki\Session\Token::SUFFIX
64 const EDIT_TOKEN_SUFFIX
= EDIT_TOKEN_SUFFIX
;
67 * @const int Serialized record version.
72 * Exclude user options that are set to their default value.
75 const GETOPTIONS_EXCLUDE_DEFAULTS
= 1;
80 const CHECK_USER_RIGHTS
= true;
85 const IGNORE_USER_RIGHTS
= false;
88 * Array of Strings List of member variables which are saved to the
89 * shared cache (memcached). Any operation which changes the
90 * corresponding database fields must call a cache-clearing function.
93 protected static $mCacheVars = [
101 'mEmailAuthenticated',
103 'mEmailTokenExpires',
108 // user_properties table
113 * Array of Strings Core rights.
114 * Each of these should have a corresponding message of the form
118 protected static $mCoreRights = [
149 'editusercssjs', # deprecated
162 'move-categorypages',
163 'move-rootuserpages',
167 'override-export-depth',
190 'userrights-interwiki',
198 * String Cached results of getAllRights()
200 protected static $mAllRights = false;
202 /** Cache variables */
213 /** @var string TS_MW timestamp from the DB */
215 /** @var string TS_MW timestamp from cache */
216 protected $mQuickTouched;
220 public $mEmailAuthenticated;
222 protected $mEmailToken;
224 protected $mEmailTokenExpires;
226 protected $mRegistration;
228 protected $mEditCount;
232 protected $mOptionOverrides;
236 * Bool Whether the cache variables have been loaded.
239 public $mOptionsLoaded;
242 * Array with already loaded items or true if all items have been loaded.
244 protected $mLoadedItems = [];
248 * String Initialization data source if mLoadedItems!==true. May be one of:
249 * - 'defaults' anonymous user initialised from class defaults
250 * - 'name' initialise from mName
251 * - 'id' initialise from mId
252 * - 'session' log in from session if possible
254 * Use the User::newFrom*() family of functions to set this.
259 * Lazy-initialized variables, invalidated with clearInstanceCache
263 protected $mDatePreference;
271 protected $mBlockreason;
273 protected $mEffectiveGroups;
275 protected $mImplicitGroups;
277 protected $mFormerGroups;
279 protected $mGlobalBlock;
296 protected $mAllowUsertalk;
299 private $mBlockedFromCreateAccount = false;
301 /** @var integer User::READ_* constant bitfield used to load data */
302 protected $queryFlagsUsed = self
::READ_NORMAL
;
304 public static $idCacheByName = [];
307 * Lightweight constructor for an anonymous user.
308 * Use the User::newFrom* factory functions for other kinds of users.
312 * @see newFromConfirmationCode()
313 * @see newFromSession()
316 public function __construct() {
317 $this->clearInstanceCache( 'defaults' );
323 public function __toString() {
324 return (string)$this->getName();
328 * Test if it's safe to load this User object.
330 * You should typically check this before using $wgUser or
331 * RequestContext::getUser in a method that might be called before the
332 * system has been fully initialized. If the object is unsafe, you should
333 * use an anonymous user:
335 * $user = $wgUser->isSafeToLoad() ? $wgUser : new User;
341 public function isSafeToLoad() {
342 global $wgFullyInitialised;
344 // The user is safe to load if:
345 // * MW_NO_SESSION is undefined AND $wgFullyInitialised is true (safe to use session data)
346 // * mLoadedItems === true (already loaded)
347 // * mFrom !== 'session' (sessions not involved at all)
349 return ( !defined( 'MW_NO_SESSION' ) && $wgFullyInitialised ) ||
350 $this->mLoadedItems
=== true ||
$this->mFrom
!== 'session';
354 * Load the user table data for this object from the source given by mFrom.
356 * @param integer $flags User::READ_* constant bitfield
358 public function load( $flags = self
::READ_NORMAL
) {
359 global $wgFullyInitialised;
361 if ( $this->mLoadedItems
=== true ) {
365 // Set it now to avoid infinite recursion in accessors
366 $oldLoadedItems = $this->mLoadedItems
;
367 $this->mLoadedItems
= true;
368 $this->queryFlagsUsed
= $flags;
370 // If this is called too early, things are likely to break.
371 if ( !$wgFullyInitialised && $this->mFrom
=== 'session' ) {
372 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
373 ->warning( 'User::loadFromSession called before the end of Setup.php', [
374 'exception' => new Exception( 'User::loadFromSession called before the end of Setup.php' ),
376 $this->loadDefaults();
377 $this->mLoadedItems
= $oldLoadedItems;
381 switch ( $this->mFrom
) {
383 $this->loadDefaults();
386 // Make sure this thread sees its own changes
387 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
388 $flags |
= self
::READ_LATEST
;
389 $this->queryFlagsUsed
= $flags;
392 $this->mId
= self
::idFromName( $this->mName
, $flags );
394 // Nonexistent user placeholder object
395 $this->loadDefaults( $this->mName
);
397 $this->loadFromId( $flags );
401 $this->loadFromId( $flags );
404 if ( !$this->loadFromSession() ) {
405 // Loading from session failed. Load defaults.
406 $this->loadDefaults();
408 Hooks
::run( 'UserLoadAfterLoadFromSession', [ $this ] );
411 throw new UnexpectedValueException(
412 "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
417 * Load user table data, given mId has already been set.
418 * @param integer $flags User::READ_* constant bitfield
419 * @return bool False if the ID does not exist, true otherwise
421 public function loadFromId( $flags = self
::READ_NORMAL
) {
422 if ( $this->mId
== 0 ) {
423 // Anonymous users are not in the database (don't need cache)
424 $this->loadDefaults();
428 // Try cache (unless this needs data from the master DB).
429 // NOTE: if this thread called saveSettings(), the cache was cleared.
430 $latest = DBAccessObjectUtils
::hasFlags( $flags, self
::READ_LATEST
);
432 if ( !$this->loadFromDatabase( $flags ) ) {
433 // Can't load from ID
437 $this->loadFromCache();
440 $this->mLoadedItems
= true;
441 $this->queryFlagsUsed
= $flags;
448 * @param string $wikiId
449 * @param integer $userId
451 public static function purge( $wikiId, $userId ) {
452 $cache = ObjectCache
::getMainWANInstance();
453 $key = $cache->makeGlobalKey( 'user', 'id', $wikiId, $userId );
454 $cache->delete( $key );
459 * @param WANObjectCache $cache
462 protected function getCacheKey( WANObjectCache
$cache ) {
463 return $cache->makeGlobalKey( 'user', 'id', wfWikiID(), $this->mId
);
467 * Load user data from shared cache, given mId has already been set.
472 protected function loadFromCache() {
473 $cache = ObjectCache
::getMainWANInstance();
474 $data = $cache->getWithSetCallback(
475 $this->getCacheKey( $cache ),
477 function ( $oldValue, &$ttl, array &$setOpts ) use ( $cache ) {
478 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
479 wfDebug( "User: cache miss for user {$this->mId}\n" );
481 $this->loadFromDatabase( self
::READ_NORMAL
);
483 $this->loadOptions();
486 foreach ( self
::$mCacheVars as $name ) {
487 $data[$name] = $this->$name;
490 $ttl = $cache->adaptiveTTL( wfTimestamp( TS_UNIX
, $this->mTouched
), $ttl );
495 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'version' => self
::VERSION
]
498 // Restore from cache
499 foreach ( self
::$mCacheVars as $name ) {
500 $this->$name = $data[$name];
506 /** @name newFrom*() static factory methods */
510 * Static factory method for creation from username.
512 * This is slightly less efficient than newFromId(), so use newFromId() if
513 * you have both an ID and a name handy.
515 * @param string $name Username, validated by Title::newFromText()
516 * @param string|bool $validate Validate username. Takes the same parameters as
517 * User::getCanonicalName(), except that true is accepted as an alias
518 * for 'valid', for BC.
520 * @return User|bool User object, or false if the username is invalid
521 * (e.g. if it contains illegal characters or is an IP address). If the
522 * username is not present in the database, the result will be a user object
523 * with a name, zero user ID and default settings.
525 public static function newFromName( $name, $validate = 'valid' ) {
526 if ( $validate === true ) {
529 $name = self
::getCanonicalName( $name, $validate );
530 if ( $name === false ) {
533 // Create unloaded user object
537 $u->setItemLoaded( 'name' );
543 * Static factory method for creation from a given user ID.
545 * @param int $id Valid user ID
546 * @return User The corresponding User object
548 public static function newFromId( $id ) {
552 $u->setItemLoaded( 'id' );
557 * Factory method to fetch whichever user has a given email confirmation code.
558 * This code is generated when an account is created or its e-mail address
561 * If the code is invalid or has expired, returns NULL.
563 * @param string $code Confirmation code
564 * @param int $flags User::READ_* bitfield
567 public static function newFromConfirmationCode( $code, $flags = 0 ) {
568 $db = ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
569 ?
wfGetDB( DB_MASTER
)
570 : wfGetDB( DB_REPLICA
);
572 $id = $db->selectField(
576 'user_email_token' => md5( $code ),
577 'user_email_token_expires > ' . $db->addQuotes( $db->timestamp() ),
581 return $id ? User
::newFromId( $id ) : null;
585 * Create a new user object using data from session. If the login
586 * credentials are invalid, the result is an anonymous user.
588 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
591 public static function newFromSession( WebRequest
$request = null ) {
593 $user->mFrom
= 'session';
594 $user->mRequest
= $request;
599 * Create a new user object from a user row.
600 * The row should have the following fields from the user table in it:
601 * - either user_name or user_id to load further data if needed (or both)
603 * - all other fields (email, etc.)
604 * It is useless to provide the remaining fields if either user_id,
605 * user_name and user_real_name are not provided because the whole row
606 * will be loaded once more from the database when accessing them.
608 * @param stdClass $row A row from the user table
609 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
612 public static function newFromRow( $row, $data = null ) {
614 $user->loadFromRow( $row, $data );
619 * Static factory method for creation of a "system" user from username.
621 * A "system" user is an account that's used to attribute logged actions
622 * taken by MediaWiki itself, as opposed to a bot or human user. Examples
623 * might include the 'Maintenance script' or 'Conversion script' accounts
624 * used by various scripts in the maintenance/ directory or accounts such
625 * as 'MediaWiki message delivery' used by the MassMessage extension.
627 * This can optionally create the user if it doesn't exist, and "steal" the
628 * account if it does exist.
630 * "Stealing" an existing user is intended to make it impossible for normal
631 * authentication processes to use the account, effectively disabling the
632 * account for normal use:
633 * - Email is invalidated, to prevent account recovery by emailing a
634 * temporary password and to disassociate the account from the existing
636 * - The token is set to a magic invalid value, to kill existing sessions
637 * and to prevent $this->setToken() calls from resetting the token to a
639 * - SessionManager is instructed to prevent new sessions for the user, to
640 * do things like deauthorizing OAuth consumers.
641 * - AuthManager is instructed to revoke access, to invalidate or remove
642 * passwords and other credentials.
644 * @param string $name Username
645 * @param array $options Options are:
646 * - validate: As for User::getCanonicalName(), default 'valid'
647 * - create: Whether to create the user if it doesn't already exist, default true
648 * - steal: Whether to "disable" the account for normal use if it already
649 * exists, default false
653 public static function newSystemUser( $name, $options = [] ) {
655 'validate' => 'valid',
660 $name = self
::getCanonicalName( $name, $options['validate'] );
661 if ( $name === false ) {
665 $fields = self
::selectFields();
667 $dbw = wfGetDB( DB_MASTER
);
668 $row = $dbw->selectRow(
671 [ 'user_name' => $name ],
675 // No user. Create it?
676 return $options['create'] ? self
::createNew( $name ) : null;
678 $user = self
::newFromRow( $row );
680 // A user is considered to exist as a non-system user if it can
681 // authenticate, or has an email set, or has a non-invalid token.
682 if ( $user->mEmail ||
$user->mToken
!== self
::INVALID_TOKEN ||
683 AuthManager
::singleton()->userCanAuthenticate( $name )
685 // User exists. Steal it?
686 if ( !$options['steal'] ) {
690 AuthManager
::singleton()->revokeAccessForUser( $name );
692 $user->invalidateEmail();
693 $user->mToken
= self
::INVALID_TOKEN
;
694 $user->saveSettings();
695 SessionManager
::singleton()->preventSessionsForUser( $user->getName() );
704 * Get the username corresponding to a given user ID
705 * @param int $id User ID
706 * @return string|bool The corresponding username
708 public static function whoIs( $id ) {
709 return UserCache
::singleton()->getProp( $id, 'name' );
713 * Get the real name of a user given their user ID
715 * @param int $id User ID
716 * @return string|bool The corresponding user's real name
718 public static function whoIsReal( $id ) {
719 return UserCache
::singleton()->getProp( $id, 'real_name' );
723 * Get database id given a user name
724 * @param string $name Username
725 * @param integer $flags User::READ_* constant bitfield
726 * @return int|null The corresponding user's ID, or null if user is nonexistent
728 public static function idFromName( $name, $flags = self
::READ_NORMAL
) {
729 $nt = Title
::makeTitleSafe( NS_USER
, $name );
730 if ( is_null( $nt ) ) {
735 if ( !( $flags & self
::READ_LATEST
) && isset( self
::$idCacheByName[$name] ) ) {
736 return self
::$idCacheByName[$name];
739 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
740 $db = wfGetDB( $index );
745 [ 'user_name' => $nt->getText() ],
750 if ( $s === false ) {
753 $result = $s->user_id
;
756 self
::$idCacheByName[$name] = $result;
758 if ( count( self
::$idCacheByName ) > 1000 ) {
759 self
::$idCacheByName = [];
766 * Reset the cache used in idFromName(). For use in tests.
768 public static function resetIdByNameCache() {
769 self
::$idCacheByName = [];
773 * Does the string match an anonymous IP address?
775 * This function exists for username validation, in order to reject
776 * usernames which are similar in form to IP addresses. Strings such
777 * as 300.300.300.300 will return true because it looks like an IP
778 * address, despite not being strictly valid.
780 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
781 * address because the usemod software would "cloak" anonymous IP
782 * addresses like this, if we allowed accounts like this to be created
783 * new users could get the old edits of these anonymous users.
785 * @param string $name Name to match
788 public static function isIP( $name ) {
789 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
790 || IP
::isIPv6( $name );
794 * Is the input a valid username?
796 * Checks if the input is a valid username, we don't want an empty string,
797 * an IP address, anything that contains slashes (would mess up subpages),
798 * is longer than the maximum allowed username size or doesn't begin with
801 * @param string $name Name to match
804 public static function isValidUserName( $name ) {
805 global $wgContLang, $wgMaxNameChars;
808 || User
::isIP( $name )
809 ||
strpos( $name, '/' ) !== false
810 ||
strlen( $name ) > $wgMaxNameChars
811 ||
$name != $wgContLang->ucfirst( $name )
816 // Ensure that the name can't be misresolved as a different title,
817 // such as with extra namespace keys at the start.
818 $parsed = Title
::newFromText( $name );
819 if ( is_null( $parsed )
820 ||
$parsed->getNamespace()
821 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
825 // Check an additional blacklist of troublemaker characters.
826 // Should these be merged into the title char list?
827 $unicodeBlacklist = '/[' .
828 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
829 '\x{00a0}' . # non-breaking space
830 '\x{2000}-\x{200f}' . # various whitespace
831 '\x{2028}-\x{202f}' . # breaks and control chars
832 '\x{3000}' . # ideographic space
833 '\x{e000}-\x{f8ff}' . # private use
835 if ( preg_match( $unicodeBlacklist, $name ) ) {
843 * Usernames which fail to pass this function will be blocked
844 * from user login and new account registrations, but may be used
845 * internally by batch processes.
847 * If an account already exists in this form, login will be blocked
848 * by a failure to pass this function.
850 * @param string $name Name to match
853 public static function isUsableName( $name ) {
854 global $wgReservedUsernames;
855 // Must be a valid username, obviously ;)
856 if ( !self
::isValidUserName( $name ) ) {
860 static $reservedUsernames = false;
861 if ( !$reservedUsernames ) {
862 $reservedUsernames = $wgReservedUsernames;
863 Hooks
::run( 'UserGetReservedNames', [ &$reservedUsernames ] );
866 // Certain names may be reserved for batch processes.
867 foreach ( $reservedUsernames as $reserved ) {
868 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
869 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
871 if ( $reserved == $name ) {
879 * Return the users who are members of the given group(s). In case of multiple groups,
880 * users who are members of at least one of them are returned.
882 * @param string|array $groups A single group name or an array of group names
883 * @param int $limit Max number of users to return. The actual limit will never exceed 5000
884 * records; larger values are ignored.
885 * @param int $after ID the user to start after
886 * @return UserArrayFromResult
888 public static function findUsersByGroup( $groups, $limit = 5000, $after = null ) {
889 if ( $groups === [] ) {
890 return UserArrayFromResult
::newFromIDs( [] );
893 $groups = array_unique( (array)$groups );
894 $limit = min( 5000, $limit );
896 $conds = [ 'ug_group' => $groups ];
897 if ( $after !== null ) {
898 $conds[] = 'ug_user > ' . (int)$after;
901 $dbr = wfGetDB( DB_REPLICA
);
902 $ids = $dbr->selectFieldValues(
909 'ORDER BY' => 'ug_user',
913 return UserArray
::newFromIDs( $ids );
917 * Usernames which fail to pass this function will be blocked
918 * from new account registrations, but may be used internally
919 * either by batch processes or by user accounts which have
920 * already been created.
922 * Additional blacklisting may be added here rather than in
923 * isValidUserName() to avoid disrupting existing accounts.
925 * @param string $name String to match
928 public static function isCreatableName( $name ) {
929 global $wgInvalidUsernameCharacters;
931 // Ensure that the username isn't longer than 235 bytes, so that
932 // (at least for the builtin skins) user javascript and css files
933 // will work. (bug 23080)
934 if ( strlen( $name ) > 235 ) {
935 wfDebugLog( 'username', __METHOD__
.
936 ": '$name' invalid due to length" );
940 // Preg yells if you try to give it an empty string
941 if ( $wgInvalidUsernameCharacters !== '' ) {
942 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
943 wfDebugLog( 'username', __METHOD__
.
944 ": '$name' invalid due to wgInvalidUsernameCharacters" );
949 return self
::isUsableName( $name );
953 * Is the input a valid password for this user?
955 * @param string $password Desired password
958 public function isValidPassword( $password ) {
959 // simple boolean wrapper for getPasswordValidity
960 return $this->getPasswordValidity( $password ) === true;
964 * Given unvalidated password input, return error message on failure.
966 * @param string $password Desired password
967 * @return bool|string|array True on success, string or array of error message on failure
969 public function getPasswordValidity( $password ) {
970 $result = $this->checkPasswordValidity( $password );
971 if ( $result->isGood() ) {
975 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
976 $messages[] = $error['message'];
978 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
979 $messages[] = $warning['message'];
981 if ( count( $messages ) === 1 ) {
989 * Check if this is a valid password for this user
991 * Create a Status object based on the password's validity.
992 * The Status should be set to fatal if the user should not
993 * be allowed to log in, and should have any errors that
994 * would block changing the password.
996 * If the return value of this is not OK, the password
997 * should not be checked. If the return value is not Good,
998 * the password can be checked, but the user should not be
999 * able to set their password to this.
1001 * @param string $password Desired password
1002 * @param string $purpose one of 'login', 'create', 'reset'
1006 public function checkPasswordValidity( $password, $purpose = 'login' ) {
1007 global $wgPasswordPolicy;
1009 $upp = new UserPasswordPolicy(
1010 $wgPasswordPolicy['policies'],
1011 $wgPasswordPolicy['checks']
1014 $status = Status
::newGood();
1015 $result = false; // init $result to false for the internal checks
1017 if ( !Hooks
::run( 'isValidPassword', [ $password, &$result, $this ] ) ) {
1018 $status->error( $result );
1022 if ( $result === false ) {
1023 $status->merge( $upp->checkUserPassword( $this, $password, $purpose ) );
1025 } elseif ( $result === true ) {
1028 $status->error( $result );
1029 return $status; // the isValidPassword hook set a string $result and returned true
1034 * Given unvalidated user input, return a canonical username, or false if
1035 * the username is invalid.
1036 * @param string $name User input
1037 * @param string|bool $validate Type of validation to use:
1038 * - false No validation
1039 * - 'valid' Valid for batch processes
1040 * - 'usable' Valid for batch processes and login
1041 * - 'creatable' Valid for batch processes, login and account creation
1043 * @throws InvalidArgumentException
1044 * @return bool|string
1046 public static function getCanonicalName( $name, $validate = 'valid' ) {
1047 // Force usernames to capital
1049 $name = $wgContLang->ucfirst( $name );
1051 # Reject names containing '#'; these will be cleaned up
1052 # with title normalisation, but then it's too late to
1054 if ( strpos( $name, '#' ) !== false ) {
1058 // Clean up name according to title rules,
1059 // but only when validation is requested (bug 12654)
1060 $t = ( $validate !== false ) ?
1061 Title
::newFromText( $name, NS_USER
) : Title
::makeTitle( NS_USER
, $name );
1062 // Check for invalid titles
1063 if ( is_null( $t ) ||
$t->getNamespace() !== NS_USER ||
$t->isExternal() ) {
1067 // Reject various classes of invalid names
1068 $name = AuthManager
::callLegacyAuthPlugin(
1069 'getCanonicalName', [ $t->getText() ], $t->getText()
1072 switch ( $validate ) {
1076 if ( !User
::isValidUserName( $name ) ) {
1081 if ( !User
::isUsableName( $name ) ) {
1086 if ( !User
::isCreatableName( $name ) ) {
1091 throw new InvalidArgumentException(
1092 'Invalid parameter value for $validate in ' . __METHOD__
);
1098 * Count the number of edits of a user
1100 * @param int $uid User ID to check
1101 * @return int The user's edit count
1103 * @deprecated since 1.21 in favour of User::getEditCount
1105 public static function edits( $uid ) {
1106 wfDeprecated( __METHOD__
, '1.21' );
1107 $user = self
::newFromId( $uid );
1108 return $user->getEditCount();
1112 * Return a random password.
1114 * @deprecated since 1.27, use PasswordFactory::generateRandomPasswordString()
1115 * @return string New random password
1117 public static function randomPassword() {
1118 global $wgMinimalPasswordLength;
1119 return PasswordFactory
::generateRandomPasswordString( $wgMinimalPasswordLength );
1123 * Set cached properties to default.
1125 * @note This no longer clears uncached lazy-initialised properties;
1126 * the constructor does that instead.
1128 * @param string|bool $name
1130 public function loadDefaults( $name = false ) {
1132 $this->mName
= $name;
1133 $this->mRealName
= '';
1135 $this->mOptionOverrides
= null;
1136 $this->mOptionsLoaded
= false;
1138 $loggedOut = $this->mRequest
&& !defined( 'MW_NO_SESSION' )
1139 ?
$this->mRequest
->getSession()->getLoggedOutTimestamp() : 0;
1140 if ( $loggedOut !== 0 ) {
1141 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1143 $this->mTouched
= '1'; # Allow any pages to be cached
1146 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1147 $this->mEmailAuthenticated
= null;
1148 $this->mEmailToken
= '';
1149 $this->mEmailTokenExpires
= null;
1150 $this->mRegistration
= wfTimestamp( TS_MW
);
1151 $this->mGroups
= [];
1153 Hooks
::run( 'UserLoadDefaults', [ $this, $name ] );
1157 * Return whether an item has been loaded.
1159 * @param string $item Item to check. Current possibilities:
1163 * @param string $all 'all' to check if the whole object has been loaded
1164 * or any other string to check if only the item is available (e.g.
1168 public function isItemLoaded( $item, $all = 'all' ) {
1169 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1170 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1174 * Set that an item has been loaded
1176 * @param string $item
1178 protected function setItemLoaded( $item ) {
1179 if ( is_array( $this->mLoadedItems
) ) {
1180 $this->mLoadedItems
[$item] = true;
1185 * Load user data from the session.
1187 * @return bool True if the user is logged in, false otherwise.
1189 private function loadFromSession() {
1192 Hooks
::run( 'UserLoadFromSession', [ $this, &$result ], '1.27' );
1193 if ( $result !== null ) {
1197 // MediaWiki\Session\Session already did the necessary authentication of the user
1198 // returned here, so just use it if applicable.
1199 $session = $this->getRequest()->getSession();
1200 $user = $session->getUser();
1201 if ( $user->isLoggedIn() ) {
1202 $this->loadFromUserObject( $user );
1204 // If this user is autoblocked, set a cookie to track the Block. This has to be done on
1205 // every session load, because an autoblocked editor might not edit again from the same
1206 // IP address after being blocked.
1207 $config = RequestContext
::getMain()->getConfig();
1208 if ( $config->get( 'CookieSetOnAutoblock' ) === true ) {
1209 $block = $this->getBlock();
1210 $shouldSetCookie = $this->getRequest()->getCookie( 'BlockID' ) === null
1212 && $block->getType() === Block
::TYPE_USER
1213 && $block->isAutoblocking();
1214 if ( $shouldSetCookie ) {
1215 wfDebug( __METHOD__
. ': User is autoblocked, setting cookie to track' );
1216 $block->setCookie( $this->getRequest()->response() );
1220 // Other code expects these to be set in the session, so set them.
1221 $session->set( 'wsUserID', $this->getId() );
1222 $session->set( 'wsUserName', $this->getName() );
1223 $session->set( 'wsToken', $this->getToken() );
1230 * Load user and user_group data from the database.
1231 * $this->mId must be set, this is how the user is identified.
1233 * @param integer $flags User::READ_* constant bitfield
1234 * @return bool True if the user exists, false if the user is anonymous
1236 public function loadFromDatabase( $flags = self
::READ_LATEST
) {
1238 $this->mId
= intval( $this->mId
);
1240 if ( !$this->mId
) {
1241 // Anonymous users are not in the database
1242 $this->loadDefaults();
1246 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
1247 $db = wfGetDB( $index );
1249 $s = $db->selectRow(
1251 self
::selectFields(),
1252 [ 'user_id' => $this->mId
],
1257 $this->queryFlagsUsed
= $flags;
1258 Hooks
::run( 'UserLoadFromDatabase', [ $this, &$s ] );
1260 if ( $s !== false ) {
1261 // Initialise user table data
1262 $this->loadFromRow( $s );
1263 $this->mGroups
= null; // deferred
1264 $this->getEditCount(); // revalidation for nulls
1269 $this->loadDefaults();
1275 * Initialize this object from a row from the user table.
1277 * @param stdClass $row Row from the user table to load.
1278 * @param array $data Further user data to load into the object
1280 * user_groups Array with groups out of the user_groups table
1281 * user_properties Array with properties out of the user_properties table
1283 protected function loadFromRow( $row, $data = null ) {
1286 $this->mGroups
= null; // deferred
1288 if ( isset( $row->user_name
) ) {
1289 $this->mName
= $row->user_name
;
1290 $this->mFrom
= 'name';
1291 $this->setItemLoaded( 'name' );
1296 if ( isset( $row->user_real_name
) ) {
1297 $this->mRealName
= $row->user_real_name
;
1298 $this->setItemLoaded( 'realname' );
1303 if ( isset( $row->user_id
) ) {
1304 $this->mId
= intval( $row->user_id
);
1305 $this->mFrom
= 'id';
1306 $this->setItemLoaded( 'id' );
1311 if ( isset( $row->user_id
) && isset( $row->user_name
) ) {
1312 self
::$idCacheByName[$row->user_name
] = $row->user_id
;
1315 if ( isset( $row->user_editcount
) ) {
1316 $this->mEditCount
= $row->user_editcount
;
1321 if ( isset( $row->user_touched
) ) {
1322 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1327 if ( isset( $row->user_token
) ) {
1328 // The definition for the column is binary(32), so trim the NULs
1329 // that appends. The previous definition was char(32), so trim
1331 $this->mToken
= rtrim( $row->user_token
, " \0" );
1332 if ( $this->mToken
=== '' ) {
1333 $this->mToken
= null;
1339 if ( isset( $row->user_email
) ) {
1340 $this->mEmail
= $row->user_email
;
1341 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1342 $this->mEmailToken
= $row->user_email_token
;
1343 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1344 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1350 $this->mLoadedItems
= true;
1353 if ( is_array( $data ) ) {
1354 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1355 $this->mGroups
= $data['user_groups'];
1357 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1358 $this->loadOptions( $data['user_properties'] );
1364 * Load the data for this user object from another user object.
1368 protected function loadFromUserObject( $user ) {
1370 foreach ( self
::$mCacheVars as $var ) {
1371 $this->$var = $user->$var;
1376 * Load the groups from the database if they aren't already loaded.
1378 private function loadGroups() {
1379 if ( is_null( $this->mGroups
) ) {
1380 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
1381 ?
wfGetDB( DB_MASTER
)
1382 : wfGetDB( DB_REPLICA
);
1383 $res = $db->select( 'user_groups',
1385 [ 'ug_user' => $this->mId
],
1387 $this->mGroups
= [];
1388 foreach ( $res as $row ) {
1389 $this->mGroups
[] = $row->ug_group
;
1395 * Add the user to the group if he/she meets given criteria.
1397 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1398 * possible to remove manually via Special:UserRights. In such case it
1399 * will not be re-added automatically. The user will also not lose the
1400 * group if they no longer meet the criteria.
1402 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1404 * @return array Array of groups the user has been promoted to.
1406 * @see $wgAutopromoteOnce
1408 public function addAutopromoteOnceGroups( $event ) {
1409 global $wgAutopromoteOnceLogInRC;
1411 if ( wfReadOnly() ||
!$this->getId() ) {
1415 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1416 if ( !count( $toPromote ) ) {
1420 if ( !$this->checkAndSetTouched() ) {
1421 return []; // raced out (bug T48834)
1424 $oldGroups = $this->getGroups(); // previous groups
1425 foreach ( $toPromote as $group ) {
1426 $this->addGroup( $group );
1428 // update groups in external authentication database
1429 Hooks
::run( 'UserGroupsChanged', [ $this, $toPromote, [], false, false ] );
1430 AuthManager
::callLegacyAuthPlugin( 'updateExternalDBGroups', [ $this, $toPromote ] );
1432 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1434 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1435 $logEntry->setPerformer( $this );
1436 $logEntry->setTarget( $this->getUserPage() );
1437 $logEntry->setParameters( [
1438 '4::oldgroups' => $oldGroups,
1439 '5::newgroups' => $newGroups,
1441 $logid = $logEntry->insert();
1442 if ( $wgAutopromoteOnceLogInRC ) {
1443 $logEntry->publish( $logid );
1450 * Builds update conditions. Additional conditions may be added to $conditions to
1451 * protected against race conditions using a compare-and-set (CAS) mechanism
1452 * based on comparing $this->mTouched with the user_touched field.
1454 * @param Database $db
1455 * @param array $conditions WHERE conditions for use with Database::update
1456 * @return array WHERE conditions for use with Database::update
1458 protected function makeUpdateConditions( Database
$db, array $conditions ) {
1459 if ( $this->mTouched
) {
1460 // CAS check: only update if the row wasn't changed sicne it was loaded.
1461 $conditions['user_touched'] = $db->timestamp( $this->mTouched
);
1468 * Bump user_touched if it didn't change since this object was loaded
1470 * On success, the mTouched field is updated.
1471 * The user serialization cache is always cleared.
1473 * @return bool Whether user_touched was actually updated
1476 protected function checkAndSetTouched() {
1479 if ( !$this->mId
) {
1480 return false; // anon
1483 // Get a new user_touched that is higher than the old one
1484 $newTouched = $this->newTouchedTimestamp();
1486 $dbw = wfGetDB( DB_MASTER
);
1487 $dbw->update( 'user',
1488 [ 'user_touched' => $dbw->timestamp( $newTouched ) ],
1489 $this->makeUpdateConditions( $dbw, [
1490 'user_id' => $this->mId
,
1494 $success = ( $dbw->affectedRows() > 0 );
1497 $this->mTouched
= $newTouched;
1498 $this->clearSharedCache();
1500 // Clears on failure too since that is desired if the cache is stale
1501 $this->clearSharedCache( 'refresh' );
1508 * Clear various cached data stored in this object. The cache of the user table
1509 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1511 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1512 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1514 public function clearInstanceCache( $reloadFrom = false ) {
1515 $this->mNewtalk
= -1;
1516 $this->mDatePreference
= null;
1517 $this->mBlockedby
= -1; # Unset
1518 $this->mHash
= false;
1519 $this->mRights
= null;
1520 $this->mEffectiveGroups
= null;
1521 $this->mImplicitGroups
= null;
1522 $this->mGroups
= null;
1523 $this->mOptions
= null;
1524 $this->mOptionsLoaded
= false;
1525 $this->mEditCount
= null;
1527 if ( $reloadFrom ) {
1528 $this->mLoadedItems
= [];
1529 $this->mFrom
= $reloadFrom;
1534 * Combine the language default options with any site-specific options
1535 * and add the default language variants.
1537 * @return array Array of String options
1539 public static function getDefaultOptions() {
1540 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1542 static $defOpt = null;
1543 static $defOptLang = null;
1545 if ( $defOpt !== null && $defOptLang === $wgContLang->getCode() ) {
1546 // $wgContLang does not change (and should not change) mid-request,
1547 // but the unit tests change it anyway, and expect this method to
1548 // return values relevant to the current $wgContLang.
1552 $defOpt = $wgDefaultUserOptions;
1553 // Default language setting
1554 $defOptLang = $wgContLang->getCode();
1555 $defOpt['language'] = $defOptLang;
1556 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1557 $defOpt[$langCode == $wgContLang->getCode() ?
'variant' : "variant-$langCode"] = $langCode;
1560 // NOTE: don't use SearchEngineConfig::getSearchableNamespaces here,
1561 // since extensions may change the set of searchable namespaces depending
1562 // on user groups/permissions.
1563 foreach ( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
1564 $defOpt['searchNs' . $nsnum] = (boolean
)$val;
1566 $defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1568 Hooks
::run( 'UserGetDefaultOptions', [ &$defOpt ] );
1574 * Get a given default option value.
1576 * @param string $opt Name of option to retrieve
1577 * @return string Default option value
1579 public static function getDefaultOption( $opt ) {
1580 $defOpts = self
::getDefaultOptions();
1581 if ( isset( $defOpts[$opt] ) ) {
1582 return $defOpts[$opt];
1589 * Get blocking information
1590 * @param bool $bFromSlave Whether to check the replica DB first.
1591 * To improve performance, non-critical checks are done against replica DBs.
1592 * Check when actually saving should be done against master.
1594 private function getBlockedStatus( $bFromSlave = true ) {
1595 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1597 if ( -1 != $this->mBlockedby
) {
1601 wfDebug( __METHOD__
. ": checking...\n" );
1603 // Initialize data...
1604 // Otherwise something ends up stomping on $this->mBlockedby when
1605 // things get lazy-loaded later, causing false positive block hits
1606 // due to -1 !== 0. Probably session-related... Nothing should be
1607 // overwriting mBlockedby, surely?
1610 # We only need to worry about passing the IP address to the Block generator if the
1611 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1612 # know which IP address they're actually coming from
1614 if ( !$this->isAllowed( 'ipblock-exempt' ) ) {
1615 // $wgUser->getName() only works after the end of Setup.php. Until
1616 // then, assume it's a logged-out user.
1617 $globalUserName = $wgUser->isSafeToLoad()
1618 ?
$wgUser->getName()
1619 : IP
::sanitizeIP( $wgUser->getRequest()->getIP() );
1620 if ( $this->getName() === $globalUserName ) {
1621 $ip = $this->getRequest()->getIP();
1626 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1628 // If no block has been found, check for a cookie indicating that the user is blocked.
1629 $blockCookieVal = (int)$this->getRequest()->getCookie( 'BlockID' );
1630 if ( !$block instanceof Block
&& $blockCookieVal > 0 ) {
1631 // Load the Block from the ID in the cookie.
1632 $tmpBlock = Block
::newFromID( $blockCookieVal );
1633 if ( $tmpBlock instanceof Block
) {
1634 // Check the validity of the block.
1635 $blockIsValid = $tmpBlock->getType() == Block
::TYPE_USER
1636 && !$tmpBlock->isExpired()
1637 && $tmpBlock->isAutoblocking();
1638 $config = RequestContext
::getMain()->getConfig();
1639 $useBlockCookie = ( $config->get( 'CookieSetOnAutoblock' ) === true );
1640 if ( $blockIsValid && $useBlockCookie ) {
1644 // If the block is not valid, clear the block cookie (but don't delete it,
1645 // because it needs to be cleared from LocalStorage as well and an empty string
1646 // value is checked for in the mediawiki.user.blockcookie module).
1647 $block->setCookie( $this->getRequest()->response(), true );
1653 if ( !$block instanceof Block
&& $ip !== null && !in_array( $ip, $wgProxyWhitelist ) ) {
1655 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1657 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1658 $block->mReason
= wfMessage( 'proxyblockreason' )->text();
1659 $block->setTarget( $ip );
1660 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1662 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1663 $block->mReason
= wfMessage( 'sorbsreason' )->text();
1664 $block->setTarget( $ip );
1668 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1669 if ( !$block instanceof Block
1670 && $wgApplyIpBlocksToXff
1672 && !in_array( $ip, $wgProxyWhitelist )
1674 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1675 $xff = array_map( 'trim', explode( ',', $xff ) );
1676 $xff = array_diff( $xff, [ $ip ] );
1677 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1678 $block = Block
::chooseBlock( $xffblocks, $xff );
1679 if ( $block instanceof Block
) {
1680 # Mangle the reason to alert the user that the block
1681 # originated from matching the X-Forwarded-For header.
1682 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->text();
1686 if ( $block instanceof Block
) {
1687 wfDebug( __METHOD__
. ": Found block.\n" );
1688 $this->mBlock
= $block;
1689 $this->mBlockedby
= $block->getByName();
1690 $this->mBlockreason
= $block->mReason
;
1691 $this->mHideName
= $block->mHideName
;
1692 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1694 $this->mBlockedby
= '';
1695 $this->mHideName
= 0;
1696 $this->mAllowUsertalk
= false;
1700 Hooks
::run( 'GetBlockedStatus', [ &$this ] );
1704 * Whether the given IP is in a DNS blacklist.
1706 * @param string $ip IP to check
1707 * @param bool $checkWhitelist Whether to check the whitelist first
1708 * @return bool True if blacklisted.
1710 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1711 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1713 if ( !$wgEnableDnsBlacklist ) {
1717 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1721 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1725 * Whether the given IP is in a given DNS blacklist.
1727 * @param string $ip IP to check
1728 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1729 * @return bool True if blacklisted.
1731 public function inDnsBlacklist( $ip, $bases ) {
1733 // @todo FIXME: IPv6 ??? (https://bugs.php.net/bug.php?id=33170)
1734 if ( IP
::isIPv4( $ip ) ) {
1735 // Reverse IP, bug 21255
1736 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1738 foreach ( (array)$bases as $base ) {
1740 // If we have an access key, use that too (ProjectHoneypot, etc.)
1742 if ( is_array( $base ) ) {
1743 if ( count( $base ) >= 2 ) {
1744 // Access key is 1, base URL is 0
1745 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1747 $host = "$ipReversed.{$base[0]}";
1749 $basename = $base[0];
1751 $host = "$ipReversed.$base";
1755 $ipList = gethostbynamel( $host );
1758 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
1762 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
1771 * Check if an IP address is in the local proxy list
1777 public static function isLocallyBlockedProxy( $ip ) {
1778 global $wgProxyList;
1780 if ( !$wgProxyList ) {
1784 if ( !is_array( $wgProxyList ) ) {
1785 // Load from the specified file
1786 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1789 if ( !is_array( $wgProxyList ) ) {
1791 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1793 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1794 // Old-style flipped proxy list
1803 * Is this user subject to rate limiting?
1805 * @return bool True if rate limited
1807 public function isPingLimitable() {
1808 global $wgRateLimitsExcludedIPs;
1809 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1810 // No other good way currently to disable rate limits
1811 // for specific IPs. :P
1812 // But this is a crappy hack and should die.
1815 return !$this->isAllowed( 'noratelimit' );
1819 * Primitive rate limits: enforce maximum actions per time period
1820 * to put a brake on flooding.
1822 * The method generates both a generic profiling point and a per action one
1823 * (suffix being "-$action".
1825 * @note When using a shared cache like memcached, IP-address
1826 * last-hit counters will be shared across wikis.
1828 * @param string $action Action to enforce; 'edit' if unspecified
1829 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1830 * @return bool True if a rate limiter was tripped
1832 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1833 // Call the 'PingLimiter' hook
1835 if ( !Hooks
::run( 'PingLimiter', [ &$this, $action, &$result, $incrBy ] ) ) {
1839 global $wgRateLimits;
1840 if ( !isset( $wgRateLimits[$action] ) ) {
1844 $limits = array_merge(
1845 [ '&can-bypass' => true ],
1846 $wgRateLimits[$action]
1849 // Some groups shouldn't trigger the ping limiter, ever
1850 if ( $limits['&can-bypass'] && !$this->isPingLimitable() ) {
1855 $id = $this->getId();
1857 $isNewbie = $this->isNewbie();
1861 if ( isset( $limits['anon'] ) ) {
1862 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1865 // limits for logged-in users
1866 if ( isset( $limits['user'] ) ) {
1867 $userLimit = $limits['user'];
1869 // limits for newbie logged-in users
1870 if ( $isNewbie && isset( $limits['newbie'] ) ) {
1871 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1875 // limits for anons and for newbie logged-in users
1878 if ( isset( $limits['ip'] ) ) {
1879 $ip = $this->getRequest()->getIP();
1880 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1882 // subnet-based limits
1883 if ( isset( $limits['subnet'] ) ) {
1884 $ip = $this->getRequest()->getIP();
1885 $subnet = IP
::getSubnet( $ip );
1886 if ( $subnet !== false ) {
1887 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1892 // Check for group-specific permissions
1893 // If more than one group applies, use the group with the highest limit ratio (max/period)
1894 foreach ( $this->getGroups() as $group ) {
1895 if ( isset( $limits[$group] ) ) {
1896 if ( $userLimit === false
1897 ||
$limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1899 $userLimit = $limits[$group];
1904 // Set the user limit key
1905 if ( $userLimit !== false ) {
1906 list( $max, $period ) = $userLimit;
1907 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
1908 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1911 // ip-based limits for all ping-limitable users
1912 if ( isset( $limits['ip-all'] ) ) {
1913 $ip = $this->getRequest()->getIP();
1914 // ignore if user limit is more permissive
1915 if ( $isNewbie ||
$userLimit === false
1916 ||
$limits['ip-all'][0] / $limits['ip-all'][1] > $userLimit[0] / $userLimit[1] ) {
1917 $keys["mediawiki:limiter:$action:ip-all:$ip"] = $limits['ip-all'];
1921 // subnet-based limits for all ping-limitable users
1922 if ( isset( $limits['subnet-all'] ) ) {
1923 $ip = $this->getRequest()->getIP();
1924 $subnet = IP
::getSubnet( $ip );
1925 if ( $subnet !== false ) {
1926 // ignore if user limit is more permissive
1927 if ( $isNewbie ||
$userLimit === false
1928 ||
$limits['ip-all'][0] / $limits['ip-all'][1]
1929 > $userLimit[0] / $userLimit[1] ) {
1930 $keys["mediawiki:limiter:$action:subnet-all:$subnet"] = $limits['subnet-all'];
1935 $cache = ObjectCache
::getLocalClusterInstance();
1938 foreach ( $keys as $key => $limit ) {
1939 list( $max, $period ) = $limit;
1940 $summary = "(limit $max in {$period}s)";
1941 $count = $cache->get( $key );
1944 if ( $count >= $max ) {
1945 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1946 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1949 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1952 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1953 if ( $incrBy > 0 ) {
1954 $cache->add( $key, 0, intval( $period ) ); // first ping
1957 if ( $incrBy > 0 ) {
1958 $cache->incr( $key, $incrBy );
1966 * Check if user is blocked
1968 * @param bool $bFromSlave Whether to check the replica DB instead of
1969 * the master. Hacked from false due to horrible probs on site.
1970 * @return bool True if blocked, false otherwise
1972 public function isBlocked( $bFromSlave = true ) {
1973 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
1977 * Get the block affecting the user, or null if the user is not blocked
1979 * @param bool $bFromSlave Whether to check the replica DB instead of the master
1980 * @return Block|null
1982 public function getBlock( $bFromSlave = true ) {
1983 $this->getBlockedStatus( $bFromSlave );
1984 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
1988 * Check if user is blocked from editing a particular article
1990 * @param Title $title Title to check
1991 * @param bool $bFromSlave Whether to check the replica DB instead of the master
1994 public function isBlockedFrom( $title, $bFromSlave = false ) {
1995 global $wgBlockAllowsUTEdit;
1997 $blocked = $this->isBlocked( $bFromSlave );
1998 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
1999 // If a user's name is suppressed, they cannot make edits anywhere
2000 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName()
2001 && $title->getNamespace() == NS_USER_TALK
) {
2003 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
2006 Hooks
::run( 'UserIsBlockedFrom', [ $this, $title, &$blocked, &$allowUsertalk ] );
2012 * If user is blocked, return the name of the user who placed the block
2013 * @return string Name of blocker
2015 public function blockedBy() {
2016 $this->getBlockedStatus();
2017 return $this->mBlockedby
;
2021 * If user is blocked, return the specified reason for the block
2022 * @return string Blocking reason
2024 public function blockedFor() {
2025 $this->getBlockedStatus();
2026 return $this->mBlockreason
;
2030 * If user is blocked, return the ID for the block
2031 * @return int Block ID
2033 public function getBlockId() {
2034 $this->getBlockedStatus();
2035 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
2039 * Check if user is blocked on all wikis.
2040 * Do not use for actual edit permission checks!
2041 * This is intended for quick UI checks.
2043 * @param string $ip IP address, uses current client if none given
2044 * @return bool True if blocked, false otherwise
2046 public function isBlockedGlobally( $ip = '' ) {
2047 return $this->getGlobalBlock( $ip ) instanceof Block
;
2051 * Check if user is blocked on all wikis.
2052 * Do not use for actual edit permission checks!
2053 * This is intended for quick UI checks.
2055 * @param string $ip IP address, uses current client if none given
2056 * @return Block|null Block object if blocked, null otherwise
2057 * @throws FatalError
2058 * @throws MWException
2060 public function getGlobalBlock( $ip = '' ) {
2061 if ( $this->mGlobalBlock
!== null ) {
2062 return $this->mGlobalBlock ?
: null;
2064 // User is already an IP?
2065 if ( IP
::isIPAddress( $this->getName() ) ) {
2066 $ip = $this->getName();
2068 $ip = $this->getRequest()->getIP();
2072 Hooks
::run( 'UserIsBlockedGlobally', [ &$this, $ip, &$blocked, &$block ] );
2074 if ( $blocked && $block === null ) {
2075 // back-compat: UserIsBlockedGlobally didn't have $block param first
2077 $block->setTarget( $ip );
2080 $this->mGlobalBlock
= $blocked ?
$block : false;
2081 return $this->mGlobalBlock ?
: null;
2085 * Check if user account is locked
2087 * @return bool True if locked, false otherwise
2089 public function isLocked() {
2090 if ( $this->mLocked
!== null ) {
2091 return $this->mLocked
;
2093 $authUser = AuthManager
::callLegacyAuthPlugin( 'getUserInstance', [ &$this ], null );
2094 $this->mLocked
= $authUser && $authUser->isLocked();
2095 Hooks
::run( 'UserIsLocked', [ $this, &$this->mLocked
] );
2096 return $this->mLocked
;
2100 * Check if user account is hidden
2102 * @return bool True if hidden, false otherwise
2104 public function isHidden() {
2105 if ( $this->mHideName
!== null ) {
2106 return $this->mHideName
;
2108 $this->getBlockedStatus();
2109 if ( !$this->mHideName
) {
2110 $authUser = AuthManager
::callLegacyAuthPlugin( 'getUserInstance', [ &$this ], null );
2111 $this->mHideName
= $authUser && $authUser->isHidden();
2112 Hooks
::run( 'UserIsHidden', [ $this, &$this->mHideName
] );
2114 return $this->mHideName
;
2118 * Get the user's ID.
2119 * @return int The user's ID; 0 if the user is anonymous or nonexistent
2121 public function getId() {
2122 if ( $this->mId
=== null && $this->mName
!== null && User
::isIP( $this->mName
) ) {
2123 // Special case, we know the user is anonymous
2125 } elseif ( !$this->isItemLoaded( 'id' ) ) {
2126 // Don't load if this was initialized from an ID
2130 return (int)$this->mId
;
2134 * Set the user and reload all fields according to a given ID
2135 * @param int $v User ID to reload
2137 public function setId( $v ) {
2139 $this->clearInstanceCache( 'id' );
2143 * Get the user name, or the IP of an anonymous user
2144 * @return string User's name or IP address
2146 public function getName() {
2147 if ( $this->isItemLoaded( 'name', 'only' ) ) {
2148 // Special case optimisation
2149 return $this->mName
;
2152 if ( $this->mName
=== false ) {
2154 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
2156 return $this->mName
;
2161 * Set the user name.
2163 * This does not reload fields from the database according to the given
2164 * name. Rather, it is used to create a temporary "nonexistent user" for
2165 * later addition to the database. It can also be used to set the IP
2166 * address for an anonymous user to something other than the current
2169 * @note User::newFromName() has roughly the same function, when the named user
2171 * @param string $str New user name to set
2173 public function setName( $str ) {
2175 $this->mName
= $str;
2179 * Get the user's name escaped by underscores.
2180 * @return string Username escaped by underscores.
2182 public function getTitleKey() {
2183 return str_replace( ' ', '_', $this->getName() );
2187 * Check if the user has new messages.
2188 * @return bool True if the user has new messages
2190 public function getNewtalk() {
2193 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2194 if ( $this->mNewtalk
=== -1 ) {
2195 $this->mNewtalk
= false; # reset talk page status
2197 // Check memcached separately for anons, who have no
2198 // entire User object stored in there.
2199 if ( !$this->mId
) {
2200 global $wgDisableAnonTalk;
2201 if ( $wgDisableAnonTalk ) {
2202 // Anon newtalk disabled by configuration.
2203 $this->mNewtalk
= false;
2205 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
2208 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2212 return (bool)$this->mNewtalk
;
2216 * Return the data needed to construct links for new talk page message
2217 * alerts. If there are new messages, this will return an associative array
2218 * with the following data:
2219 * wiki: The database name of the wiki
2220 * link: Root-relative link to the user's talk page
2221 * rev: The last talk page revision that the user has seen or null. This
2222 * is useful for building diff links.
2223 * If there are no new messages, it returns an empty array.
2224 * @note This function was designed to accomodate multiple talk pages, but
2225 * currently only returns a single link and revision.
2228 public function getNewMessageLinks() {
2230 if ( !Hooks
::run( 'UserRetrieveNewTalks', [ &$this, &$talks ] ) ) {
2232 } elseif ( !$this->getNewtalk() ) {
2235 $utp = $this->getTalkPage();
2236 $dbr = wfGetDB( DB_REPLICA
);
2237 // Get the "last viewed rev" timestamp from the oldest message notification
2238 $timestamp = $dbr->selectField( 'user_newtalk',
2239 'MIN(user_last_timestamp)',
2240 $this->isAnon() ?
[ 'user_ip' => $this->getName() ] : [ 'user_id' => $this->getId() ],
2242 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2243 return [ [ 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ] ];
2247 * Get the revision ID for the last talk page revision viewed by the talk
2249 * @return int|null Revision ID or null
2251 public function getNewMessageRevisionId() {
2252 $newMessageRevisionId = null;
2253 $newMessageLinks = $this->getNewMessageLinks();
2254 if ( $newMessageLinks ) {
2255 // Note: getNewMessageLinks() never returns more than a single link
2256 // and it is always for the same wiki, but we double-check here in
2257 // case that changes some time in the future.
2258 if ( count( $newMessageLinks ) === 1
2259 && $newMessageLinks[0]['wiki'] === wfWikiID()
2260 && $newMessageLinks[0]['rev']
2262 /** @var Revision $newMessageRevision */
2263 $newMessageRevision = $newMessageLinks[0]['rev'];
2264 $newMessageRevisionId = $newMessageRevision->getId();
2267 return $newMessageRevisionId;
2271 * Internal uncached check for new messages
2274 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2275 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2276 * @return bool True if the user has new messages
2278 protected function checkNewtalk( $field, $id ) {
2279 $dbr = wfGetDB( DB_REPLICA
);
2281 $ok = $dbr->selectField( 'user_newtalk', $field, [ $field => $id ], __METHOD__
);
2283 return $ok !== false;
2287 * Add or update the new messages flag
2288 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2289 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2290 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2291 * @return bool True if successful, false otherwise
2293 protected function updateNewtalk( $field, $id, $curRev = null ) {
2294 // Get timestamp of the talk page revision prior to the current one
2295 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2296 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2297 // Mark the user as having new messages since this revision
2298 $dbw = wfGetDB( DB_MASTER
);
2299 $dbw->insert( 'user_newtalk',
2300 [ $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ],
2303 if ( $dbw->affectedRows() ) {
2304 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2307 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2313 * Clear the new messages flag for the given user
2314 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2315 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2316 * @return bool True if successful, false otherwise
2318 protected function deleteNewtalk( $field, $id ) {
2319 $dbw = wfGetDB( DB_MASTER
);
2320 $dbw->delete( 'user_newtalk',
2323 if ( $dbw->affectedRows() ) {
2324 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2327 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2333 * Update the 'You have new messages!' status.
2334 * @param bool $val Whether the user has new messages
2335 * @param Revision $curRev New, as yet unseen revision of the user talk
2336 * page. Ignored if null or !$val.
2338 public function setNewtalk( $val, $curRev = null ) {
2339 if ( wfReadOnly() ) {
2344 $this->mNewtalk
= $val;
2346 if ( $this->isAnon() ) {
2348 $id = $this->getName();
2351 $id = $this->getId();
2355 $changed = $this->updateNewtalk( $field, $id, $curRev );
2357 $changed = $this->deleteNewtalk( $field, $id );
2361 $this->invalidateCache();
2366 * Generate a current or new-future timestamp to be stored in the
2367 * user_touched field when we update things.
2368 * @return string Timestamp in TS_MW format
2370 private function newTouchedTimestamp() {
2371 global $wgClockSkewFudge;
2373 $time = wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2374 if ( $this->mTouched
&& $time <= $this->mTouched
) {
2375 $time = wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $this->mTouched
) +
1 );
2382 * Clear user data from memcached
2384 * Use after applying updates to the database; caller's
2385 * responsibility to update user_touched if appropriate.
2387 * Called implicitly from invalidateCache() and saveSettings().
2389 * @param string $mode Use 'refresh' to clear now; otherwise before DB commit
2391 public function clearSharedCache( $mode = 'changed' ) {
2392 if ( !$this->getId() ) {
2396 $cache = ObjectCache
::getMainWANInstance();
2397 $key = $this->getCacheKey( $cache );
2398 if ( $mode === 'refresh' ) {
2399 $cache->delete( $key, 1 );
2401 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle(
2402 function() use ( $cache, $key ) {
2403 $cache->delete( $key );
2411 * Immediately touch the user data cache for this account
2413 * Calls touch() and removes account data from memcached
2415 public function invalidateCache() {
2417 $this->clearSharedCache();
2421 * Update the "touched" timestamp for the user
2423 * This is useful on various login/logout events when making sure that
2424 * a browser or proxy that has multiple tenants does not suffer cache
2425 * pollution where the new user sees the old users content. The value
2426 * of getTouched() is checked when determining 304 vs 200 responses.
2427 * Unlike invalidateCache(), this preserves the User object cache and
2428 * avoids database writes.
2432 public function touch() {
2433 $id = $this->getId();
2435 $key = wfMemcKey( 'user-quicktouched', 'id', $id );
2436 ObjectCache
::getMainWANInstance()->touchCheckKey( $key );
2437 $this->mQuickTouched
= null;
2442 * Validate the cache for this account.
2443 * @param string $timestamp A timestamp in TS_MW format
2446 public function validateCache( $timestamp ) {
2447 return ( $timestamp >= $this->getTouched() );
2451 * Get the user touched timestamp
2453 * Use this value only to validate caches via inequalities
2454 * such as in the case of HTTP If-Modified-Since response logic
2456 * @return string TS_MW Timestamp
2458 public function getTouched() {
2462 if ( $this->mQuickTouched
=== null ) {
2463 $key = wfMemcKey( 'user-quicktouched', 'id', $this->mId
);
2464 $cache = ObjectCache
::getMainWANInstance();
2466 $this->mQuickTouched
= wfTimestamp( TS_MW
, $cache->getCheckKeyTime( $key ) );
2469 return max( $this->mTouched
, $this->mQuickTouched
);
2472 return $this->mTouched
;
2476 * Get the user_touched timestamp field (time of last DB updates)
2477 * @return string TS_MW Timestamp
2480 public function getDBTouched() {
2483 return $this->mTouched
;
2487 * @deprecated Removed in 1.27.
2491 public function getPassword() {
2492 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2496 * @deprecated Removed in 1.27.
2500 public function getTemporaryPassword() {
2501 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2505 * Set the password and reset the random token.
2506 * Calls through to authentication plugin if necessary;
2507 * will have no effect if the auth plugin refuses to
2508 * pass the change through or if the legal password
2511 * As a special case, setting the password to null
2512 * wipes it, so the account cannot be logged in until
2513 * a new password is set, for instance via e-mail.
2515 * @deprecated since 1.27, use AuthManager instead
2516 * @param string $str New password to set
2517 * @throws PasswordError On failure
2520 public function setPassword( $str ) {
2521 return $this->setPasswordInternal( $str );
2525 * Set the password and reset the random token unconditionally.
2527 * @deprecated since 1.27, use AuthManager instead
2528 * @param string|null $str New password to set or null to set an invalid
2529 * password hash meaning that the user will not be able to log in
2530 * through the web interface.
2532 public function setInternalPassword( $str ) {
2533 $this->setPasswordInternal( $str );
2537 * Actually set the password and such
2538 * @since 1.27 cannot set a password for a user not in the database
2539 * @param string|null $str New password to set or null to set an invalid
2540 * password hash meaning that the user will not be able to log in
2541 * through the web interface.
2542 * @return bool Success
2544 private function setPasswordInternal( $str ) {
2545 $manager = AuthManager
::singleton();
2547 // If the user doesn't exist yet, fail
2548 if ( !$manager->userExists( $this->getName() ) ) {
2549 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2552 $status = $this->changeAuthenticationData( [
2553 'username' => $this->getName(),
2557 if ( !$status->isGood() ) {
2558 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
2559 ->info( __METHOD__
. ': Password change rejected: '
2560 . $status->getWikiText( null, null, 'en' ) );
2564 $this->setOption( 'watchlisttoken', false );
2565 SessionManager
::singleton()->invalidateSessionsForUser( $this );
2571 * Changes credentials of the user.
2573 * This is a convenience wrapper around AuthManager::changeAuthenticationData.
2574 * Note that this can return a status that isOK() but not isGood() on certain types of failures,
2575 * e.g. when no provider handled the change.
2577 * @param array $data A set of authentication data in fieldname => value format. This is the
2578 * same data you would pass the changeauthenticationdata API - 'username', 'password' etc.
2582 public function changeAuthenticationData( array $data ) {
2583 $manager = AuthManager
::singleton();
2584 $reqs = $manager->getAuthenticationRequests( AuthManager
::ACTION_CHANGE
, $this );
2585 $reqs = AuthenticationRequest
::loadRequestsFromSubmission( $reqs, $data );
2587 $status = Status
::newGood( 'ignored' );
2588 foreach ( $reqs as $req ) {
2589 $status->merge( $manager->allowsAuthenticationDataChange( $req ), true );
2591 if ( $status->getValue() === 'ignored' ) {
2592 $status->warning( 'authenticationdatachange-ignored' );
2595 if ( $status->isGood() ) {
2596 foreach ( $reqs as $req ) {
2597 $manager->changeAuthenticationData( $req );
2604 * Get the user's current token.
2605 * @param bool $forceCreation Force the generation of a new token if the
2606 * user doesn't have one (default=true for backwards compatibility).
2607 * @return string|null Token
2609 public function getToken( $forceCreation = true ) {
2610 global $wgAuthenticationTokenVersion;
2613 if ( !$this->mToken
&& $forceCreation ) {
2617 if ( !$this->mToken
) {
2618 // The user doesn't have a token, return null to indicate that.
2620 } elseif ( $this->mToken
=== self
::INVALID_TOKEN
) {
2621 // We return a random value here so existing token checks are very
2623 return MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2624 } elseif ( $wgAuthenticationTokenVersion === null ) {
2625 // $wgAuthenticationTokenVersion not in use, so return the raw secret
2626 return $this->mToken
;
2628 // $wgAuthenticationTokenVersion in use, so hmac it.
2629 $ret = MWCryptHash
::hmac( $wgAuthenticationTokenVersion, $this->mToken
, false );
2631 // The raw hash can be overly long. Shorten it up.
2632 $len = max( 32, self
::TOKEN_LENGTH
);
2633 if ( strlen( $ret ) < $len ) {
2634 // Should never happen, even md5 is 128 bits
2635 throw new \
UnexpectedValueException( 'Hmac returned less than 128 bits' );
2637 return substr( $ret, -$len );
2642 * Set the random token (used for persistent authentication)
2643 * Called from loadDefaults() among other places.
2645 * @param string|bool $token If specified, set the token to this value
2647 public function setToken( $token = false ) {
2649 if ( $this->mToken
=== self
::INVALID_TOKEN
) {
2650 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
2651 ->debug( __METHOD__
. ": Ignoring attempt to set token for system user \"$this\"" );
2652 } elseif ( !$token ) {
2653 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2655 $this->mToken
= $token;
2660 * Set the password for a password reminder or new account email
2662 * @deprecated Removed in 1.27. Use PasswordReset instead.
2663 * @param string $str New password to set or null to set an invalid
2664 * password hash meaning that the user will not be able to use it
2665 * @param bool $throttle If true, reset the throttle timestamp to the present
2667 public function setNewpassword( $str, $throttle = true ) {
2668 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2672 * Has password reminder email been sent within the last
2673 * $wgPasswordReminderResendTime hours?
2674 * @deprecated Removed in 1.27. See above.
2677 public function isPasswordReminderThrottled() {
2678 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2682 * Get the user's e-mail address
2683 * @return string User's email address
2685 public function getEmail() {
2687 Hooks
::run( 'UserGetEmail', [ $this, &$this->mEmail
] );
2688 return $this->mEmail
;
2692 * Get the timestamp of the user's e-mail authentication
2693 * @return string TS_MW timestamp
2695 public function getEmailAuthenticationTimestamp() {
2697 Hooks
::run( 'UserGetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
2698 return $this->mEmailAuthenticated
;
2702 * Set the user's e-mail address
2703 * @param string $str New e-mail address
2705 public function setEmail( $str ) {
2707 if ( $str == $this->mEmail
) {
2710 $this->invalidateEmail();
2711 $this->mEmail
= $str;
2712 Hooks
::run( 'UserSetEmail', [ $this, &$this->mEmail
] );
2716 * Set the user's e-mail address and a confirmation mail if needed.
2719 * @param string $str New e-mail address
2722 public function setEmailWithConfirmation( $str ) {
2723 global $wgEnableEmail, $wgEmailAuthentication;
2725 if ( !$wgEnableEmail ) {
2726 return Status
::newFatal( 'emaildisabled' );
2729 $oldaddr = $this->getEmail();
2730 if ( $str === $oldaddr ) {
2731 return Status
::newGood( true );
2734 $type = $oldaddr != '' ?
'changed' : 'set';
2735 $notificationResult = null;
2737 if ( $wgEmailAuthentication ) {
2738 // Send the user an email notifying the user of the change in registered
2739 // email address on their previous email address
2740 if ( $type == 'changed' ) {
2741 $change = $str != '' ?
'changed' : 'removed';
2742 $notificationResult = $this->sendMail(
2743 wfMessage( 'notificationemail_subject_' . $change )->text(),
2744 wfMessage( 'notificationemail_body_' . $change,
2745 $this->getRequest()->getIP(),
2752 $this->setEmail( $str );
2754 if ( $str !== '' && $wgEmailAuthentication ) {
2755 // Send a confirmation request to the new address if needed
2756 $result = $this->sendConfirmationMail( $type );
2758 if ( $notificationResult !== null ) {
2759 $result->merge( $notificationResult );
2762 if ( $result->isGood() ) {
2763 // Say to the caller that a confirmation and notification mail has been sent
2764 $result->value
= 'eauth';
2767 $result = Status
::newGood( true );
2774 * Get the user's real name
2775 * @return string User's real name
2777 public function getRealName() {
2778 if ( !$this->isItemLoaded( 'realname' ) ) {
2782 return $this->mRealName
;
2786 * Set the user's real name
2787 * @param string $str New real name
2789 public function setRealName( $str ) {
2791 $this->mRealName
= $str;
2795 * Get the user's current setting for a given option.
2797 * @param string $oname The option to check
2798 * @param string $defaultOverride A default value returned if the option does not exist
2799 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2800 * @return string User's current value for the option
2801 * @see getBoolOption()
2802 * @see getIntOption()
2804 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2805 global $wgHiddenPrefs;
2806 $this->loadOptions();
2808 # We want 'disabled' preferences to always behave as the default value for
2809 # users, even if they have set the option explicitly in their settings (ie they
2810 # set it, and then it was disabled removing their ability to change it). But
2811 # we don't want to erase the preferences in the database in case the preference
2812 # is re-enabled again. So don't touch $mOptions, just override the returned value
2813 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2814 return self
::getDefaultOption( $oname );
2817 if ( array_key_exists( $oname, $this->mOptions
) ) {
2818 return $this->mOptions
[$oname];
2820 return $defaultOverride;
2825 * Get all user's options
2827 * @param int $flags Bitwise combination of:
2828 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2829 * to the default value. (Since 1.25)
2832 public function getOptions( $flags = 0 ) {
2833 global $wgHiddenPrefs;
2834 $this->loadOptions();
2835 $options = $this->mOptions
;
2837 # We want 'disabled' preferences to always behave as the default value for
2838 # users, even if they have set the option explicitly in their settings (ie they
2839 # set it, and then it was disabled removing their ability to change it). But
2840 # we don't want to erase the preferences in the database in case the preference
2841 # is re-enabled again. So don't touch $mOptions, just override the returned value
2842 foreach ( $wgHiddenPrefs as $pref ) {
2843 $default = self
::getDefaultOption( $pref );
2844 if ( $default !== null ) {
2845 $options[$pref] = $default;
2849 if ( $flags & self
::GETOPTIONS_EXCLUDE_DEFAULTS
) {
2850 $options = array_diff_assoc( $options, self
::getDefaultOptions() );
2857 * Get the user's current setting for a given option, as a boolean value.
2859 * @param string $oname The option to check
2860 * @return bool User's current value for the option
2863 public function getBoolOption( $oname ) {
2864 return (bool)$this->getOption( $oname );
2868 * Get the user's current setting for a given option, as an integer value.
2870 * @param string $oname The option to check
2871 * @param int $defaultOverride A default value returned if the option does not exist
2872 * @return int User's current value for the option
2875 public function getIntOption( $oname, $defaultOverride = 0 ) {
2876 $val = $this->getOption( $oname );
2878 $val = $defaultOverride;
2880 return intval( $val );
2884 * Set the given option for a user.
2886 * You need to call saveSettings() to actually write to the database.
2888 * @param string $oname The option to set
2889 * @param mixed $val New value to set
2891 public function setOption( $oname, $val ) {
2892 $this->loadOptions();
2894 // Explicitly NULL values should refer to defaults
2895 if ( is_null( $val ) ) {
2896 $val = self
::getDefaultOption( $oname );
2899 $this->mOptions
[$oname] = $val;
2903 * Get a token stored in the preferences (like the watchlist one),
2904 * resetting it if it's empty (and saving changes).
2906 * @param string $oname The option name to retrieve the token from
2907 * @return string|bool User's current value for the option, or false if this option is disabled.
2908 * @see resetTokenFromOption()
2910 * @deprecated since 1.26 Applications should use the OAuth extension
2912 public function getTokenFromOption( $oname ) {
2913 global $wgHiddenPrefs;
2915 $id = $this->getId();
2916 if ( !$id ||
in_array( $oname, $wgHiddenPrefs ) ) {
2920 $token = $this->getOption( $oname );
2922 // Default to a value based on the user token to avoid space
2923 // wasted on storing tokens for all users. When this option
2924 // is set manually by the user, only then is it stored.
2925 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
2932 * Reset a token stored in the preferences (like the watchlist one).
2933 * *Does not* save user's preferences (similarly to setOption()).
2935 * @param string $oname The option name to reset the token in
2936 * @return string|bool New token value, or false if this option is disabled.
2937 * @see getTokenFromOption()
2940 public function resetTokenFromOption( $oname ) {
2941 global $wgHiddenPrefs;
2942 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2946 $token = MWCryptRand
::generateHex( 40 );
2947 $this->setOption( $oname, $token );
2952 * Return a list of the types of user options currently returned by
2953 * User::getOptionKinds().
2955 * Currently, the option kinds are:
2956 * - 'registered' - preferences which are registered in core MediaWiki or
2957 * by extensions using the UserGetDefaultOptions hook.
2958 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2959 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2960 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2961 * be used by user scripts.
2962 * - 'special' - "preferences" that are not accessible via User::getOptions
2963 * or User::setOptions.
2964 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2965 * These are usually legacy options, removed in newer versions.
2967 * The API (and possibly others) use this function to determine the possible
2968 * option types for validation purposes, so make sure to update this when a
2969 * new option kind is added.
2971 * @see User::getOptionKinds
2972 * @return array Option kinds
2974 public static function listOptionKinds() {
2977 'registered-multiselect',
2978 'registered-checkmatrix',
2986 * Return an associative array mapping preferences keys to the kind of a preference they're
2987 * used for. Different kinds are handled differently when setting or reading preferences.
2989 * See User::listOptionKinds for the list of valid option types that can be provided.
2991 * @see User::listOptionKinds
2992 * @param IContextSource $context
2993 * @param array $options Assoc. array with options keys to check as keys.
2994 * Defaults to $this->mOptions.
2995 * @return array The key => kind mapping data
2997 public function getOptionKinds( IContextSource
$context, $options = null ) {
2998 $this->loadOptions();
2999 if ( $options === null ) {
3000 $options = $this->mOptions
;
3003 $prefs = Preferences
::getPreferences( $this, $context );
3006 // Pull out the "special" options, so they don't get converted as
3007 // multiselect or checkmatrix.
3008 $specialOptions = array_fill_keys( Preferences
::getSaveBlacklist(), true );
3009 foreach ( $specialOptions as $name => $value ) {
3010 unset( $prefs[$name] );
3013 // Multiselect and checkmatrix options are stored in the database with
3014 // one key per option, each having a boolean value. Extract those keys.
3015 $multiselectOptions = [];
3016 foreach ( $prefs as $name => $info ) {
3017 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
3018 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
3019 $opts = HTMLFormField
::flattenOptions( $info['options'] );
3020 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
3022 foreach ( $opts as $value ) {
3023 $multiselectOptions["$prefix$value"] = true;
3026 unset( $prefs[$name] );
3029 $checkmatrixOptions = [];
3030 foreach ( $prefs as $name => $info ) {
3031 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
3032 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
3033 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
3034 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
3035 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
3037 foreach ( $columns as $column ) {
3038 foreach ( $rows as $row ) {
3039 $checkmatrixOptions["$prefix$column-$row"] = true;
3043 unset( $prefs[$name] );
3047 // $value is ignored
3048 foreach ( $options as $key => $value ) {
3049 if ( isset( $prefs[$key] ) ) {
3050 $mapping[$key] = 'registered';
3051 } elseif ( isset( $multiselectOptions[$key] ) ) {
3052 $mapping[$key] = 'registered-multiselect';
3053 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
3054 $mapping[$key] = 'registered-checkmatrix';
3055 } elseif ( isset( $specialOptions[$key] ) ) {
3056 $mapping[$key] = 'special';
3057 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
3058 $mapping[$key] = 'userjs';
3060 $mapping[$key] = 'unused';
3068 * Reset certain (or all) options to the site defaults
3070 * The optional parameter determines which kinds of preferences will be reset.
3071 * Supported values are everything that can be reported by getOptionKinds()
3072 * and 'all', which forces a reset of *all* preferences and overrides everything else.
3074 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
3075 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
3076 * for backwards-compatibility.
3077 * @param IContextSource|null $context Context source used when $resetKinds
3078 * does not contain 'all', passed to getOptionKinds().
3079 * Defaults to RequestContext::getMain() when null.
3081 public function resetOptions(
3082 $resetKinds = [ 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ],
3083 IContextSource
$context = null
3086 $defaultOptions = self
::getDefaultOptions();
3088 if ( !is_array( $resetKinds ) ) {
3089 $resetKinds = [ $resetKinds ];
3092 if ( in_array( 'all', $resetKinds ) ) {
3093 $newOptions = $defaultOptions;
3095 if ( $context === null ) {
3096 $context = RequestContext
::getMain();
3099 $optionKinds = $this->getOptionKinds( $context );
3100 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
3103 // Use default values for the options that should be deleted, and
3104 // copy old values for the ones that shouldn't.
3105 foreach ( $this->mOptions
as $key => $value ) {
3106 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
3107 if ( array_key_exists( $key, $defaultOptions ) ) {
3108 $newOptions[$key] = $defaultOptions[$key];
3111 $newOptions[$key] = $value;
3116 Hooks
::run( 'UserResetAllOptions', [ $this, &$newOptions, $this->mOptions
, $resetKinds ] );
3118 $this->mOptions
= $newOptions;
3119 $this->mOptionsLoaded
= true;
3123 * Get the user's preferred date format.
3124 * @return string User's preferred date format
3126 public function getDatePreference() {
3127 // Important migration for old data rows
3128 if ( is_null( $this->mDatePreference
) ) {
3130 $value = $this->getOption( 'date' );
3131 $map = $wgLang->getDatePreferenceMigrationMap();
3132 if ( isset( $map[$value] ) ) {
3133 $value = $map[$value];
3135 $this->mDatePreference
= $value;
3137 return $this->mDatePreference
;
3141 * Determine based on the wiki configuration and the user's options,
3142 * whether this user must be over HTTPS no matter what.
3146 public function requiresHTTPS() {
3147 global $wgSecureLogin;
3148 if ( !$wgSecureLogin ) {
3151 $https = $this->getBoolOption( 'prefershttps' );
3152 Hooks
::run( 'UserRequiresHTTPS', [ $this, &$https ] );
3154 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
3161 * Get the user preferred stub threshold
3165 public function getStubThreshold() {
3166 global $wgMaxArticleSize; # Maximum article size, in Kb
3167 $threshold = $this->getIntOption( 'stubthreshold' );
3168 if ( $threshold > $wgMaxArticleSize * 1024 ) {
3169 // If they have set an impossible value, disable the preference
3170 // so we can use the parser cache again.
3177 * Get the permissions this user has.
3178 * @return array Array of String permission names
3180 public function getRights() {
3181 if ( is_null( $this->mRights
) ) {
3182 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
3183 Hooks
::run( 'UserGetRights', [ $this, &$this->mRights
] );
3185 // Deny any rights denied by the user's session, unless this
3186 // endpoint has no sessions.
3187 if ( !defined( 'MW_NO_SESSION' ) ) {
3188 $allowedRights = $this->getRequest()->getSession()->getAllowedUserRights();
3189 if ( $allowedRights !== null ) {
3190 $this->mRights
= array_intersect( $this->mRights
, $allowedRights );
3194 // Force reindexation of rights when a hook has unset one of them
3195 $this->mRights
= array_values( array_unique( $this->mRights
) );
3197 // If block disables login, we should also remove any
3198 // extra rights blocked users might have, in case the
3199 // blocked user has a pre-existing session (T129738).
3200 // This is checked here for cases where people only call
3201 // $user->isAllowed(). It is also checked in Title::checkUserBlock()
3202 // to give a better error message in the common case.
3203 $config = RequestContext
::getMain()->getConfig();
3205 $this->isLoggedIn() &&
3206 $config->get( 'BlockDisablesLogin' ) &&
3210 $this->mRights
= array_intersect( $this->mRights
, $anon->getRights() );
3213 return $this->mRights
;
3217 * Get the list of explicit group memberships this user has.
3218 * The implicit * and user groups are not included.
3219 * @return array Array of String internal group names
3221 public function getGroups() {
3223 $this->loadGroups();
3224 return $this->mGroups
;
3228 * Get the list of implicit group memberships this user has.
3229 * This includes all explicit groups, plus 'user' if logged in,
3230 * '*' for all accounts, and autopromoted groups
3231 * @param bool $recache Whether to avoid the cache
3232 * @return array Array of String internal group names
3234 public function getEffectiveGroups( $recache = false ) {
3235 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
3236 $this->mEffectiveGroups
= array_unique( array_merge(
3237 $this->getGroups(), // explicit groups
3238 $this->getAutomaticGroups( $recache ) // implicit groups
3240 // Hook for additional groups
3241 Hooks
::run( 'UserEffectiveGroups', [ &$this, &$this->mEffectiveGroups
] );
3242 // Force reindexation of groups when a hook has unset one of them
3243 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
3245 return $this->mEffectiveGroups
;
3249 * Get the list of implicit group memberships this user has.
3250 * This includes 'user' if logged in, '*' for all accounts,
3251 * and autopromoted groups
3252 * @param bool $recache Whether to avoid the cache
3253 * @return array Array of String internal group names
3255 public function getAutomaticGroups( $recache = false ) {
3256 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
3257 $this->mImplicitGroups
= [ '*' ];
3258 if ( $this->getId() ) {
3259 $this->mImplicitGroups
[] = 'user';
3261 $this->mImplicitGroups
= array_unique( array_merge(
3262 $this->mImplicitGroups
,
3263 Autopromote
::getAutopromoteGroups( $this )
3267 // Assure data consistency with rights/groups,
3268 // as getEffectiveGroups() depends on this function
3269 $this->mEffectiveGroups
= null;
3272 return $this->mImplicitGroups
;
3276 * Returns the groups the user has belonged to.
3278 * The user may still belong to the returned groups. Compare with getGroups().
3280 * The function will not return groups the user had belonged to before MW 1.17
3282 * @return array Names of the groups the user has belonged to.
3284 public function getFormerGroups() {
3287 if ( is_null( $this->mFormerGroups
) ) {
3288 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3289 ?
wfGetDB( DB_MASTER
)
3290 : wfGetDB( DB_REPLICA
);
3291 $res = $db->select( 'user_former_groups',
3293 [ 'ufg_user' => $this->mId
],
3295 $this->mFormerGroups
= [];
3296 foreach ( $res as $row ) {
3297 $this->mFormerGroups
[] = $row->ufg_group
;
3301 return $this->mFormerGroups
;
3305 * Get the user's edit count.
3306 * @return int|null Null for anonymous users
3308 public function getEditCount() {
3309 if ( !$this->getId() ) {
3313 if ( $this->mEditCount
=== null ) {
3314 /* Populate the count, if it has not been populated yet */
3315 $dbr = wfGetDB( DB_REPLICA
);
3316 // check if the user_editcount field has been initialized
3317 $count = $dbr->selectField(
3318 'user', 'user_editcount',
3319 [ 'user_id' => $this->mId
],
3323 if ( $count === null ) {
3324 // it has not been initialized. do so.
3325 $count = $this->initEditCount();
3327 $this->mEditCount
= $count;
3329 return (int)$this->mEditCount
;
3333 * Add the user to the given group.
3334 * This takes immediate effect.
3335 * @param string $group Name of the group to add
3338 public function addGroup( $group ) {
3341 if ( !Hooks
::run( 'UserAddGroup', [ $this, &$group ] ) ) {
3345 $dbw = wfGetDB( DB_MASTER
);
3346 if ( $this->getId() ) {
3347 $dbw->insert( 'user_groups',
3349 'ug_user' => $this->getId(),
3350 'ug_group' => $group,
3356 $this->loadGroups();
3357 $this->mGroups
[] = $group;
3358 // In case loadGroups was not called before, we now have the right twice.
3359 // Get rid of the duplicate.
3360 $this->mGroups
= array_unique( $this->mGroups
);
3362 // Refresh the groups caches, and clear the rights cache so it will be
3363 // refreshed on the next call to $this->getRights().
3364 $this->getEffectiveGroups( true );
3365 $this->mRights
= null;
3367 $this->invalidateCache();
3373 * Remove the user from the given group.
3374 * This takes immediate effect.
3375 * @param string $group Name of the group to remove
3378 public function removeGroup( $group ) {
3380 if ( !Hooks
::run( 'UserRemoveGroup', [ $this, &$group ] ) ) {
3384 $dbw = wfGetDB( DB_MASTER
);
3385 $dbw->delete( 'user_groups',
3387 'ug_user' => $this->getId(),
3388 'ug_group' => $group,
3391 // Remember that the user was in this group
3392 $dbw->insert( 'user_former_groups',
3394 'ufg_user' => $this->getId(),
3395 'ufg_group' => $group,
3401 $this->loadGroups();
3402 $this->mGroups
= array_diff( $this->mGroups
, [ $group ] );
3404 // Refresh the groups caches, and clear the rights cache so it will be
3405 // refreshed on the next call to $this->getRights().
3406 $this->getEffectiveGroups( true );
3407 $this->mRights
= null;
3409 $this->invalidateCache();
3415 * Get whether the user is logged in
3418 public function isLoggedIn() {
3419 return $this->getId() != 0;
3423 * Get whether the user is anonymous
3426 public function isAnon() {
3427 return !$this->isLoggedIn();
3431 * @return bool Whether this user is flagged as being a bot role account
3434 public function isBot() {
3435 if ( in_array( 'bot', $this->getGroups() ) && $this->isAllowed( 'bot' ) ) {
3440 Hooks
::run( "UserIsBot", [ $this, &$isBot ] );
3446 * Check if user is allowed to access a feature / make an action
3448 * @param string ... Permissions to test
3449 * @return bool True if user is allowed to perform *any* of the given actions
3451 public function isAllowedAny() {
3452 $permissions = func_get_args();
3453 foreach ( $permissions as $permission ) {
3454 if ( $this->isAllowed( $permission ) ) {
3463 * @param string ... Permissions to test
3464 * @return bool True if the user is allowed to perform *all* of the given actions
3466 public function isAllowedAll() {
3467 $permissions = func_get_args();
3468 foreach ( $permissions as $permission ) {
3469 if ( !$this->isAllowed( $permission ) ) {
3477 * Internal mechanics of testing a permission
3478 * @param string $action
3481 public function isAllowed( $action = '' ) {
3482 if ( $action === '' ) {
3483 return true; // In the spirit of DWIM
3485 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3486 // by misconfiguration: 0 == 'foo'
3487 return in_array( $action, $this->getRights(), true );
3491 * Check whether to enable recent changes patrol features for this user
3492 * @return bool True or false
3494 public function useRCPatrol() {
3495 global $wgUseRCPatrol;
3496 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3500 * Check whether to enable new pages patrol features for this user
3501 * @return bool True or false
3503 public function useNPPatrol() {
3504 global $wgUseRCPatrol, $wgUseNPPatrol;
3506 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3507 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3512 * Check whether to enable new files patrol features for this user
3513 * @return bool True or false
3515 public function useFilePatrol() {
3516 global $wgUseRCPatrol, $wgUseFilePatrol;
3518 ( $wgUseRCPatrol ||
$wgUseFilePatrol )
3519 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3524 * Get the WebRequest object to use with this object
3526 * @return WebRequest
3528 public function getRequest() {
3529 if ( $this->mRequest
) {
3530 return $this->mRequest
;
3538 * Check the watched status of an article.
3539 * @since 1.22 $checkRights parameter added
3540 * @param Title $title Title of the article to look at
3541 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3542 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3545 public function isWatched( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3546 if ( $title->isWatchable() && ( !$checkRights ||
$this->isAllowed( 'viewmywatchlist' ) ) ) {
3547 return MediaWikiServices
::getInstance()->getWatchedItemStore()->isWatched( $this, $title );
3554 * @since 1.22 $checkRights parameter added
3555 * @param Title $title Title of the article to look at
3556 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3557 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3559 public function addWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3560 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3561 MediaWikiServices
::getInstance()->getWatchedItemStore()->addWatchBatchForUser(
3563 [ $title->getSubjectPage(), $title->getTalkPage() ]
3566 $this->invalidateCache();
3570 * Stop watching an article.
3571 * @since 1.22 $checkRights parameter added
3572 * @param Title $title Title of the article to look at
3573 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3574 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3576 public function removeWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3577 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3578 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
3579 $store->removeWatch( $this, $title->getSubjectPage() );
3580 $store->removeWatch( $this, $title->getTalkPage() );
3582 $this->invalidateCache();
3586 * Clear the user's notification timestamp for the given title.
3587 * If e-notif e-mails are on, they will receive notification mails on
3588 * the next change of the page if it's watched etc.
3589 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3590 * @param Title $title Title of the article to look at
3591 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3593 public function clearNotification( &$title, $oldid = 0 ) {
3594 global $wgUseEnotif, $wgShowUpdatedMarker;
3596 // Do nothing if the database is locked to writes
3597 if ( wfReadOnly() ) {
3601 // Do nothing if not allowed to edit the watchlist
3602 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3606 // If we're working on user's talk page, we should update the talk page message indicator
3607 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3608 if ( !Hooks
::run( 'UserClearNewTalkNotification', [ &$this, $oldid ] ) ) {
3612 // Try to update the DB post-send and only if needed...
3613 DeferredUpdates
::addCallableUpdate( function() use ( $title, $oldid ) {
3614 if ( !$this->getNewtalk() ) {
3615 return; // no notifications to clear
3618 // Delete the last notifications (they stack up)
3619 $this->setNewtalk( false );
3621 // If there is a new, unseen, revision, use its timestamp
3623 ?
$title->getNextRevisionID( $oldid, Title
::GAID_FOR_UPDATE
)
3626 $this->setNewtalk( true, Revision
::newFromId( $nextid ) );
3631 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3635 if ( $this->isAnon() ) {
3636 // Nothing else to do...
3640 // Only update the timestamp if the page is being watched.
3641 // The query to find out if it is watched is cached both in memcached and per-invocation,
3642 // and when it does have to be executed, it can be on a replica DB
3643 // If this is the user's newtalk page, we always update the timestamp
3645 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3649 MediaWikiServices
::getInstance()->getWatchedItemStore()
3650 ->resetNotificationTimestamp( $this, $title, $force, $oldid );
3654 * Resets all of the given user's page-change notification timestamps.
3655 * If e-notif e-mails are on, they will receive notification mails on
3656 * the next change of any watched page.
3657 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3659 public function clearAllNotifications() {
3660 global $wgUseEnotif, $wgShowUpdatedMarker;
3661 // Do nothing if not allowed to edit the watchlist
3662 if ( wfReadOnly() ||
!$this->isAllowed( 'editmywatchlist' ) ) {
3666 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3667 $this->setNewtalk( false );
3671 $id = $this->getId();
3676 $dbw = wfGetDB( DB_MASTER
);
3677 $asOfTimes = array_unique( $dbw->selectFieldValues(
3679 'wl_notificationtimestamp',
3680 [ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ],
3682 [ 'ORDER BY' => 'wl_notificationtimestamp DESC', 'LIMIT' => 500 ]
3684 if ( !$asOfTimes ) {
3687 // Immediately update the most recent touched rows, which hopefully covers what
3688 // the user sees on the watchlist page before pressing "mark all pages visited"....
3691 [ 'wl_notificationtimestamp' => null ],
3692 [ 'wl_user' => $id, 'wl_notificationtimestamp' => $asOfTimes ],
3695 // ...and finish the older ones in a post-send update with lag checks...
3696 DeferredUpdates
::addUpdate( new AutoCommitUpdate(
3699 function () use ( $dbw, $id ) {
3700 global $wgUpdateRowsPerQuery;
3702 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
3703 $ticket = $lbFactory->getEmptyTransactionTicket( __METHOD__
);
3704 $asOfTimes = array_unique( $dbw->selectFieldValues(
3706 'wl_notificationtimestamp',
3707 [ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ],
3710 foreach ( array_chunk( $asOfTimes, $wgUpdateRowsPerQuery ) as $asOfTimeBatch ) {
3713 [ 'wl_notificationtimestamp' => null ],
3714 [ 'wl_user' => $id, 'wl_notificationtimestamp' => $asOfTimeBatch ],
3717 $lbFactory->commitAndWaitForReplication( __METHOD__
, $ticket );
3721 // We also need to clear here the "you have new message" notification for the own
3722 // user_talk page; it's cleared one page view later in WikiPage::doViewUpdates().
3726 * Set a cookie on the user's client. Wrapper for
3727 * WebResponse::setCookie
3728 * @deprecated since 1.27
3729 * @param string $name Name of the cookie to set
3730 * @param string $value Value to set
3731 * @param int $exp Expiration time, as a UNIX time value;
3732 * if 0 or not specified, use the default $wgCookieExpiration
3733 * @param bool $secure
3734 * true: Force setting the secure attribute when setting the cookie
3735 * false: Force NOT setting the secure attribute when setting the cookie
3736 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3737 * @param array $params Array of options sent passed to WebResponse::setcookie()
3738 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3741 protected function setCookie(
3742 $name, $value, $exp = 0, $secure = null, $params = [], $request = null
3744 wfDeprecated( __METHOD__
, '1.27' );
3745 if ( $request === null ) {
3746 $request = $this->getRequest();
3748 $params['secure'] = $secure;
3749 $request->response()->setCookie( $name, $value, $exp, $params );
3753 * Clear a cookie on the user's client
3754 * @deprecated since 1.27
3755 * @param string $name Name of the cookie to clear
3756 * @param bool $secure
3757 * true: Force setting the secure attribute when setting the cookie
3758 * false: Force NOT setting the secure attribute when setting the cookie
3759 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3760 * @param array $params Array of options sent passed to WebResponse::setcookie()
3762 protected function clearCookie( $name, $secure = null, $params = [] ) {
3763 wfDeprecated( __METHOD__
, '1.27' );
3764 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3768 * Set an extended login cookie on the user's client. The expiry of the cookie
3769 * is controlled by the $wgExtendedLoginCookieExpiration configuration
3772 * @see User::setCookie
3774 * @deprecated since 1.27
3775 * @param string $name Name of the cookie to set
3776 * @param string $value Value to set
3777 * @param bool $secure
3778 * true: Force setting the secure attribute when setting the cookie
3779 * false: Force NOT setting the secure attribute when setting the cookie
3780 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3782 protected function setExtendedLoginCookie( $name, $value, $secure ) {
3783 global $wgExtendedLoginCookieExpiration, $wgCookieExpiration;
3785 wfDeprecated( __METHOD__
, '1.27' );
3788 $exp +
= $wgExtendedLoginCookieExpiration !== null
3789 ?
$wgExtendedLoginCookieExpiration
3790 : $wgCookieExpiration;
3792 $this->setCookie( $name, $value, $exp, $secure );
3796 * Persist this user's session (e.g. set cookies)
3798 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3800 * @param bool $secure Whether to force secure/insecure cookies or use default
3801 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3803 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3805 if ( 0 == $this->mId
) {
3809 $session = $this->getRequest()->getSession();
3810 if ( $request && $session->getRequest() !== $request ) {
3811 $session = $session->sessionWithRequest( $request );
3813 $delay = $session->delaySave();
3815 if ( !$session->getUser()->equals( $this ) ) {
3816 if ( !$session->canSetUser() ) {
3817 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3818 ->warning( __METHOD__
.
3819 ": Cannot save user \"$this\" to a user \"{$session->getUser()}\"'s immutable session"
3823 $session->setUser( $this );
3826 $session->setRememberUser( $rememberMe );
3827 if ( $secure !== null ) {
3828 $session->setForceHTTPS( $secure );
3831 $session->persist();
3833 ScopedCallback
::consume( $delay );
3837 * Log this user out.
3839 public function logout() {
3840 if ( Hooks
::run( 'UserLogout', [ &$this ] ) ) {
3846 * Clear the user's session, and reset the instance cache.
3849 public function doLogout() {
3850 $session = $this->getRequest()->getSession();
3851 if ( !$session->canSetUser() ) {
3852 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3853 ->warning( __METHOD__
. ": Cannot log out of an immutable session" );
3854 $error = 'immutable';
3855 } elseif ( !$session->getUser()->equals( $this ) ) {
3856 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3857 ->warning( __METHOD__
.
3858 ": Cannot log user \"$this\" out of a user \"{$session->getUser()}\"'s session"
3860 // But we still may as well make this user object anon
3861 $this->clearInstanceCache( 'defaults' );
3862 $error = 'wronguser';
3864 $this->clearInstanceCache( 'defaults' );
3865 $delay = $session->delaySave();
3866 $session->unpersist(); // Clear cookies (T127436)
3867 $session->setLoggedOutTimestamp( time() );
3868 $session->setUser( new User
);
3869 $session->set( 'wsUserID', 0 ); // Other code expects this
3870 $session->resetAllTokens();
3871 ScopedCallback
::consume( $delay );
3874 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authevents' )->info( 'Logout', [
3875 'event' => 'logout',
3876 'successful' => $error === false,
3877 'status' => $error ?
: 'success',
3882 * Save this user's settings into the database.
3883 * @todo Only rarely do all these fields need to be set!
3885 public function saveSettings() {
3886 if ( wfReadOnly() ) {
3887 // @TODO: caller should deal with this instead!
3888 // This should really just be an exception.
3889 MWExceptionHandler
::logException( new DBExpectedError(
3891 "Could not update user with ID '{$this->mId}'; DB is read-only."
3897 if ( 0 == $this->mId
) {
3901 // Get a new user_touched that is higher than the old one.
3902 // This will be used for a CAS check as a last-resort safety
3903 // check against race conditions and replica DB lag.
3904 $newTouched = $this->newTouchedTimestamp();
3906 $dbw = wfGetDB( DB_MASTER
);
3907 $dbw->update( 'user',
3909 'user_name' => $this->mName
,
3910 'user_real_name' => $this->mRealName
,
3911 'user_email' => $this->mEmail
,
3912 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3913 'user_touched' => $dbw->timestamp( $newTouched ),
3914 'user_token' => strval( $this->mToken
),
3915 'user_email_token' => $this->mEmailToken
,
3916 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
3917 ], $this->makeUpdateConditions( $dbw, [ /* WHERE */
3918 'user_id' => $this->mId
,
3922 if ( !$dbw->affectedRows() ) {
3923 // Maybe the problem was a missed cache update; clear it to be safe
3924 $this->clearSharedCache( 'refresh' );
3925 // User was changed in the meantime or loaded with stale data
3926 $from = ( $this->queryFlagsUsed
& self
::READ_LATEST
) ?
'master' : 'replica';
3927 throw new MWException(
3928 "CAS update failed on user_touched for user ID '{$this->mId}' (read from $from);" .
3929 " the version of the user to be saved is older than the current version."
3933 $this->mTouched
= $newTouched;
3934 $this->saveOptions();
3936 Hooks
::run( 'UserSaveSettings', [ $this ] );
3937 $this->clearSharedCache();
3938 $this->getUserPage()->invalidateCache();
3942 * If only this user's username is known, and it exists, return the user ID.
3944 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
3947 public function idForName( $flags = 0 ) {
3948 $s = trim( $this->getName() );
3953 $db = ( ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
)
3954 ?
wfGetDB( DB_MASTER
)
3955 : wfGetDB( DB_REPLICA
);
3957 $options = ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
)
3958 ?
[ 'LOCK IN SHARE MODE' ]
3961 $id = $db->selectField( 'user',
3962 'user_id', [ 'user_name' => $s ], __METHOD__
, $options );
3968 * Add a user to the database, return the user object
3970 * @param string $name Username to add
3971 * @param array $params Array of Strings Non-default parameters to save to
3972 * the database as user_* fields:
3973 * - email: The user's email address.
3974 * - email_authenticated: The email authentication timestamp.
3975 * - real_name: The user's real name.
3976 * - options: An associative array of non-default options.
3977 * - token: Random authentication token. Do not set.
3978 * - registration: Registration timestamp. Do not set.
3980 * @return User|null User object, or null if the username already exists.
3982 public static function createNew( $name, $params = [] ) {
3983 foreach ( [ 'password', 'newpassword', 'newpass_time', 'password_expires' ] as $field ) {
3984 if ( isset( $params[$field] ) ) {
3985 wfDeprecated( __METHOD__
. " with param '$field'", '1.27' );
3986 unset( $params[$field] );
3992 $user->setToken(); // init token
3993 if ( isset( $params['options'] ) ) {
3994 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
3995 unset( $params['options'] );
3997 $dbw = wfGetDB( DB_MASTER
);
3998 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
4000 $noPass = PasswordFactory
::newInvalidPassword()->toString();
4003 'user_id' => $seqVal,
4004 'user_name' => $name,
4005 'user_password' => $noPass,
4006 'user_newpassword' => $noPass,
4007 'user_email' => $user->mEmail
,
4008 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
4009 'user_real_name' => $user->mRealName
,
4010 'user_token' => strval( $user->mToken
),
4011 'user_registration' => $dbw->timestamp( $user->mRegistration
),
4012 'user_editcount' => 0,
4013 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
4015 foreach ( $params as $name => $value ) {
4016 $fields["user_$name"] = $value;
4018 $dbw->insert( 'user', $fields, __METHOD__
, [ 'IGNORE' ] );
4019 if ( $dbw->affectedRows() ) {
4020 $newUser = User
::newFromId( $dbw->insertId() );
4028 * Add this existing user object to the database. If the user already
4029 * exists, a fatal status object is returned, and the user object is
4030 * initialised with the data from the database.
4032 * Previously, this function generated a DB error due to a key conflict
4033 * if the user already existed. Many extension callers use this function
4034 * in code along the lines of:
4036 * $user = User::newFromName( $name );
4037 * if ( !$user->isLoggedIn() ) {
4038 * $user->addToDatabase();
4040 * // do something with $user...
4042 * However, this was vulnerable to a race condition (bug 16020). By
4043 * initialising the user object if the user exists, we aim to support this
4044 * calling sequence as far as possible.
4046 * Note that if the user exists, this function will acquire a write lock,
4047 * so it is still advisable to make the call conditional on isLoggedIn(),
4048 * and to commit the transaction after calling.
4050 * @throws MWException
4053 public function addToDatabase() {
4055 if ( !$this->mToken
) {
4056 $this->setToken(); // init token
4059 $this->mTouched
= $this->newTouchedTimestamp();
4061 $noPass = PasswordFactory
::newInvalidPassword()->toString();
4063 $dbw = wfGetDB( DB_MASTER
);
4064 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
4065 $dbw->insert( 'user',
4067 'user_id' => $seqVal,
4068 'user_name' => $this->mName
,
4069 'user_password' => $noPass,
4070 'user_newpassword' => $noPass,
4071 'user_email' => $this->mEmail
,
4072 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
4073 'user_real_name' => $this->mRealName
,
4074 'user_token' => strval( $this->mToken
),
4075 'user_registration' => $dbw->timestamp( $this->mRegistration
),
4076 'user_editcount' => 0,
4077 'user_touched' => $dbw->timestamp( $this->mTouched
),
4081 if ( !$dbw->affectedRows() ) {
4082 // Use locking reads to bypass any REPEATABLE-READ snapshot.
4083 $this->mId
= $dbw->selectField(
4086 [ 'user_name' => $this->mName
],
4088 [ 'LOCK IN SHARE MODE' ]
4092 if ( $this->loadFromDatabase( self
::READ_LOCKING
) ) {
4097 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
4098 "to insert user '{$this->mName}' row, but it was not present in select!" );
4100 return Status
::newFatal( 'userexists' );
4102 $this->mId
= $dbw->insertId();
4103 self
::$idCacheByName[$this->mName
] = $this->mId
;
4105 // Clear instance cache other than user table data, which is already accurate
4106 $this->clearInstanceCache();
4108 $this->saveOptions();
4109 return Status
::newGood();
4113 * If this user is logged-in and blocked,
4114 * block any IP address they've successfully logged in from.
4115 * @return bool A block was spread
4117 public function spreadAnyEditBlock() {
4118 if ( $this->isLoggedIn() && $this->isBlocked() ) {
4119 return $this->spreadBlock();
4126 * If this (non-anonymous) user is blocked,
4127 * block the IP address they've successfully logged in from.
4128 * @return bool A block was spread
4130 protected function spreadBlock() {
4131 wfDebug( __METHOD__
. "()\n" );
4133 if ( $this->mId
== 0 ) {
4137 $userblock = Block
::newFromTarget( $this->getName() );
4138 if ( !$userblock ) {
4142 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
4146 * Get whether the user is explicitly blocked from account creation.
4147 * @return bool|Block
4149 public function isBlockedFromCreateAccount() {
4150 $this->getBlockedStatus();
4151 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
4152 return $this->mBlock
;
4155 # bug 13611: if the IP address the user is trying to create an account from is
4156 # blocked with createaccount disabled, prevent new account creation there even
4157 # when the user is logged in
4158 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
4159 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
4161 return $this->mBlockedFromCreateAccount
instanceof Block
4162 && $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
4163 ?
$this->mBlockedFromCreateAccount
4168 * Get whether the user is blocked from using Special:Emailuser.
4171 public function isBlockedFromEmailuser() {
4172 $this->getBlockedStatus();
4173 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
4177 * Get whether the user is allowed to create an account.
4180 public function isAllowedToCreateAccount() {
4181 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
4185 * Get this user's personal page title.
4187 * @return Title User's personal page title
4189 public function getUserPage() {
4190 return Title
::makeTitle( NS_USER
, $this->getName() );
4194 * Get this user's talk page title.
4196 * @return Title User's talk page title
4198 public function getTalkPage() {
4199 $title = $this->getUserPage();
4200 return $title->getTalkPage();
4204 * Determine whether the user is a newbie. Newbies are either
4205 * anonymous IPs, or the most recently created accounts.
4208 public function isNewbie() {
4209 return !$this->isAllowed( 'autoconfirmed' );
4213 * Check to see if the given clear-text password is one of the accepted passwords
4214 * @deprecated since 1.27, use AuthManager instead
4215 * @param string $password User password
4216 * @return bool True if the given password is correct, otherwise False
4218 public function checkPassword( $password ) {
4219 $manager = AuthManager
::singleton();
4220 $reqs = AuthenticationRequest
::loadRequestsFromSubmission(
4221 $manager->getAuthenticationRequests( AuthManager
::ACTION_LOGIN
),
4223 'username' => $this->getName(),
4224 'password' => $password,
4227 $res = AuthManager
::singleton()->beginAuthentication( $reqs, 'null:' );
4228 switch ( $res->status
) {
4229 case AuthenticationResponse
::PASS
:
4231 case AuthenticationResponse
::FAIL
:
4232 // Hope it's not a PreAuthenticationProvider that failed...
4233 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
4234 ->info( __METHOD__
. ': Authentication failed: ' . $res->message
->plain() );
4237 throw new BadMethodCallException(
4238 'AuthManager returned a response unsupported by ' . __METHOD__
4244 * Check if the given clear-text password matches the temporary password
4245 * sent by e-mail for password reset operations.
4247 * @deprecated since 1.27, use AuthManager instead
4248 * @param string $plaintext
4249 * @return bool True if matches, false otherwise
4251 public function checkTemporaryPassword( $plaintext ) {
4252 // Can't check the temporary password individually.
4253 return $this->checkPassword( $plaintext );
4257 * Initialize (if necessary) and return a session token value
4258 * which can be used in edit forms to show that the user's
4259 * login credentials aren't being hijacked with a foreign form
4263 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4264 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4265 * @return MediaWiki\Session\Token The new edit token
4267 public function getEditTokenObject( $salt = '', $request = null ) {
4268 if ( $this->isAnon() ) {
4269 return new LoggedOutEditToken();
4273 $request = $this->getRequest();
4275 return $request->getSession()->getToken( $salt );
4279 * Initialize (if necessary) and return a session token value
4280 * which can be used in edit forms to show that the user's
4281 * login credentials aren't being hijacked with a foreign form
4284 * The $salt for 'edit' and 'csrf' tokens is the default (empty string).
4287 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4288 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4289 * @return string The new edit token
4291 public function getEditToken( $salt = '', $request = null ) {
4292 return $this->getEditTokenObject( $salt, $request )->toString();
4296 * Get the embedded timestamp from a token.
4297 * @deprecated since 1.27, use \MediaWiki\Session\Token::getTimestamp instead.
4298 * @param string $val Input token
4301 public static function getEditTokenTimestamp( $val ) {
4302 wfDeprecated( __METHOD__
, '1.27' );
4303 return MediaWiki\Session\Token
::getTimestamp( $val );
4307 * Check given value against the token value stored in the session.
4308 * A match should confirm that the form was submitted from the
4309 * user's own login session, not a form submission from a third-party
4312 * @param string $val Input value to compare
4313 * @param string $salt Optional function-specific data for hashing
4314 * @param WebRequest|null $request Object to use or null to use $wgRequest
4315 * @param int $maxage Fail tokens older than this, in seconds
4316 * @return bool Whether the token matches
4318 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4319 return $this->getEditTokenObject( $salt, $request )->match( $val, $maxage );
4323 * Check given value against the token value stored in the session,
4324 * ignoring the suffix.
4326 * @param string $val Input value to compare
4327 * @param string $salt Optional function-specific data for hashing
4328 * @param WebRequest|null $request Object to use or null to use $wgRequest
4329 * @param int $maxage Fail tokens older than this, in seconds
4330 * @return bool Whether the token matches
4332 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4333 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . Token
::SUFFIX
;
4334 return $this->matchEditToken( $val, $salt, $request, $maxage );
4338 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4339 * mail to the user's given address.
4341 * @param string $type Message to send, either "created", "changed" or "set"
4344 public function sendConfirmationMail( $type = 'created' ) {
4346 $expiration = null; // gets passed-by-ref and defined in next line.
4347 $token = $this->confirmationToken( $expiration );
4348 $url = $this->confirmationTokenUrl( $token );
4349 $invalidateURL = $this->invalidationTokenUrl( $token );
4350 $this->saveSettings();
4352 if ( $type == 'created' ||
$type === false ) {
4353 $message = 'confirmemail_body';
4354 } elseif ( $type === true ) {
4355 $message = 'confirmemail_body_changed';
4357 // Messages: confirmemail_body_changed, confirmemail_body_set
4358 $message = 'confirmemail_body_' . $type;
4361 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4362 wfMessage( $message,
4363 $this->getRequest()->getIP(),
4366 $wgLang->userTimeAndDate( $expiration, $this ),
4368 $wgLang->userDate( $expiration, $this ),
4369 $wgLang->userTime( $expiration, $this ) )->text() );
4373 * Send an e-mail to this user's account. Does not check for
4374 * confirmed status or validity.
4376 * @param string $subject Message subject
4377 * @param string $body Message body
4378 * @param User|null $from Optional sending user; if unspecified, default
4379 * $wgPasswordSender will be used.
4380 * @param string $replyto Reply-To address
4383 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4384 global $wgPasswordSender;
4386 if ( $from instanceof User
) {
4387 $sender = MailAddress
::newFromUser( $from );
4389 $sender = new MailAddress( $wgPasswordSender,
4390 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4392 $to = MailAddress
::newFromUser( $this );
4394 return UserMailer
::send( $to, $sender, $subject, $body, [
4395 'replyTo' => $replyto,
4400 * Generate, store, and return a new e-mail confirmation code.
4401 * A hash (unsalted, since it's used as a key) is stored.
4403 * @note Call saveSettings() after calling this function to commit
4404 * this change to the database.
4406 * @param string &$expiration Accepts the expiration time
4407 * @return string New token
4409 protected function confirmationToken( &$expiration ) {
4410 global $wgUserEmailConfirmationTokenExpiry;
4412 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4413 $expiration = wfTimestamp( TS_MW
, $expires );
4415 $token = MWCryptRand
::generateHex( 32 );
4416 $hash = md5( $token );
4417 $this->mEmailToken
= $hash;
4418 $this->mEmailTokenExpires
= $expiration;
4423 * Return a URL the user can use to confirm their email address.
4424 * @param string $token Accepts the email confirmation token
4425 * @return string New token URL
4427 protected function confirmationTokenUrl( $token ) {
4428 return $this->getTokenUrl( 'ConfirmEmail', $token );
4432 * Return a URL the user can use to invalidate their email address.
4433 * @param string $token Accepts the email confirmation token
4434 * @return string New token URL
4436 protected function invalidationTokenUrl( $token ) {
4437 return $this->getTokenUrl( 'InvalidateEmail', $token );
4441 * Internal function to format the e-mail validation/invalidation URLs.
4442 * This uses a quickie hack to use the
4443 * hardcoded English names of the Special: pages, for ASCII safety.
4445 * @note Since these URLs get dropped directly into emails, using the
4446 * short English names avoids insanely long URL-encoded links, which
4447 * also sometimes can get corrupted in some browsers/mailers
4448 * (bug 6957 with Gmail and Internet Explorer).
4450 * @param string $page Special page
4451 * @param string $token Token
4452 * @return string Formatted URL
4454 protected function getTokenUrl( $page, $token ) {
4455 // Hack to bypass localization of 'Special:'
4456 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4457 return $title->getCanonicalURL();
4461 * Mark the e-mail address confirmed.
4463 * @note Call saveSettings() after calling this function to commit the change.
4467 public function confirmEmail() {
4468 // Check if it's already confirmed, so we don't touch the database
4469 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4470 if ( !$this->isEmailConfirmed() ) {
4471 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4472 Hooks
::run( 'ConfirmEmailComplete', [ $this ] );
4478 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4479 * address if it was already confirmed.
4481 * @note Call saveSettings() after calling this function to commit the change.
4482 * @return bool Returns true
4484 public function invalidateEmail() {
4486 $this->mEmailToken
= null;
4487 $this->mEmailTokenExpires
= null;
4488 $this->setEmailAuthenticationTimestamp( null );
4490 Hooks
::run( 'InvalidateEmailComplete', [ $this ] );
4495 * Set the e-mail authentication timestamp.
4496 * @param string $timestamp TS_MW timestamp
4498 public function setEmailAuthenticationTimestamp( $timestamp ) {
4500 $this->mEmailAuthenticated
= $timestamp;
4501 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
4505 * Is this user allowed to send e-mails within limits of current
4506 * site configuration?
4509 public function canSendEmail() {
4510 global $wgEnableEmail, $wgEnableUserEmail;
4511 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4514 $canSend = $this->isEmailConfirmed();
4515 Hooks
::run( 'UserCanSendEmail', [ &$this, &$canSend ] );
4520 * Is this user allowed to receive e-mails within limits of current
4521 * site configuration?
4524 public function canReceiveEmail() {
4525 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4529 * Is this user's e-mail address valid-looking and confirmed within
4530 * limits of the current site configuration?
4532 * @note If $wgEmailAuthentication is on, this may require the user to have
4533 * confirmed their address by returning a code or using a password
4534 * sent to the address from the wiki.
4538 public function isEmailConfirmed() {
4539 global $wgEmailAuthentication;
4542 if ( Hooks
::run( 'EmailConfirmed', [ &$this, &$confirmed ] ) ) {
4543 if ( $this->isAnon() ) {
4546 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4549 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4559 * Check whether there is an outstanding request for e-mail confirmation.
4562 public function isEmailConfirmationPending() {
4563 global $wgEmailAuthentication;
4564 return $wgEmailAuthentication &&
4565 !$this->isEmailConfirmed() &&
4566 $this->mEmailToken
&&
4567 $this->mEmailTokenExpires
> wfTimestamp();
4571 * Get the timestamp of account creation.
4573 * @return string|bool|null Timestamp of account creation, false for
4574 * non-existent/anonymous user accounts, or null if existing account
4575 * but information is not in database.
4577 public function getRegistration() {
4578 if ( $this->isAnon() ) {
4582 return $this->mRegistration
;
4586 * Get the timestamp of the first edit
4588 * @return string|bool Timestamp of first edit, or false for
4589 * non-existent/anonymous user accounts.
4591 public function getFirstEditTimestamp() {
4592 if ( $this->getId() == 0 ) {
4593 return false; // anons
4595 $dbr = wfGetDB( DB_REPLICA
);
4596 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4597 [ 'rev_user' => $this->getId() ],
4599 [ 'ORDER BY' => 'rev_timestamp ASC' ]
4602 return false; // no edits
4604 return wfTimestamp( TS_MW
, $time );
4608 * Get the permissions associated with a given list of groups
4610 * @param array $groups Array of Strings List of internal group names
4611 * @return array Array of Strings List of permission key names for given groups combined
4613 public static function getGroupPermissions( $groups ) {
4614 global $wgGroupPermissions, $wgRevokePermissions;
4616 // grant every granted permission first
4617 foreach ( $groups as $group ) {
4618 if ( isset( $wgGroupPermissions[$group] ) ) {
4619 $rights = array_merge( $rights,
4620 // array_filter removes empty items
4621 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4624 // now revoke the revoked permissions
4625 foreach ( $groups as $group ) {
4626 if ( isset( $wgRevokePermissions[$group] ) ) {
4627 $rights = array_diff( $rights,
4628 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4631 return array_unique( $rights );
4635 * Get all the groups who have a given permission
4637 * @param string $role Role to check
4638 * @return array Array of Strings List of internal group names with the given permission
4640 public static function getGroupsWithPermission( $role ) {
4641 global $wgGroupPermissions;
4642 $allowedGroups = [];
4643 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4644 if ( self
::groupHasPermission( $group, $role ) ) {
4645 $allowedGroups[] = $group;
4648 return $allowedGroups;
4652 * Check, if the given group has the given permission
4654 * If you're wanting to check whether all users have a permission, use
4655 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4659 * @param string $group Group to check
4660 * @param string $role Role to check
4663 public static function groupHasPermission( $group, $role ) {
4664 global $wgGroupPermissions, $wgRevokePermissions;
4665 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4666 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4670 * Check if all users may be assumed to have the given permission
4672 * We generally assume so if the right is granted to '*' and isn't revoked
4673 * on any group. It doesn't attempt to take grants or other extension
4674 * limitations on rights into account in the general case, though, as that
4675 * would require it to always return false and defeat the purpose.
4676 * Specifically, session-based rights restrictions (such as OAuth or bot
4677 * passwords) are applied based on the current session.
4680 * @param string $right Right to check
4683 public static function isEveryoneAllowed( $right ) {
4684 global $wgGroupPermissions, $wgRevokePermissions;
4687 // Use the cached results, except in unit tests which rely on
4688 // being able change the permission mid-request
4689 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4690 return $cache[$right];
4693 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4694 $cache[$right] = false;
4698 // If it's revoked anywhere, then everyone doesn't have it
4699 foreach ( $wgRevokePermissions as $rights ) {
4700 if ( isset( $rights[$right] ) && $rights[$right] ) {
4701 $cache[$right] = false;
4706 // Remove any rights that aren't allowed to the global-session user,
4707 // unless there are no sessions for this endpoint.
4708 if ( !defined( 'MW_NO_SESSION' ) ) {
4709 $allowedRights = SessionManager
::getGlobalSession()->getAllowedUserRights();
4710 if ( $allowedRights !== null && !in_array( $right, $allowedRights, true ) ) {
4711 $cache[$right] = false;
4716 // Allow extensions to say false
4717 if ( !Hooks
::run( 'UserIsEveryoneAllowed', [ $right ] ) ) {
4718 $cache[$right] = false;
4722 $cache[$right] = true;
4727 * Get the localized descriptive name for a group, if it exists
4729 * @param string $group Internal group name
4730 * @return string Localized descriptive group name
4732 public static function getGroupName( $group ) {
4733 $msg = wfMessage( "group-$group" );
4734 return $msg->isBlank() ?
$group : $msg->text();
4738 * Get the localized descriptive name for a member of a group, if it exists
4740 * @param string $group Internal group name
4741 * @param string $username Username for gender (since 1.19)
4742 * @return string Localized name for group member
4744 public static function getGroupMember( $group, $username = '#' ) {
4745 $msg = wfMessage( "group-$group-member", $username );
4746 return $msg->isBlank() ?
$group : $msg->text();
4750 * Return the set of defined explicit groups.
4751 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4752 * are not included, as they are defined automatically, not in the database.
4753 * @return array Array of internal group names
4755 public static function getAllGroups() {
4756 global $wgGroupPermissions, $wgRevokePermissions;
4758 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4759 self
::getImplicitGroups()
4764 * Get a list of all available permissions.
4765 * @return string[] Array of permission names
4767 public static function getAllRights() {
4768 if ( self
::$mAllRights === false ) {
4769 global $wgAvailableRights;
4770 if ( count( $wgAvailableRights ) ) {
4771 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
4773 self
::$mAllRights = self
::$mCoreRights;
4775 Hooks
::run( 'UserGetAllRights', [ &self
::$mAllRights ] );
4777 return self
::$mAllRights;
4781 * Get a list of implicit groups
4782 * @return array Array of Strings Array of internal group names
4784 public static function getImplicitGroups() {
4785 global $wgImplicitGroups;
4787 $groups = $wgImplicitGroups;
4788 # Deprecated, use $wgImplicitGroups instead
4789 Hooks
::run( 'UserGetImplicitGroups', [ &$groups ], '1.25' );
4795 * Get the title of a page describing a particular group
4797 * @param string $group Internal group name
4798 * @return Title|bool Title of the page if it exists, false otherwise
4800 public static function getGroupPage( $group ) {
4801 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4802 if ( $msg->exists() ) {
4803 $title = Title
::newFromText( $msg->text() );
4804 if ( is_object( $title ) ) {
4812 * Create a link to the group in HTML, if available;
4813 * else return the group name.
4815 * @param string $group Internal name of the group
4816 * @param string $text The text of the link
4817 * @return string HTML link to the group
4819 public static function makeGroupLinkHTML( $group, $text = '' ) {
4820 if ( $text == '' ) {
4821 $text = self
::getGroupName( $group );
4823 $title = self
::getGroupPage( $group );
4825 return Linker
::link( $title, htmlspecialchars( $text ) );
4827 return htmlspecialchars( $text );
4832 * Create a link to the group in Wikitext, if available;
4833 * else return the group name.
4835 * @param string $group Internal name of the group
4836 * @param string $text The text of the link
4837 * @return string Wikilink to the group
4839 public static function makeGroupLinkWiki( $group, $text = '' ) {
4840 if ( $text == '' ) {
4841 $text = self
::getGroupName( $group );
4843 $title = self
::getGroupPage( $group );
4845 $page = $title->getFullText();
4846 return "[[$page|$text]]";
4853 * Returns an array of the groups that a particular group can add/remove.
4855 * @param string $group The group to check for whether it can add/remove
4856 * @return array Array( 'add' => array( addablegroups ),
4857 * 'remove' => array( removablegroups ),
4858 * 'add-self' => array( addablegroups to self),
4859 * 'remove-self' => array( removable groups from self) )
4861 public static function changeableByGroup( $group ) {
4862 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4871 if ( empty( $wgAddGroups[$group] ) ) {
4872 // Don't add anything to $groups
4873 } elseif ( $wgAddGroups[$group] === true ) {
4874 // You get everything
4875 $groups['add'] = self
::getAllGroups();
4876 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4877 $groups['add'] = $wgAddGroups[$group];
4880 // Same thing for remove
4881 if ( empty( $wgRemoveGroups[$group] ) ) {
4883 } elseif ( $wgRemoveGroups[$group] === true ) {
4884 $groups['remove'] = self
::getAllGroups();
4885 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4886 $groups['remove'] = $wgRemoveGroups[$group];
4889 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4890 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4891 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4892 if ( is_int( $key ) ) {
4893 $wgGroupsAddToSelf['user'][] = $value;
4898 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
4899 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4900 if ( is_int( $key ) ) {
4901 $wgGroupsRemoveFromSelf['user'][] = $value;
4906 // Now figure out what groups the user can add to him/herself
4907 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4909 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4910 // No idea WHY this would be used, but it's there
4911 $groups['add-self'] = User
::getAllGroups();
4912 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4913 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4916 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4918 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4919 $groups['remove-self'] = User
::getAllGroups();
4920 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4921 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4928 * Returns an array of groups that this user can add and remove
4929 * @return array Array( 'add' => array( addablegroups ),
4930 * 'remove' => array( removablegroups ),
4931 * 'add-self' => array( addablegroups to self),
4932 * 'remove-self' => array( removable groups from self) )
4934 public function changeableGroups() {
4935 if ( $this->isAllowed( 'userrights' ) ) {
4936 // This group gives the right to modify everything (reverse-
4937 // compatibility with old "userrights lets you change
4939 // Using array_merge to make the groups reindexed
4940 $all = array_merge( User
::getAllGroups() );
4949 // Okay, it's not so simple, we will have to go through the arrays
4956 $addergroups = $this->getEffectiveGroups();
4958 foreach ( $addergroups as $addergroup ) {
4959 $groups = array_merge_recursive(
4960 $groups, $this->changeableByGroup( $addergroup )
4962 $groups['add'] = array_unique( $groups['add'] );
4963 $groups['remove'] = array_unique( $groups['remove'] );
4964 $groups['add-self'] = array_unique( $groups['add-self'] );
4965 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4971 * Deferred version of incEditCountImmediate()
4973 public function incEditCount() {
4974 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle(
4976 $this->incEditCountImmediate();
4983 * Increment the user's edit-count field.
4984 * Will have no effect for anonymous users.
4987 public function incEditCountImmediate() {
4988 if ( $this->isAnon() ) {
4992 $dbw = wfGetDB( DB_MASTER
);
4993 // No rows will be "affected" if user_editcount is NULL
4996 [ 'user_editcount=user_editcount+1' ],
4997 [ 'user_id' => $this->getId(), 'user_editcount IS NOT NULL' ],
5000 // Lazy initialization check...
5001 if ( $dbw->affectedRows() == 0 ) {
5002 // Now here's a goddamn hack...
5003 $dbr = wfGetDB( DB_REPLICA
);
5004 if ( $dbr !== $dbw ) {
5005 // If we actually have a replica DB server, the count is
5006 // at least one behind because the current transaction
5007 // has not been committed and replicated.
5008 $this->mEditCount
= $this->initEditCount( 1 );
5010 // But if DB_REPLICA is selecting the master, then the
5011 // count we just read includes the revision that was
5012 // just added in the working transaction.
5013 $this->mEditCount
= $this->initEditCount();
5016 if ( $this->mEditCount
=== null ) {
5017 $this->getEditCount();
5018 $dbr = wfGetDB( DB_REPLICA
);
5019 $this->mEditCount +
= ( $dbr !== $dbw ) ?
1 : 0;
5021 $this->mEditCount++
;
5024 // Edit count in user cache too
5025 $this->invalidateCache();
5029 * Initialize user_editcount from data out of the revision table
5031 * @param int $add Edits to add to the count from the revision table
5032 * @return int Number of edits
5034 protected function initEditCount( $add = 0 ) {
5035 // Pull from a replica DB to be less cruel to servers
5036 // Accuracy isn't the point anyway here
5037 $dbr = wfGetDB( DB_REPLICA
);
5038 $count = (int)$dbr->selectField(
5041 [ 'rev_user' => $this->getId() ],
5044 $count = $count +
$add;
5046 $dbw = wfGetDB( DB_MASTER
);
5049 [ 'user_editcount' => $count ],
5050 [ 'user_id' => $this->getId() ],
5058 * Get the description of a given right
5060 * @param string $right Right to query
5061 * @return string Localized description of the right
5063 public static function getRightDescription( $right ) {
5064 $key = "right-$right";
5065 $msg = wfMessage( $key );
5066 return $msg->isBlank() ?
$right : $msg->text();
5070 * Make a new-style password hash
5072 * @param string $password Plain-text password
5073 * @param bool|string $salt Optional salt, may be random or the user ID.
5074 * If unspecified or false, will generate one automatically
5075 * @return string Password hash
5076 * @deprecated since 1.24, use Password class
5078 public static function crypt( $password, $salt = false ) {
5079 wfDeprecated( __METHOD__
, '1.24' );
5080 $passwordFactory = new PasswordFactory();
5081 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
5082 $hash = $passwordFactory->newFromPlaintext( $password );
5083 return $hash->toString();
5087 * Compare a password hash with a plain-text password. Requires the user
5088 * ID if there's a chance that the hash is an old-style hash.
5090 * @param string $hash Password hash
5091 * @param string $password Plain-text password to compare
5092 * @param string|bool $userId User ID for old-style password salt
5095 * @deprecated since 1.24, use Password class
5097 public static function comparePasswords( $hash, $password, $userId = false ) {
5098 wfDeprecated( __METHOD__
, '1.24' );
5100 // Check for *really* old password hashes that don't even have a type
5101 // The old hash format was just an md5 hex hash, with no type information
5102 if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) {
5103 global $wgPasswordSalt;
5104 if ( $wgPasswordSalt ) {
5105 $password = ":B:{$userId}:{$hash}";
5107 $password = ":A:{$hash}";
5111 $passwordFactory = new PasswordFactory();
5112 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
5113 $hash = $passwordFactory->newFromCiphertext( $hash );
5114 return $hash->equals( $password );
5118 * Add a newuser log entry for this user.
5119 * Before 1.19 the return value was always true.
5121 * @deprecated since 1.27, AuthManager handles logging
5122 * @param string|bool $action Account creation type.
5123 * - String, one of the following values:
5124 * - 'create' for an anonymous user creating an account for himself.
5125 * This will force the action's performer to be the created user itself,
5126 * no matter the value of $wgUser
5127 * - 'create2' for a logged in user creating an account for someone else
5128 * - 'byemail' when the created user will receive its password by e-mail
5129 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
5130 * - Boolean means whether the account was created by e-mail (deprecated):
5131 * - true will be converted to 'byemail'
5132 * - false will be converted to 'create' if this object is the same as
5133 * $wgUser and to 'create2' otherwise
5134 * @param string $reason User supplied reason
5137 public function addNewUserLogEntry( $action = false, $reason = '' ) {
5138 return true; // disabled
5142 * Add an autocreate newuser log entry for this user
5143 * Used by things like CentralAuth and perhaps other authplugins.
5144 * Consider calling addNewUserLogEntry() directly instead.
5146 * @deprecated since 1.27, AuthManager handles logging
5149 public function addNewUserLogEntryAutoCreate() {
5150 $this->addNewUserLogEntry( 'autocreate' );
5156 * Load the user options either from cache, the database or an array
5158 * @param array $data Rows for the current user out of the user_properties table
5160 protected function loadOptions( $data = null ) {
5165 if ( $this->mOptionsLoaded
) {
5169 $this->mOptions
= self
::getDefaultOptions();
5171 if ( !$this->getId() ) {
5172 // For unlogged-in users, load language/variant options from request.
5173 // There's no need to do it for logged-in users: they can set preferences,
5174 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5175 // so don't override user's choice (especially when the user chooses site default).
5176 $variant = $wgContLang->getDefaultVariant();
5177 $this->mOptions
['variant'] = $variant;
5178 $this->mOptions
['language'] = $variant;
5179 $this->mOptionsLoaded
= true;
5183 // Maybe load from the object
5184 if ( !is_null( $this->mOptionOverrides
) ) {
5185 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5186 foreach ( $this->mOptionOverrides
as $key => $value ) {
5187 $this->mOptions
[$key] = $value;
5190 if ( !is_array( $data ) ) {
5191 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5192 // Load from database
5193 $dbr = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
5194 ?
wfGetDB( DB_MASTER
)
5195 : wfGetDB( DB_REPLICA
);
5197 $res = $dbr->select(
5199 [ 'up_property', 'up_value' ],
5200 [ 'up_user' => $this->getId() ],
5204 $this->mOptionOverrides
= [];
5206 foreach ( $res as $row ) {
5207 $data[$row->up_property
] = $row->up_value
;
5210 foreach ( $data as $property => $value ) {
5211 $this->mOptionOverrides
[$property] = $value;
5212 $this->mOptions
[$property] = $value;
5216 $this->mOptionsLoaded
= true;
5218 Hooks
::run( 'UserLoadOptions', [ $this, &$this->mOptions
] );
5222 * Saves the non-default options for this user, as previously set e.g. via
5223 * setOption(), in the database's "user_properties" (preferences) table.
5224 * Usually used via saveSettings().
5226 protected function saveOptions() {
5227 $this->loadOptions();
5229 // Not using getOptions(), to keep hidden preferences in database
5230 $saveOptions = $this->mOptions
;
5232 // Allow hooks to abort, for instance to save to a global profile.
5233 // Reset options to default state before saving.
5234 if ( !Hooks
::run( 'UserSaveOptions', [ $this, &$saveOptions ] ) ) {
5238 $userId = $this->getId();
5240 $insert_rows = []; // all the new preference rows
5241 foreach ( $saveOptions as $key => $value ) {
5242 // Don't bother storing default values
5243 $defaultOption = self
::getDefaultOption( $key );
5244 if ( ( $defaultOption === null && $value !== false && $value !== null )
5245 ||
$value != $defaultOption
5248 'up_user' => $userId,
5249 'up_property' => $key,
5250 'up_value' => $value,
5255 $dbw = wfGetDB( DB_MASTER
);
5257 $res = $dbw->select( 'user_properties',
5258 [ 'up_property', 'up_value' ], [ 'up_user' => $userId ], __METHOD__
);
5260 // Find prior rows that need to be removed or updated. These rows will
5261 // all be deleted (the latter so that INSERT IGNORE applies the new values).
5263 foreach ( $res as $row ) {
5264 if ( !isset( $saveOptions[$row->up_property
] )
5265 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
5267 $keysDelete[] = $row->up_property
;
5271 if ( count( $keysDelete ) ) {
5272 // Do the DELETE by PRIMARY KEY for prior rows.
5273 // In the past a very large portion of calls to this function are for setting
5274 // 'rememberpassword' for new accounts (a preference that has since been removed).
5275 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5276 // caused gap locks on [max user ID,+infinity) which caused high contention since
5277 // updates would pile up on each other as they are for higher (newer) user IDs.
5278 // It might not be necessary these days, but it shouldn't hurt either.
5279 $dbw->delete( 'user_properties',
5280 [ 'up_user' => $userId, 'up_property' => $keysDelete ], __METHOD__
);
5282 // Insert the new preference rows
5283 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, [ 'IGNORE' ] );
5287 * Lazily instantiate and return a factory object for making passwords
5289 * @deprecated since 1.27, create a PasswordFactory directly instead
5290 * @return PasswordFactory
5292 public static function getPasswordFactory() {
5293 wfDeprecated( __METHOD__
, '1.27' );
5294 $ret = new PasswordFactory();
5295 $ret->init( RequestContext
::getMain()->getConfig() );
5300 * Provide an array of HTML5 attributes to put on an input element
5301 * intended for the user to enter a new password. This may include
5302 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
5304 * Do *not* use this when asking the user to enter his current password!
5305 * Regardless of configuration, users may have invalid passwords for whatever
5306 * reason (e.g., they were set before requirements were tightened up).
5307 * Only use it when asking for a new password, like on account creation or
5310 * Obviously, you still need to do server-side checking.
5312 * NOTE: A combination of bugs in various browsers means that this function
5313 * actually just returns array() unconditionally at the moment. May as
5314 * well keep it around for when the browser bugs get fixed, though.
5316 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
5318 * @deprecated since 1.27
5319 * @return array Array of HTML attributes suitable for feeding to
5320 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
5321 * That will get confused by the boolean attribute syntax used.)
5323 public static function passwordChangeInputAttribs() {
5324 global $wgMinimalPasswordLength;
5326 if ( $wgMinimalPasswordLength == 0 ) {
5330 # Note that the pattern requirement will always be satisfied if the
5331 # input is empty, so we need required in all cases.
5333 # @todo FIXME: Bug 23769: This needs to not claim the password is required
5334 # if e-mail confirmation is being used. Since HTML5 input validation
5335 # is b0rked anyway in some browsers, just return nothing. When it's
5336 # re-enabled, fix this code to not output required for e-mail
5338 # $ret = array( 'required' );
5341 # We can't actually do this right now, because Opera 9.6 will print out
5342 # the entered password visibly in its error message! When other
5343 # browsers add support for this attribute, or Opera fixes its support,
5344 # we can add support with a version check to avoid doing this on Opera
5345 # versions where it will be a problem. Reported to Opera as
5346 # DSK-262266, but they don't have a public bug tracker for us to follow.
5348 if ( $wgMinimalPasswordLength > 1 ) {
5349 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
5350 $ret['title'] = wfMessage( 'passwordtooshort' )
5351 ->numParams( $wgMinimalPasswordLength )->text();
5359 * Return the list of user fields that should be selected to create
5360 * a new user object.
5363 public static function selectFields() {
5371 'user_email_authenticated',
5373 'user_email_token_expires',
5374 'user_registration',
5380 * Factory function for fatal permission-denied errors
5383 * @param string $permission User right required
5386 static function newFatalPermissionDeniedStatus( $permission ) {
5389 $groups = array_map(
5390 [ 'User', 'makeGroupLinkWiki' ],
5391 User
::getGroupsWithPermission( $permission )
5395 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5397 return Status
::newFatal( 'badaccess-group0' );
5402 * Get a new instance of this user that was loaded from the master via a locking read
5404 * Use this instead of the main context User when updating that user. This avoids races
5405 * where that user was loaded from a replica DB or even the master but without proper locks.
5407 * @return User|null Returns null if the user was not found in the DB
5410 public function getInstanceForUpdate() {
5411 if ( !$this->getId() ) {
5412 return null; // anon
5415 $user = self
::newFromId( $this->getId() );
5416 if ( !$user->loadFromId( self
::READ_EXCLUSIVE
) ) {
5424 * Checks if two user objects point to the same user.
5430 public function equals( User
$user ) {
5431 return $this->getName() === $user->getName();