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',
189 'userrights-interwiki',
197 * String Cached results of getAllRights()
199 protected static $mAllRights = false;
201 /** Cache variables */
212 /** @var string TS_MW timestamp from the DB */
214 /** @var string TS_MW timestamp from cache */
215 protected $mQuickTouched;
219 public $mEmailAuthenticated;
221 protected $mEmailToken;
223 protected $mEmailTokenExpires;
225 protected $mRegistration;
227 protected $mEditCount;
231 protected $mOptionOverrides;
235 * Bool Whether the cache variables have been loaded.
238 public $mOptionsLoaded;
241 * Array with already loaded items or true if all items have been loaded.
243 protected $mLoadedItems = [];
247 * String Initialization data source if mLoadedItems!==true. May be one of:
248 * - 'defaults' anonymous user initialised from class defaults
249 * - 'name' initialise from mName
250 * - 'id' initialise from mId
251 * - 'session' log in from session if possible
253 * Use the User::newFrom*() family of functions to set this.
258 * Lazy-initialized variables, invalidated with clearInstanceCache
262 protected $mDatePreference;
270 protected $mBlockreason;
272 protected $mEffectiveGroups;
274 protected $mImplicitGroups;
276 protected $mFormerGroups;
278 protected $mGlobalBlock;
295 protected $mAllowUsertalk;
298 private $mBlockedFromCreateAccount = false;
300 /** @var integer User::READ_* constant bitfield used to load data */
301 protected $queryFlagsUsed = self
::READ_NORMAL
;
303 /** @var string Indicates type of block (used for eventlogging)
304 * Permitted values: 'cookie-block', 'proxy-block', 'openproxy-block', 'xff-block'
306 public $blockTrigger = false;
308 public static $idCacheByName = [];
311 * Lightweight constructor for an anonymous user.
312 * Use the User::newFrom* factory functions for other kinds of users.
316 * @see newFromConfirmationCode()
317 * @see newFromSession()
320 public function __construct() {
321 $this->clearInstanceCache( 'defaults' );
327 public function __toString() {
328 return (string)$this->getName();
332 * Test if it's safe to load this User object.
334 * You should typically check this before using $wgUser or
335 * RequestContext::getUser in a method that might be called before the
336 * system has been fully initialized. If the object is unsafe, you should
337 * use an anonymous user:
339 * $user = $wgUser->isSafeToLoad() ? $wgUser : new User;
345 public function isSafeToLoad() {
346 global $wgFullyInitialised;
348 // The user is safe to load if:
349 // * MW_NO_SESSION is undefined AND $wgFullyInitialised is true (safe to use session data)
350 // * mLoadedItems === true (already loaded)
351 // * mFrom !== 'session' (sessions not involved at all)
353 return ( !defined( 'MW_NO_SESSION' ) && $wgFullyInitialised ) ||
354 $this->mLoadedItems
=== true ||
$this->mFrom
!== 'session';
358 * Load the user table data for this object from the source given by mFrom.
360 * @param integer $flags User::READ_* constant bitfield
362 public function load( $flags = self
::READ_NORMAL
) {
363 global $wgFullyInitialised;
365 if ( $this->mLoadedItems
=== true ) {
369 // Set it now to avoid infinite recursion in accessors
370 $oldLoadedItems = $this->mLoadedItems
;
371 $this->mLoadedItems
= true;
372 $this->queryFlagsUsed
= $flags;
374 // If this is called too early, things are likely to break.
375 if ( !$wgFullyInitialised && $this->mFrom
=== 'session' ) {
376 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
377 ->warning( 'User::loadFromSession called before the end of Setup.php', [
378 'exception' => new Exception( 'User::loadFromSession called before the end of Setup.php' ),
380 $this->loadDefaults();
381 $this->mLoadedItems
= $oldLoadedItems;
385 switch ( $this->mFrom
) {
387 $this->loadDefaults();
390 // Make sure this thread sees its own changes
391 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
392 $flags |
= self
::READ_LATEST
;
393 $this->queryFlagsUsed
= $flags;
396 $this->mId
= self
::idFromName( $this->mName
, $flags );
398 // Nonexistent user placeholder object
399 $this->loadDefaults( $this->mName
);
401 $this->loadFromId( $flags );
405 $this->loadFromId( $flags );
408 if ( !$this->loadFromSession() ) {
409 // Loading from session failed. Load defaults.
410 $this->loadDefaults();
412 Hooks
::run( 'UserLoadAfterLoadFromSession', [ $this ] );
415 throw new UnexpectedValueException(
416 "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
421 * Load user table data, given mId has already been set.
422 * @param integer $flags User::READ_* constant bitfield
423 * @return bool False if the ID does not exist, true otherwise
425 public function loadFromId( $flags = self
::READ_NORMAL
) {
426 if ( $this->mId
== 0 ) {
427 // Anonymous users are not in the database (don't need cache)
428 $this->loadDefaults();
432 // Try cache (unless this needs data from the master DB).
433 // NOTE: if this thread called saveSettings(), the cache was cleared.
434 $latest = DBAccessObjectUtils
::hasFlags( $flags, self
::READ_LATEST
);
436 if ( !$this->loadFromDatabase( $flags ) ) {
437 // Can't load from ID
441 $this->loadFromCache();
444 $this->mLoadedItems
= true;
445 $this->queryFlagsUsed
= $flags;
452 * @param string $wikiId
453 * @param integer $userId
455 public static function purge( $wikiId, $userId ) {
456 $cache = ObjectCache
::getMainWANInstance();
457 $key = $cache->makeGlobalKey( 'user', 'id', $wikiId, $userId );
458 $cache->delete( $key );
463 * @param WANObjectCache $cache
466 protected function getCacheKey( WANObjectCache
$cache ) {
467 return $cache->makeGlobalKey( 'user', 'id', wfWikiID(), $this->mId
);
471 * Load user data from shared cache, given mId has already been set.
476 protected function loadFromCache() {
477 $cache = ObjectCache
::getMainWANInstance();
478 $data = $cache->getWithSetCallback(
479 $this->getCacheKey( $cache ),
481 function ( $oldValue, &$ttl, array &$setOpts ) use ( $cache ) {
482 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
483 wfDebug( "User: cache miss for user {$this->mId}\n" );
485 $this->loadFromDatabase( self
::READ_NORMAL
);
487 $this->loadOptions();
490 foreach ( self
::$mCacheVars as $name ) {
491 $data[$name] = $this->$name;
494 $ttl = $cache->adaptiveTTL( wfTimestamp( TS_UNIX
, $this->mTouched
), $ttl );
499 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'version' => self
::VERSION
]
502 // Restore from cache
503 foreach ( self
::$mCacheVars as $name ) {
504 $this->$name = $data[$name];
510 /** @name newFrom*() static factory methods */
514 * Static factory method for creation from username.
516 * This is slightly less efficient than newFromId(), so use newFromId() if
517 * you have both an ID and a name handy.
519 * @param string $name Username, validated by Title::newFromText()
520 * @param string|bool $validate Validate username. Takes the same parameters as
521 * User::getCanonicalName(), except that true is accepted as an alias
522 * for 'valid', for BC.
524 * @return User|bool User object, or false if the username is invalid
525 * (e.g. if it contains illegal characters or is an IP address). If the
526 * username is not present in the database, the result will be a user object
527 * with a name, zero user ID and default settings.
529 public static function newFromName( $name, $validate = 'valid' ) {
530 if ( $validate === true ) {
533 $name = self
::getCanonicalName( $name, $validate );
534 if ( $name === false ) {
537 // Create unloaded user object
541 $u->setItemLoaded( 'name' );
547 * Static factory method for creation from a given user ID.
549 * @param int $id Valid user ID
550 * @return User The corresponding User object
552 public static function newFromId( $id ) {
556 $u->setItemLoaded( 'id' );
561 * Factory method to fetch whichever user has a given email confirmation code.
562 * This code is generated when an account is created or its e-mail address
565 * If the code is invalid or has expired, returns NULL.
567 * @param string $code Confirmation code
568 * @param int $flags User::READ_* bitfield
571 public static function newFromConfirmationCode( $code, $flags = 0 ) {
572 $db = ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
573 ?
wfGetDB( DB_MASTER
)
574 : wfGetDB( DB_REPLICA
);
576 $id = $db->selectField(
580 'user_email_token' => md5( $code ),
581 'user_email_token_expires > ' . $db->addQuotes( $db->timestamp() ),
585 return $id ? User
::newFromId( $id ) : null;
589 * Create a new user object using data from session. If the login
590 * credentials are invalid, the result is an anonymous user.
592 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
595 public static function newFromSession( WebRequest
$request = null ) {
597 $user->mFrom
= 'session';
598 $user->mRequest
= $request;
603 * Create a new user object from a user row.
604 * The row should have the following fields from the user table in it:
605 * - either user_name or user_id to load further data if needed (or both)
607 * - all other fields (email, etc.)
608 * It is useless to provide the remaining fields if either user_id,
609 * user_name and user_real_name are not provided because the whole row
610 * will be loaded once more from the database when accessing them.
612 * @param stdClass $row A row from the user table
613 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
616 public static function newFromRow( $row, $data = null ) {
618 $user->loadFromRow( $row, $data );
623 * Static factory method for creation of a "system" user from username.
625 * A "system" user is an account that's used to attribute logged actions
626 * taken by MediaWiki itself, as opposed to a bot or human user. Examples
627 * might include the 'Maintenance script' or 'Conversion script' accounts
628 * used by various scripts in the maintenance/ directory or accounts such
629 * as 'MediaWiki message delivery' used by the MassMessage extension.
631 * This can optionally create the user if it doesn't exist, and "steal" the
632 * account if it does exist.
634 * "Stealing" an existing user is intended to make it impossible for normal
635 * authentication processes to use the account, effectively disabling the
636 * account for normal use:
637 * - Email is invalidated, to prevent account recovery by emailing a
638 * temporary password and to disassociate the account from the existing
640 * - The token is set to a magic invalid value, to kill existing sessions
641 * and to prevent $this->setToken() calls from resetting the token to a
643 * - SessionManager is instructed to prevent new sessions for the user, to
644 * do things like deauthorizing OAuth consumers.
645 * - AuthManager is instructed to revoke access, to invalidate or remove
646 * passwords and other credentials.
648 * @param string $name Username
649 * @param array $options Options are:
650 * - validate: As for User::getCanonicalName(), default 'valid'
651 * - create: Whether to create the user if it doesn't already exist, default true
652 * - steal: Whether to "disable" the account for normal use if it already
653 * exists, default false
657 public static function newSystemUser( $name, $options = [] ) {
659 'validate' => 'valid',
664 $name = self
::getCanonicalName( $name, $options['validate'] );
665 if ( $name === false ) {
669 $fields = self
::selectFields();
671 $dbw = wfGetDB( DB_MASTER
);
672 $row = $dbw->selectRow(
675 [ 'user_name' => $name ],
679 // No user. Create it?
680 return $options['create'] ? self
::createNew( $name, [ 'token' => self
::INVALID_TOKEN
] ) : null;
682 $user = self
::newFromRow( $row );
684 // A user is considered to exist as a non-system user if it can
685 // authenticate, or has an email set, or has a non-invalid token.
686 if ( $user->mEmail ||
$user->mToken
!== self
::INVALID_TOKEN ||
687 AuthManager
::singleton()->userCanAuthenticate( $name )
689 // User exists. Steal it?
690 if ( !$options['steal'] ) {
694 AuthManager
::singleton()->revokeAccessForUser( $name );
696 $user->invalidateEmail();
697 $user->mToken
= self
::INVALID_TOKEN
;
698 $user->saveSettings();
699 SessionManager
::singleton()->preventSessionsForUser( $user->getName() );
708 * Get the username corresponding to a given user ID
709 * @param int $id User ID
710 * @return string|bool The corresponding username
712 public static function whoIs( $id ) {
713 return UserCache
::singleton()->getProp( $id, 'name' );
717 * Get the real name of a user given their user ID
719 * @param int $id User ID
720 * @return string|bool The corresponding user's real name
722 public static function whoIsReal( $id ) {
723 return UserCache
::singleton()->getProp( $id, 'real_name' );
727 * Get database id given a user name
728 * @param string $name Username
729 * @param integer $flags User::READ_* constant bitfield
730 * @return int|null The corresponding user's ID, or null if user is nonexistent
732 public static function idFromName( $name, $flags = self
::READ_NORMAL
) {
733 $nt = Title
::makeTitleSafe( NS_USER
, $name );
734 if ( is_null( $nt ) ) {
739 if ( !( $flags & self
::READ_LATEST
) && isset( self
::$idCacheByName[$name] ) ) {
740 return self
::$idCacheByName[$name];
743 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
744 $db = wfGetDB( $index );
749 [ 'user_name' => $nt->getText() ],
754 if ( $s === false ) {
757 $result = $s->user_id
;
760 self
::$idCacheByName[$name] = $result;
762 if ( count( self
::$idCacheByName ) > 1000 ) {
763 self
::$idCacheByName = [];
770 * Reset the cache used in idFromName(). For use in tests.
772 public static function resetIdByNameCache() {
773 self
::$idCacheByName = [];
777 * Does the string match an anonymous IP address?
779 * This function exists for username validation, in order to reject
780 * usernames which are similar in form to IP addresses. Strings such
781 * as 300.300.300.300 will return true because it looks like an IP
782 * address, despite not being strictly valid.
784 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
785 * address because the usemod software would "cloak" anonymous IP
786 * addresses like this, if we allowed accounts like this to be created
787 * new users could get the old edits of these anonymous users.
789 * @param string $name Name to match
792 public static function isIP( $name ) {
793 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
794 || IP
::isIPv6( $name );
798 * Is the input a valid username?
800 * Checks if the input is a valid username, we don't want an empty string,
801 * an IP address, anything that contains slashes (would mess up subpages),
802 * is longer than the maximum allowed username size or doesn't begin with
805 * @param string $name Name to match
808 public static function isValidUserName( $name ) {
809 global $wgContLang, $wgMaxNameChars;
812 || User
::isIP( $name )
813 ||
strpos( $name, '/' ) !== false
814 ||
strlen( $name ) > $wgMaxNameChars
815 ||
$name != $wgContLang->ucfirst( $name )
820 // Ensure that the name can't be misresolved as a different title,
821 // such as with extra namespace keys at the start.
822 $parsed = Title
::newFromText( $name );
823 if ( is_null( $parsed )
824 ||
$parsed->getNamespace()
825 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
829 // Check an additional blacklist of troublemaker characters.
830 // Should these be merged into the title char list?
831 $unicodeBlacklist = '/[' .
832 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
833 '\x{00a0}' . # non-breaking space
834 '\x{2000}-\x{200f}' . # various whitespace
835 '\x{2028}-\x{202f}' . # breaks and control chars
836 '\x{3000}' . # ideographic space
837 '\x{e000}-\x{f8ff}' . # private use
839 if ( preg_match( $unicodeBlacklist, $name ) ) {
847 * Usernames which fail to pass this function will be blocked
848 * from user login and new account registrations, but may be used
849 * internally by batch processes.
851 * If an account already exists in this form, login will be blocked
852 * by a failure to pass this function.
854 * @param string $name Name to match
857 public static function isUsableName( $name ) {
858 global $wgReservedUsernames;
859 // Must be a valid username, obviously ;)
860 if ( !self
::isValidUserName( $name ) ) {
864 static $reservedUsernames = false;
865 if ( !$reservedUsernames ) {
866 $reservedUsernames = $wgReservedUsernames;
867 Hooks
::run( 'UserGetReservedNames', [ &$reservedUsernames ] );
870 // Certain names may be reserved for batch processes.
871 foreach ( $reservedUsernames as $reserved ) {
872 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
873 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
875 if ( $reserved == $name ) {
883 * Return the users who are members of the given group(s). In case of multiple groups,
884 * users who are members of at least one of them are returned.
886 * @param string|array $groups A single group name or an array of group names
887 * @param int $limit Max number of users to return. The actual limit will never exceed 5000
888 * records; larger values are ignored.
889 * @param int $after ID the user to start after
890 * @return UserArrayFromResult
892 public static function findUsersByGroup( $groups, $limit = 5000, $after = null ) {
893 if ( $groups === [] ) {
894 return UserArrayFromResult
::newFromIDs( [] );
897 $groups = array_unique( (array)$groups );
898 $limit = min( 5000, $limit );
900 $conds = [ 'ug_group' => $groups ];
901 if ( $after !== null ) {
902 $conds[] = 'ug_user > ' . (int)$after;
905 $dbr = wfGetDB( DB_REPLICA
);
906 $ids = $dbr->selectFieldValues(
913 'ORDER BY' => 'ug_user',
917 return UserArray
::newFromIDs( $ids );
921 * Usernames which fail to pass this function will be blocked
922 * from new account registrations, but may be used internally
923 * either by batch processes or by user accounts which have
924 * already been created.
926 * Additional blacklisting may be added here rather than in
927 * isValidUserName() to avoid disrupting existing accounts.
929 * @param string $name String to match
932 public static function isCreatableName( $name ) {
933 global $wgInvalidUsernameCharacters;
935 // Ensure that the username isn't longer than 235 bytes, so that
936 // (at least for the builtin skins) user javascript and css files
937 // will work. (bug 23080)
938 if ( strlen( $name ) > 235 ) {
939 wfDebugLog( 'username', __METHOD__
.
940 ": '$name' invalid due to length" );
944 // Preg yells if you try to give it an empty string
945 if ( $wgInvalidUsernameCharacters !== '' ) {
946 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
947 wfDebugLog( 'username', __METHOD__
.
948 ": '$name' invalid due to wgInvalidUsernameCharacters" );
953 return self
::isUsableName( $name );
957 * Is the input a valid password for this user?
959 * @param string $password Desired password
962 public function isValidPassword( $password ) {
963 // simple boolean wrapper for getPasswordValidity
964 return $this->getPasswordValidity( $password ) === true;
968 * Given unvalidated password input, return error message on failure.
970 * @param string $password Desired password
971 * @return bool|string|array True on success, string or array of error message on failure
973 public function getPasswordValidity( $password ) {
974 $result = $this->checkPasswordValidity( $password );
975 if ( $result->isGood() ) {
979 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
980 $messages[] = $error['message'];
982 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
983 $messages[] = $warning['message'];
985 if ( count( $messages ) === 1 ) {
993 * Check if this is a valid password for this user
995 * Create a Status object based on the password's validity.
996 * The Status should be set to fatal if the user should not
997 * be allowed to log in, and should have any errors that
998 * would block changing the password.
1000 * If the return value of this is not OK, the password
1001 * should not be checked. If the return value is not Good,
1002 * the password can be checked, but the user should not be
1003 * able to set their password to this.
1005 * @param string $password Desired password
1009 public function checkPasswordValidity( $password ) {
1010 global $wgPasswordPolicy;
1012 $upp = new UserPasswordPolicy(
1013 $wgPasswordPolicy['policies'],
1014 $wgPasswordPolicy['checks']
1017 $status = Status
::newGood();
1018 $result = false; // init $result to false for the internal checks
1020 if ( !Hooks
::run( 'isValidPassword', [ $password, &$result, $this ] ) ) {
1021 $status->error( $result );
1025 if ( $result === false ) {
1026 $status->merge( $upp->checkUserPassword( $this, $password ) );
1028 } elseif ( $result === true ) {
1031 $status->error( $result );
1032 return $status; // the isValidPassword hook set a string $result and returned true
1037 * Given unvalidated user input, return a canonical username, or false if
1038 * the username is invalid.
1039 * @param string $name User input
1040 * @param string|bool $validate Type of validation to use:
1041 * - false No validation
1042 * - 'valid' Valid for batch processes
1043 * - 'usable' Valid for batch processes and login
1044 * - 'creatable' Valid for batch processes, login and account creation
1046 * @throws InvalidArgumentException
1047 * @return bool|string
1049 public static function getCanonicalName( $name, $validate = 'valid' ) {
1050 // Force usernames to capital
1052 $name = $wgContLang->ucfirst( $name );
1054 # Reject names containing '#'; these will be cleaned up
1055 # with title normalisation, but then it's too late to
1057 if ( strpos( $name, '#' ) !== false ) {
1061 // Clean up name according to title rules,
1062 // but only when validation is requested (bug 12654)
1063 $t = ( $validate !== false ) ?
1064 Title
::newFromText( $name, NS_USER
) : Title
::makeTitle( NS_USER
, $name );
1065 // Check for invalid titles
1066 if ( is_null( $t ) ||
$t->getNamespace() !== NS_USER ||
$t->isExternal() ) {
1070 // Reject various classes of invalid names
1071 $name = AuthManager
::callLegacyAuthPlugin(
1072 'getCanonicalName', [ $t->getText() ], $t->getText()
1075 switch ( $validate ) {
1079 if ( !User
::isValidUserName( $name ) ) {
1084 if ( !User
::isUsableName( $name ) ) {
1089 if ( !User
::isCreatableName( $name ) ) {
1094 throw new InvalidArgumentException(
1095 'Invalid parameter value for $validate in ' . __METHOD__
);
1101 * Return a random password.
1103 * @deprecated since 1.27, use PasswordFactory::generateRandomPasswordString()
1104 * @return string New random password
1106 public static function randomPassword() {
1107 global $wgMinimalPasswordLength;
1108 return PasswordFactory
::generateRandomPasswordString( $wgMinimalPasswordLength );
1112 * Set cached properties to default.
1114 * @note This no longer clears uncached lazy-initialised properties;
1115 * the constructor does that instead.
1117 * @param string|bool $name
1119 public function loadDefaults( $name = false ) {
1121 $this->mName
= $name;
1122 $this->mRealName
= '';
1124 $this->mOptionOverrides
= null;
1125 $this->mOptionsLoaded
= false;
1127 $loggedOut = $this->mRequest
&& !defined( 'MW_NO_SESSION' )
1128 ?
$this->mRequest
->getSession()->getLoggedOutTimestamp() : 0;
1129 if ( $loggedOut !== 0 ) {
1130 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1132 $this->mTouched
= '1'; # Allow any pages to be cached
1135 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1136 $this->mEmailAuthenticated
= null;
1137 $this->mEmailToken
= '';
1138 $this->mEmailTokenExpires
= null;
1139 $this->mRegistration
= wfTimestamp( TS_MW
);
1140 $this->mGroups
= [];
1142 Hooks
::run( 'UserLoadDefaults', [ $this, $name ] );
1146 * Return whether an item has been loaded.
1148 * @param string $item Item to check. Current possibilities:
1152 * @param string $all 'all' to check if the whole object has been loaded
1153 * or any other string to check if only the item is available (e.g.
1157 public function isItemLoaded( $item, $all = 'all' ) {
1158 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1159 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1163 * Set that an item has been loaded
1165 * @param string $item
1167 protected function setItemLoaded( $item ) {
1168 if ( is_array( $this->mLoadedItems
) ) {
1169 $this->mLoadedItems
[$item] = true;
1174 * Load user data from the session.
1176 * @return bool True if the user is logged in, false otherwise.
1178 private function loadFromSession() {
1181 Hooks
::run( 'UserLoadFromSession', [ $this, &$result ], '1.27' );
1182 if ( $result !== null ) {
1186 // MediaWiki\Session\Session already did the necessary authentication of the user
1187 // returned here, so just use it if applicable.
1188 $session = $this->getRequest()->getSession();
1189 $user = $session->getUser();
1190 if ( $user->isLoggedIn() ) {
1191 $this->loadFromUserObject( $user );
1193 // If this user is autoblocked, set a cookie to track the Block. This has to be done on
1194 // every session load, because an autoblocked editor might not edit again from the same
1195 // IP address after being blocked.
1196 $config = RequestContext
::getMain()->getConfig();
1197 if ( $config->get( 'CookieSetOnAutoblock' ) === true ) {
1198 $block = $this->getBlock();
1199 $shouldSetCookie = $this->getRequest()->getCookie( 'BlockID' ) === null
1201 && $block->getType() === Block
::TYPE_USER
1202 && $block->isAutoblocking();
1203 if ( $shouldSetCookie ) {
1204 wfDebug( __METHOD__
. ': User is autoblocked, setting cookie to track' );
1205 $block->setCookie( $this->getRequest()->response() );
1209 // Other code expects these to be set in the session, so set them.
1210 $session->set( 'wsUserID', $this->getId() );
1211 $session->set( 'wsUserName', $this->getName() );
1212 $session->set( 'wsToken', $this->getToken() );
1219 * Load user and user_group data from the database.
1220 * $this->mId must be set, this is how the user is identified.
1222 * @param integer $flags User::READ_* constant bitfield
1223 * @return bool True if the user exists, false if the user is anonymous
1225 public function loadFromDatabase( $flags = self
::READ_LATEST
) {
1227 $this->mId
= intval( $this->mId
);
1229 if ( !$this->mId
) {
1230 // Anonymous users are not in the database
1231 $this->loadDefaults();
1235 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
1236 $db = wfGetDB( $index );
1238 $s = $db->selectRow(
1240 self
::selectFields(),
1241 [ 'user_id' => $this->mId
],
1246 $this->queryFlagsUsed
= $flags;
1247 Hooks
::run( 'UserLoadFromDatabase', [ $this, &$s ] );
1249 if ( $s !== false ) {
1250 // Initialise user table data
1251 $this->loadFromRow( $s );
1252 $this->mGroups
= null; // deferred
1253 $this->getEditCount(); // revalidation for nulls
1258 $this->loadDefaults();
1264 * Initialize this object from a row from the user table.
1266 * @param stdClass $row Row from the user table to load.
1267 * @param array $data Further user data to load into the object
1269 * user_groups Array with groups out of the user_groups table
1270 * user_properties Array with properties out of the user_properties table
1272 protected function loadFromRow( $row, $data = null ) {
1275 $this->mGroups
= null; // deferred
1277 if ( isset( $row->user_name
) ) {
1278 $this->mName
= $row->user_name
;
1279 $this->mFrom
= 'name';
1280 $this->setItemLoaded( 'name' );
1285 if ( isset( $row->user_real_name
) ) {
1286 $this->mRealName
= $row->user_real_name
;
1287 $this->setItemLoaded( 'realname' );
1292 if ( isset( $row->user_id
) ) {
1293 $this->mId
= intval( $row->user_id
);
1294 $this->mFrom
= 'id';
1295 $this->setItemLoaded( 'id' );
1300 if ( isset( $row->user_id
) && isset( $row->user_name
) ) {
1301 self
::$idCacheByName[$row->user_name
] = $row->user_id
;
1304 if ( isset( $row->user_editcount
) ) {
1305 $this->mEditCount
= $row->user_editcount
;
1310 if ( isset( $row->user_touched
) ) {
1311 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1316 if ( isset( $row->user_token
) ) {
1317 // The definition for the column is binary(32), so trim the NULs
1318 // that appends. The previous definition was char(32), so trim
1320 $this->mToken
= rtrim( $row->user_token
, " \0" );
1321 if ( $this->mToken
=== '' ) {
1322 $this->mToken
= null;
1328 if ( isset( $row->user_email
) ) {
1329 $this->mEmail
= $row->user_email
;
1330 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1331 $this->mEmailToken
= $row->user_email_token
;
1332 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1333 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1339 $this->mLoadedItems
= true;
1342 if ( is_array( $data ) ) {
1343 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1344 $this->mGroups
= $data['user_groups'];
1346 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1347 $this->loadOptions( $data['user_properties'] );
1353 * Load the data for this user object from another user object.
1357 protected function loadFromUserObject( $user ) {
1359 foreach ( self
::$mCacheVars as $var ) {
1360 $this->$var = $user->$var;
1365 * Load the groups from the database if they aren't already loaded.
1367 private function loadGroups() {
1368 if ( is_null( $this->mGroups
) ) {
1369 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
1370 ?
wfGetDB( DB_MASTER
)
1371 : wfGetDB( DB_REPLICA
);
1372 $res = $db->select( 'user_groups',
1374 [ 'ug_user' => $this->mId
],
1376 $this->mGroups
= [];
1377 foreach ( $res as $row ) {
1378 $this->mGroups
[] = $row->ug_group
;
1384 * Add the user to the group if he/she meets given criteria.
1386 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1387 * possible to remove manually via Special:UserRights. In such case it
1388 * will not be re-added automatically. The user will also not lose the
1389 * group if they no longer meet the criteria.
1391 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1393 * @return array Array of groups the user has been promoted to.
1395 * @see $wgAutopromoteOnce
1397 public function addAutopromoteOnceGroups( $event ) {
1398 global $wgAutopromoteOnceLogInRC;
1400 if ( wfReadOnly() ||
!$this->getId() ) {
1404 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1405 if ( !count( $toPromote ) ) {
1409 if ( !$this->checkAndSetTouched() ) {
1410 return []; // raced out (bug T48834)
1413 $oldGroups = $this->getGroups(); // previous groups
1414 foreach ( $toPromote as $group ) {
1415 $this->addGroup( $group );
1417 // update groups in external authentication database
1418 Hooks
::run( 'UserGroupsChanged', [ $this, $toPromote, [], false, false ] );
1419 AuthManager
::callLegacyAuthPlugin( 'updateExternalDBGroups', [ $this, $toPromote ] );
1421 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1423 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1424 $logEntry->setPerformer( $this );
1425 $logEntry->setTarget( $this->getUserPage() );
1426 $logEntry->setParameters( [
1427 '4::oldgroups' => $oldGroups,
1428 '5::newgroups' => $newGroups,
1430 $logid = $logEntry->insert();
1431 if ( $wgAutopromoteOnceLogInRC ) {
1432 $logEntry->publish( $logid );
1439 * Builds update conditions. Additional conditions may be added to $conditions to
1440 * protected against race conditions using a compare-and-set (CAS) mechanism
1441 * based on comparing $this->mTouched with the user_touched field.
1443 * @param Database $db
1444 * @param array $conditions WHERE conditions for use with Database::update
1445 * @return array WHERE conditions for use with Database::update
1447 protected function makeUpdateConditions( Database
$db, array $conditions ) {
1448 if ( $this->mTouched
) {
1449 // CAS check: only update if the row wasn't changed sicne it was loaded.
1450 $conditions['user_touched'] = $db->timestamp( $this->mTouched
);
1457 * Bump user_touched if it didn't change since this object was loaded
1459 * On success, the mTouched field is updated.
1460 * The user serialization cache is always cleared.
1462 * @return bool Whether user_touched was actually updated
1465 protected function checkAndSetTouched() {
1468 if ( !$this->mId
) {
1469 return false; // anon
1472 // Get a new user_touched that is higher than the old one
1473 $newTouched = $this->newTouchedTimestamp();
1475 $dbw = wfGetDB( DB_MASTER
);
1476 $dbw->update( 'user',
1477 [ 'user_touched' => $dbw->timestamp( $newTouched ) ],
1478 $this->makeUpdateConditions( $dbw, [
1479 'user_id' => $this->mId
,
1483 $success = ( $dbw->affectedRows() > 0 );
1486 $this->mTouched
= $newTouched;
1487 $this->clearSharedCache();
1489 // Clears on failure too since that is desired if the cache is stale
1490 $this->clearSharedCache( 'refresh' );
1497 * Clear various cached data stored in this object. The cache of the user table
1498 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1500 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1501 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1503 public function clearInstanceCache( $reloadFrom = false ) {
1504 $this->mNewtalk
= -1;
1505 $this->mDatePreference
= null;
1506 $this->mBlockedby
= -1; # Unset
1507 $this->mHash
= false;
1508 $this->mRights
= null;
1509 $this->mEffectiveGroups
= null;
1510 $this->mImplicitGroups
= null;
1511 $this->mGroups
= null;
1512 $this->mOptions
= null;
1513 $this->mOptionsLoaded
= false;
1514 $this->mEditCount
= null;
1516 if ( $reloadFrom ) {
1517 $this->mLoadedItems
= [];
1518 $this->mFrom
= $reloadFrom;
1523 * Combine the language default options with any site-specific options
1524 * and add the default language variants.
1526 * @return array Array of String options
1528 public static function getDefaultOptions() {
1529 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1531 static $defOpt = null;
1532 static $defOptLang = null;
1534 if ( $defOpt !== null && $defOptLang === $wgContLang->getCode() ) {
1535 // $wgContLang does not change (and should not change) mid-request,
1536 // but the unit tests change it anyway, and expect this method to
1537 // return values relevant to the current $wgContLang.
1541 $defOpt = $wgDefaultUserOptions;
1542 // Default language setting
1543 $defOptLang = $wgContLang->getCode();
1544 $defOpt['language'] = $defOptLang;
1545 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1546 $defOpt[$langCode == $wgContLang->getCode() ?
'variant' : "variant-$langCode"] = $langCode;
1549 // NOTE: don't use SearchEngineConfig::getSearchableNamespaces here,
1550 // since extensions may change the set of searchable namespaces depending
1551 // on user groups/permissions.
1552 foreach ( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
1553 $defOpt['searchNs' . $nsnum] = (boolean
)$val;
1555 $defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1557 Hooks
::run( 'UserGetDefaultOptions', [ &$defOpt ] );
1563 * Get a given default option value.
1565 * @param string $opt Name of option to retrieve
1566 * @return string Default option value
1568 public static function getDefaultOption( $opt ) {
1569 $defOpts = self
::getDefaultOptions();
1570 if ( isset( $defOpts[$opt] ) ) {
1571 return $defOpts[$opt];
1578 * Get blocking information
1579 * @param bool $bFromSlave Whether to check the replica DB first.
1580 * To improve performance, non-critical checks are done against replica DBs.
1581 * Check when actually saving should be done against master.
1583 private function getBlockedStatus( $bFromSlave = true ) {
1584 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1586 if ( -1 != $this->mBlockedby
) {
1590 wfDebug( __METHOD__
. ": checking...\n" );
1592 // Initialize data...
1593 // Otherwise something ends up stomping on $this->mBlockedby when
1594 // things get lazy-loaded later, causing false positive block hits
1595 // due to -1 !== 0. Probably session-related... Nothing should be
1596 // overwriting mBlockedby, surely?
1599 # We only need to worry about passing the IP address to the Block generator if the
1600 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1601 # know which IP address they're actually coming from
1603 if ( !$this->isAllowed( 'ipblock-exempt' ) ) {
1604 // $wgUser->getName() only works after the end of Setup.php. Until
1605 // then, assume it's a logged-out user.
1606 $globalUserName = $wgUser->isSafeToLoad()
1607 ?
$wgUser->getName()
1608 : IP
::sanitizeIP( $wgUser->getRequest()->getIP() );
1609 if ( $this->getName() === $globalUserName ) {
1610 $ip = $this->getRequest()->getIP();
1615 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1617 // If no block has been found, check for a cookie indicating that the user is blocked.
1618 $blockCookieVal = (int)$this->getRequest()->getCookie( 'BlockID' );
1619 if ( !$block instanceof Block
&& $blockCookieVal > 0 ) {
1620 // Load the Block from the ID in the cookie.
1621 $tmpBlock = Block
::newFromID( $blockCookieVal );
1622 if ( $tmpBlock instanceof Block
) {
1623 // Check the validity of the block.
1624 $blockIsValid = $tmpBlock->getType() == Block
::TYPE_USER
1625 && !$tmpBlock->isExpired()
1626 && $tmpBlock->isAutoblocking();
1627 $config = RequestContext
::getMain()->getConfig();
1628 $useBlockCookie = ( $config->get( 'CookieSetOnAutoblock' ) === true );
1629 if ( $blockIsValid && $useBlockCookie ) {
1632 $this->blockTrigger
= 'cookie-block';
1634 // If the block is not valid, clear the block cookie (but don't delete it,
1635 // because it needs to be cleared from LocalStorage as well and an empty string
1636 // value is checked for in the mediawiki.user.blockcookie module).
1637 $tmpBlock->setCookie( $this->getRequest()->response(), true );
1643 if ( !$block instanceof Block
&& $ip !== null && !in_array( $ip, $wgProxyWhitelist ) ) {
1645 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1646 $block = new Block( [
1647 'byText' => wfMessage( 'proxyblocker' )->text(),
1648 'reason' => wfMessage( 'proxyblockreason' )->text(),
1650 'systemBlock' => 'proxy',
1652 $this->blockTrigger
= 'proxy-block';
1653 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1654 $block = new Block( [
1655 'byText' => wfMessage( 'sorbs' )->text(),
1656 'reason' => wfMessage( 'sorbsreason' )->text(),
1658 'systemBlock' => 'dnsbl',
1660 $this->blockTrigger
= 'openproxy-block';
1664 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1665 if ( !$block instanceof Block
1666 && $wgApplyIpBlocksToXff
1668 && !in_array( $ip, $wgProxyWhitelist )
1670 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1671 $xff = array_map( 'trim', explode( ',', $xff ) );
1672 $xff = array_diff( $xff, [ $ip ] );
1673 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1674 $block = Block
::chooseBlock( $xffblocks, $xff );
1675 if ( $block instanceof Block
) {
1676 # Mangle the reason to alert the user that the block
1677 # originated from matching the X-Forwarded-For header.
1678 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->text();
1679 $this->blockTrigger
= 'xff-block';
1683 if ( $block instanceof Block
) {
1684 wfDebug( __METHOD__
. ": Found block.\n" );
1685 $this->mBlock
= $block;
1686 $this->mBlockedby
= $block->getByName();
1687 $this->mBlockreason
= $block->mReason
;
1688 $this->mHideName
= $block->mHideName
;
1689 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1691 $this->mBlockedby
= '';
1692 $this->mHideName
= 0;
1693 $this->mAllowUsertalk
= false;
1694 $this->blockTrigger
= false;
1697 // Avoid PHP 7.1 warning of passing $this by reference
1700 Hooks
::run( 'GetBlockedStatus', [ &$user ] );
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 values from the specified file
1786 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1789 if ( is_array( $wgProxyList ) ) {
1791 // Look for IP as value
1792 array_search( $ip, $wgProxyList ) !== false ||
1793 // Look for IP as key (for backwards-compatility)
1794 array_key_exists( $ip, $wgProxyList )
1804 * Is this user subject to rate limiting?
1806 * @return bool True if rate limited
1808 public function isPingLimitable() {
1809 global $wgRateLimitsExcludedIPs;
1810 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1811 // No other good way currently to disable rate limits
1812 // for specific IPs. :P
1813 // But this is a crappy hack and should die.
1816 return !$this->isAllowed( 'noratelimit' );
1820 * Primitive rate limits: enforce maximum actions per time period
1821 * to put a brake on flooding.
1823 * The method generates both a generic profiling point and a per action one
1824 * (suffix being "-$action".
1826 * @note When using a shared cache like memcached, IP-address
1827 * last-hit counters will be shared across wikis.
1829 * @param string $action Action to enforce; 'edit' if unspecified
1830 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1831 * @return bool True if a rate limiter was tripped
1833 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1834 // Avoid PHP 7.1 warning of passing $this by reference
1836 // Call the 'PingLimiter' hook
1838 if ( !Hooks
::run( 'PingLimiter', [ &$user, $action, &$result, $incrBy ] ) ) {
1842 global $wgRateLimits;
1843 if ( !isset( $wgRateLimits[$action] ) ) {
1847 $limits = array_merge(
1848 [ '&can-bypass' => true ],
1849 $wgRateLimits[$action]
1852 // Some groups shouldn't trigger the ping limiter, ever
1853 if ( $limits['&can-bypass'] && !$this->isPingLimitable() ) {
1858 $id = $this->getId();
1860 $isNewbie = $this->isNewbie();
1864 if ( isset( $limits['anon'] ) ) {
1865 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1868 // limits for logged-in users
1869 if ( isset( $limits['user'] ) ) {
1870 $userLimit = $limits['user'];
1872 // limits for newbie logged-in users
1873 if ( $isNewbie && isset( $limits['newbie'] ) ) {
1874 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1878 // limits for anons and for newbie logged-in users
1881 if ( isset( $limits['ip'] ) ) {
1882 $ip = $this->getRequest()->getIP();
1883 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1885 // subnet-based limits
1886 if ( isset( $limits['subnet'] ) ) {
1887 $ip = $this->getRequest()->getIP();
1888 $subnet = IP
::getSubnet( $ip );
1889 if ( $subnet !== false ) {
1890 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1895 // Check for group-specific permissions
1896 // If more than one group applies, use the group with the highest limit ratio (max/period)
1897 foreach ( $this->getGroups() as $group ) {
1898 if ( isset( $limits[$group] ) ) {
1899 if ( $userLimit === false
1900 ||
$limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1902 $userLimit = $limits[$group];
1907 // Set the user limit key
1908 if ( $userLimit !== false ) {
1909 list( $max, $period ) = $userLimit;
1910 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
1911 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1914 // ip-based limits for all ping-limitable users
1915 if ( isset( $limits['ip-all'] ) ) {
1916 $ip = $this->getRequest()->getIP();
1917 // ignore if user limit is more permissive
1918 if ( $isNewbie ||
$userLimit === false
1919 ||
$limits['ip-all'][0] / $limits['ip-all'][1] > $userLimit[0] / $userLimit[1] ) {
1920 $keys["mediawiki:limiter:$action:ip-all:$ip"] = $limits['ip-all'];
1924 // subnet-based limits for all ping-limitable users
1925 if ( isset( $limits['subnet-all'] ) ) {
1926 $ip = $this->getRequest()->getIP();
1927 $subnet = IP
::getSubnet( $ip );
1928 if ( $subnet !== false ) {
1929 // ignore if user limit is more permissive
1930 if ( $isNewbie ||
$userLimit === false
1931 ||
$limits['ip-all'][0] / $limits['ip-all'][1]
1932 > $userLimit[0] / $userLimit[1] ) {
1933 $keys["mediawiki:limiter:$action:subnet-all:$subnet"] = $limits['subnet-all'];
1938 $cache = ObjectCache
::getLocalClusterInstance();
1941 foreach ( $keys as $key => $limit ) {
1942 list( $max, $period ) = $limit;
1943 $summary = "(limit $max in {$period}s)";
1944 $count = $cache->get( $key );
1947 if ( $count >= $max ) {
1948 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1949 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1952 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1955 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1956 if ( $incrBy > 0 ) {
1957 $cache->add( $key, 0, intval( $period ) ); // first ping
1960 if ( $incrBy > 0 ) {
1961 $cache->incr( $key, $incrBy );
1969 * Check if user is blocked
1971 * @param bool $bFromSlave Whether to check the replica DB instead of
1972 * the master. Hacked from false due to horrible probs on site.
1973 * @return bool True if blocked, false otherwise
1975 public function isBlocked( $bFromSlave = true ) {
1976 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
1980 * Get the block affecting the user, or null if the user is not blocked
1982 * @param bool $bFromSlave Whether to check the replica DB instead of the master
1983 * @return Block|null
1985 public function getBlock( $bFromSlave = true ) {
1986 $this->getBlockedStatus( $bFromSlave );
1987 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
1991 * Check if user is blocked from editing a particular article
1993 * @param Title $title Title to check
1994 * @param bool $bFromSlave Whether to check the replica DB instead of the master
1997 public function isBlockedFrom( $title, $bFromSlave = false ) {
1998 global $wgBlockAllowsUTEdit;
2000 $blocked = $this->isBlocked( $bFromSlave );
2001 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
2002 // If a user's name is suppressed, they cannot make edits anywhere
2003 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName()
2004 && $title->getNamespace() == NS_USER_TALK
) {
2006 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
2009 Hooks
::run( 'UserIsBlockedFrom', [ $this, $title, &$blocked, &$allowUsertalk ] );
2015 * If user is blocked, return the name of the user who placed the block
2016 * @return string Name of blocker
2018 public function blockedBy() {
2019 $this->getBlockedStatus();
2020 return $this->mBlockedby
;
2024 * If user is blocked, return the specified reason for the block
2025 * @return string Blocking reason
2027 public function blockedFor() {
2028 $this->getBlockedStatus();
2029 return $this->mBlockreason
;
2033 * If user is blocked, return the ID for the block
2034 * @return int Block ID
2036 public function getBlockId() {
2037 $this->getBlockedStatus();
2038 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
2042 * Check if user is blocked on all wikis.
2043 * Do not use for actual edit permission checks!
2044 * This is intended for quick UI checks.
2046 * @param string $ip IP address, uses current client if none given
2047 * @return bool True if blocked, false otherwise
2049 public function isBlockedGlobally( $ip = '' ) {
2050 return $this->getGlobalBlock( $ip ) instanceof Block
;
2054 * Check if user is blocked on all wikis.
2055 * Do not use for actual edit permission checks!
2056 * This is intended for quick UI checks.
2058 * @param string $ip IP address, uses current client if none given
2059 * @return Block|null Block object if blocked, null otherwise
2060 * @throws FatalError
2061 * @throws MWException
2063 public function getGlobalBlock( $ip = '' ) {
2064 if ( $this->mGlobalBlock
!== null ) {
2065 return $this->mGlobalBlock ?
: null;
2067 // User is already an IP?
2068 if ( IP
::isIPAddress( $this->getName() ) ) {
2069 $ip = $this->getName();
2071 $ip = $this->getRequest()->getIP();
2073 // Avoid PHP 7.1 warning of passing $this by reference
2077 Hooks
::run( 'UserIsBlockedGlobally', [ &$user, $ip, &$blocked, &$block ] );
2079 if ( $blocked && $block === null ) {
2080 // back-compat: UserIsBlockedGlobally didn't have $block param first
2081 $block = new Block( [
2083 'systemBlock' => 'global-block'
2087 $this->mGlobalBlock
= $blocked ?
$block : false;
2088 return $this->mGlobalBlock ?
: null;
2092 * Check if user account is locked
2094 * @return bool True if locked, false otherwise
2096 public function isLocked() {
2097 if ( $this->mLocked
!== null ) {
2098 return $this->mLocked
;
2100 // Avoid PHP 7.1 warning of passing $this by reference
2102 $authUser = AuthManager
::callLegacyAuthPlugin( 'getUserInstance', [ &$user ], null );
2103 $this->mLocked
= $authUser && $authUser->isLocked();
2104 Hooks
::run( 'UserIsLocked', [ $this, &$this->mLocked
] );
2105 return $this->mLocked
;
2109 * Check if user account is hidden
2111 * @return bool True if hidden, false otherwise
2113 public function isHidden() {
2114 if ( $this->mHideName
!== null ) {
2115 return $this->mHideName
;
2117 $this->getBlockedStatus();
2118 if ( !$this->mHideName
) {
2119 // Avoid PHP 7.1 warning of passing $this by reference
2121 $authUser = AuthManager
::callLegacyAuthPlugin( 'getUserInstance', [ &$user ], null );
2122 $this->mHideName
= $authUser && $authUser->isHidden();
2123 Hooks
::run( 'UserIsHidden', [ $this, &$this->mHideName
] );
2125 return $this->mHideName
;
2129 * Get the user's ID.
2130 * @return int The user's ID; 0 if the user is anonymous or nonexistent
2132 public function getId() {
2133 if ( $this->mId
=== null && $this->mName
!== null && User
::isIP( $this->mName
) ) {
2134 // Special case, we know the user is anonymous
2136 } elseif ( !$this->isItemLoaded( 'id' ) ) {
2137 // Don't load if this was initialized from an ID
2141 return (int)$this->mId
;
2145 * Set the user and reload all fields according to a given ID
2146 * @param int $v User ID to reload
2148 public function setId( $v ) {
2150 $this->clearInstanceCache( 'id' );
2154 * Get the user name, or the IP of an anonymous user
2155 * @return string User's name or IP address
2157 public function getName() {
2158 if ( $this->isItemLoaded( 'name', 'only' ) ) {
2159 // Special case optimisation
2160 return $this->mName
;
2163 if ( $this->mName
=== false ) {
2165 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
2167 return $this->mName
;
2172 * Set the user name.
2174 * This does not reload fields from the database according to the given
2175 * name. Rather, it is used to create a temporary "nonexistent user" for
2176 * later addition to the database. It can also be used to set the IP
2177 * address for an anonymous user to something other than the current
2180 * @note User::newFromName() has roughly the same function, when the named user
2182 * @param string $str New user name to set
2184 public function setName( $str ) {
2186 $this->mName
= $str;
2190 * Get the user's name escaped by underscores.
2191 * @return string Username escaped by underscores.
2193 public function getTitleKey() {
2194 return str_replace( ' ', '_', $this->getName() );
2198 * Check if the user has new messages.
2199 * @return bool True if the user has new messages
2201 public function getNewtalk() {
2204 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2205 if ( $this->mNewtalk
=== -1 ) {
2206 $this->mNewtalk
= false; # reset talk page status
2208 // Check memcached separately for anons, who have no
2209 // entire User object stored in there.
2210 if ( !$this->mId
) {
2211 global $wgDisableAnonTalk;
2212 if ( $wgDisableAnonTalk ) {
2213 // Anon newtalk disabled by configuration.
2214 $this->mNewtalk
= false;
2216 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
2219 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2223 return (bool)$this->mNewtalk
;
2227 * Return the data needed to construct links for new talk page message
2228 * alerts. If there are new messages, this will return an associative array
2229 * with the following data:
2230 * wiki: The database name of the wiki
2231 * link: Root-relative link to the user's talk page
2232 * rev: The last talk page revision that the user has seen or null. This
2233 * is useful for building diff links.
2234 * If there are no new messages, it returns an empty array.
2235 * @note This function was designed to accomodate multiple talk pages, but
2236 * currently only returns a single link and revision.
2239 public function getNewMessageLinks() {
2240 // Avoid PHP 7.1 warning of passing $this by reference
2243 if ( !Hooks
::run( 'UserRetrieveNewTalks', [ &$user, &$talks ] ) ) {
2245 } elseif ( !$this->getNewtalk() ) {
2248 $utp = $this->getTalkPage();
2249 $dbr = wfGetDB( DB_REPLICA
);
2250 // Get the "last viewed rev" timestamp from the oldest message notification
2251 $timestamp = $dbr->selectField( 'user_newtalk',
2252 'MIN(user_last_timestamp)',
2253 $this->isAnon() ?
[ 'user_ip' => $this->getName() ] : [ 'user_id' => $this->getId() ],
2255 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2256 return [ [ 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ] ];
2260 * Get the revision ID for the last talk page revision viewed by the talk
2262 * @return int|null Revision ID or null
2264 public function getNewMessageRevisionId() {
2265 $newMessageRevisionId = null;
2266 $newMessageLinks = $this->getNewMessageLinks();
2267 if ( $newMessageLinks ) {
2268 // Note: getNewMessageLinks() never returns more than a single link
2269 // and it is always for the same wiki, but we double-check here in
2270 // case that changes some time in the future.
2271 if ( count( $newMessageLinks ) === 1
2272 && $newMessageLinks[0]['wiki'] === wfWikiID()
2273 && $newMessageLinks[0]['rev']
2275 /** @var Revision $newMessageRevision */
2276 $newMessageRevision = $newMessageLinks[0]['rev'];
2277 $newMessageRevisionId = $newMessageRevision->getId();
2280 return $newMessageRevisionId;
2284 * Internal uncached check for new messages
2287 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2288 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2289 * @return bool True if the user has new messages
2291 protected function checkNewtalk( $field, $id ) {
2292 $dbr = wfGetDB( DB_REPLICA
);
2294 $ok = $dbr->selectField( 'user_newtalk', $field, [ $field => $id ], __METHOD__
);
2296 return $ok !== false;
2300 * Add or update the new messages flag
2301 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2302 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2303 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2304 * @return bool True if successful, false otherwise
2306 protected function updateNewtalk( $field, $id, $curRev = null ) {
2307 // Get timestamp of the talk page revision prior to the current one
2308 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2309 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2310 // Mark the user as having new messages since this revision
2311 $dbw = wfGetDB( DB_MASTER
);
2312 $dbw->insert( 'user_newtalk',
2313 [ $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ],
2316 if ( $dbw->affectedRows() ) {
2317 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2320 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2326 * Clear the new messages flag for the given user
2327 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2328 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2329 * @return bool True if successful, false otherwise
2331 protected function deleteNewtalk( $field, $id ) {
2332 $dbw = wfGetDB( DB_MASTER
);
2333 $dbw->delete( 'user_newtalk',
2336 if ( $dbw->affectedRows() ) {
2337 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2340 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2346 * Update the 'You have new messages!' status.
2347 * @param bool $val Whether the user has new messages
2348 * @param Revision $curRev New, as yet unseen revision of the user talk
2349 * page. Ignored if null or !$val.
2351 public function setNewtalk( $val, $curRev = null ) {
2352 if ( wfReadOnly() ) {
2357 $this->mNewtalk
= $val;
2359 if ( $this->isAnon() ) {
2361 $id = $this->getName();
2364 $id = $this->getId();
2368 $changed = $this->updateNewtalk( $field, $id, $curRev );
2370 $changed = $this->deleteNewtalk( $field, $id );
2374 $this->invalidateCache();
2379 * Generate a current or new-future timestamp to be stored in the
2380 * user_touched field when we update things.
2381 * @return string Timestamp in TS_MW format
2383 private function newTouchedTimestamp() {
2384 global $wgClockSkewFudge;
2386 $time = wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2387 if ( $this->mTouched
&& $time <= $this->mTouched
) {
2388 $time = wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $this->mTouched
) +
1 );
2395 * Clear user data from memcached
2397 * Use after applying updates to the database; caller's
2398 * responsibility to update user_touched if appropriate.
2400 * Called implicitly from invalidateCache() and saveSettings().
2402 * @param string $mode Use 'refresh' to clear now; otherwise before DB commit
2404 public function clearSharedCache( $mode = 'changed' ) {
2405 if ( !$this->getId() ) {
2409 $cache = ObjectCache
::getMainWANInstance();
2410 $key = $this->getCacheKey( $cache );
2411 if ( $mode === 'refresh' ) {
2412 $cache->delete( $key, 1 );
2414 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle(
2415 function() use ( $cache, $key ) {
2416 $cache->delete( $key );
2424 * Immediately touch the user data cache for this account
2426 * Calls touch() and removes account data from memcached
2428 public function invalidateCache() {
2430 $this->clearSharedCache();
2434 * Update the "touched" timestamp for the user
2436 * This is useful on various login/logout events when making sure that
2437 * a browser or proxy that has multiple tenants does not suffer cache
2438 * pollution where the new user sees the old users content. The value
2439 * of getTouched() is checked when determining 304 vs 200 responses.
2440 * Unlike invalidateCache(), this preserves the User object cache and
2441 * avoids database writes.
2445 public function touch() {
2446 $id = $this->getId();
2448 $key = wfMemcKey( 'user-quicktouched', 'id', $id );
2449 ObjectCache
::getMainWANInstance()->touchCheckKey( $key );
2450 $this->mQuickTouched
= null;
2455 * Validate the cache for this account.
2456 * @param string $timestamp A timestamp in TS_MW format
2459 public function validateCache( $timestamp ) {
2460 return ( $timestamp >= $this->getTouched() );
2464 * Get the user touched timestamp
2466 * Use this value only to validate caches via inequalities
2467 * such as in the case of HTTP If-Modified-Since response logic
2469 * @return string TS_MW Timestamp
2471 public function getTouched() {
2475 if ( $this->mQuickTouched
=== null ) {
2476 $key = wfMemcKey( 'user-quicktouched', 'id', $this->mId
);
2477 $cache = ObjectCache
::getMainWANInstance();
2479 $this->mQuickTouched
= wfTimestamp( TS_MW
, $cache->getCheckKeyTime( $key ) );
2482 return max( $this->mTouched
, $this->mQuickTouched
);
2485 return $this->mTouched
;
2489 * Get the user_touched timestamp field (time of last DB updates)
2490 * @return string TS_MW Timestamp
2493 public function getDBTouched() {
2496 return $this->mTouched
;
2500 * Set the password and reset the random token.
2501 * Calls through to authentication plugin if necessary;
2502 * will have no effect if the auth plugin refuses to
2503 * pass the change through or if the legal password
2506 * As a special case, setting the password to null
2507 * wipes it, so the account cannot be logged in until
2508 * a new password is set, for instance via e-mail.
2510 * @deprecated since 1.27, use AuthManager instead
2511 * @param string $str New password to set
2512 * @throws PasswordError On failure
2515 public function setPassword( $str ) {
2516 return $this->setPasswordInternal( $str );
2520 * Set the password and reset the random token unconditionally.
2522 * @deprecated since 1.27, use AuthManager instead
2523 * @param string|null $str New password to set or null to set an invalid
2524 * password hash meaning that the user will not be able to log in
2525 * through the web interface.
2527 public function setInternalPassword( $str ) {
2528 $this->setPasswordInternal( $str );
2532 * Actually set the password and such
2533 * @since 1.27 cannot set a password for a user not in the database
2534 * @param string|null $str New password to set or null to set an invalid
2535 * password hash meaning that the user will not be able to log in
2536 * through the web interface.
2537 * @return bool Success
2539 private function setPasswordInternal( $str ) {
2540 $manager = AuthManager
::singleton();
2542 // If the user doesn't exist yet, fail
2543 if ( !$manager->userExists( $this->getName() ) ) {
2544 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2547 $status = $this->changeAuthenticationData( [
2548 'username' => $this->getName(),
2552 if ( !$status->isGood() ) {
2553 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
2554 ->info( __METHOD__
. ': Password change rejected: '
2555 . $status->getWikiText( null, null, 'en' ) );
2559 $this->setOption( 'watchlisttoken', false );
2560 SessionManager
::singleton()->invalidateSessionsForUser( $this );
2566 * Changes credentials of the user.
2568 * This is a convenience wrapper around AuthManager::changeAuthenticationData.
2569 * Note that this can return a status that isOK() but not isGood() on certain types of failures,
2570 * e.g. when no provider handled the change.
2572 * @param array $data A set of authentication data in fieldname => value format. This is the
2573 * same data you would pass the changeauthenticationdata API - 'username', 'password' etc.
2577 public function changeAuthenticationData( array $data ) {
2578 $manager = AuthManager
::singleton();
2579 $reqs = $manager->getAuthenticationRequests( AuthManager
::ACTION_CHANGE
, $this );
2580 $reqs = AuthenticationRequest
::loadRequestsFromSubmission( $reqs, $data );
2582 $status = Status
::newGood( 'ignored' );
2583 foreach ( $reqs as $req ) {
2584 $status->merge( $manager->allowsAuthenticationDataChange( $req ), true );
2586 if ( $status->getValue() === 'ignored' ) {
2587 $status->warning( 'authenticationdatachange-ignored' );
2590 if ( $status->isGood() ) {
2591 foreach ( $reqs as $req ) {
2592 $manager->changeAuthenticationData( $req );
2599 * Get the user's current token.
2600 * @param bool $forceCreation Force the generation of a new token if the
2601 * user doesn't have one (default=true for backwards compatibility).
2602 * @return string|null Token
2604 public function getToken( $forceCreation = true ) {
2605 global $wgAuthenticationTokenVersion;
2608 if ( !$this->mToken
&& $forceCreation ) {
2612 if ( !$this->mToken
) {
2613 // The user doesn't have a token, return null to indicate that.
2615 } elseif ( $this->mToken
=== self
::INVALID_TOKEN
) {
2616 // We return a random value here so existing token checks are very
2618 return MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2619 } elseif ( $wgAuthenticationTokenVersion === null ) {
2620 // $wgAuthenticationTokenVersion not in use, so return the raw secret
2621 return $this->mToken
;
2623 // $wgAuthenticationTokenVersion in use, so hmac it.
2624 $ret = MWCryptHash
::hmac( $wgAuthenticationTokenVersion, $this->mToken
, false );
2626 // The raw hash can be overly long. Shorten it up.
2627 $len = max( 32, self
::TOKEN_LENGTH
);
2628 if ( strlen( $ret ) < $len ) {
2629 // Should never happen, even md5 is 128 bits
2630 throw new \
UnexpectedValueException( 'Hmac returned less than 128 bits' );
2632 return substr( $ret, -$len );
2637 * Set the random token (used for persistent authentication)
2638 * Called from loadDefaults() among other places.
2640 * @param string|bool $token If specified, set the token to this value
2642 public function setToken( $token = false ) {
2644 if ( $this->mToken
=== self
::INVALID_TOKEN
) {
2645 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
2646 ->debug( __METHOD__
. ": Ignoring attempt to set token for system user \"$this\"" );
2647 } elseif ( !$token ) {
2648 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2650 $this->mToken
= $token;
2655 * Set the password for a password reminder or new account email
2657 * @deprecated Removed in 1.27. Use PasswordReset instead.
2658 * @param string $str New password to set or null to set an invalid
2659 * password hash meaning that the user will not be able to use it
2660 * @param bool $throttle If true, reset the throttle timestamp to the present
2662 public function setNewpassword( $str, $throttle = true ) {
2663 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2667 * Get the user's e-mail address
2668 * @return string User's email address
2670 public function getEmail() {
2672 Hooks
::run( 'UserGetEmail', [ $this, &$this->mEmail
] );
2673 return $this->mEmail
;
2677 * Get the timestamp of the user's e-mail authentication
2678 * @return string TS_MW timestamp
2680 public function getEmailAuthenticationTimestamp() {
2682 Hooks
::run( 'UserGetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
2683 return $this->mEmailAuthenticated
;
2687 * Set the user's e-mail address
2688 * @param string $str New e-mail address
2690 public function setEmail( $str ) {
2692 if ( $str == $this->mEmail
) {
2695 $this->invalidateEmail();
2696 $this->mEmail
= $str;
2697 Hooks
::run( 'UserSetEmail', [ $this, &$this->mEmail
] );
2701 * Set the user's e-mail address and a confirmation mail if needed.
2704 * @param string $str New e-mail address
2707 public function setEmailWithConfirmation( $str ) {
2708 global $wgEnableEmail, $wgEmailAuthentication;
2710 if ( !$wgEnableEmail ) {
2711 return Status
::newFatal( 'emaildisabled' );
2714 $oldaddr = $this->getEmail();
2715 if ( $str === $oldaddr ) {
2716 return Status
::newGood( true );
2719 $type = $oldaddr != '' ?
'changed' : 'set';
2720 $notificationResult = null;
2722 if ( $wgEmailAuthentication ) {
2723 // Send the user an email notifying the user of the change in registered
2724 // email address on their previous email address
2725 if ( $type == 'changed' ) {
2726 $change = $str != '' ?
'changed' : 'removed';
2727 $notificationResult = $this->sendMail(
2728 wfMessage( 'notificationemail_subject_' . $change )->text(),
2729 wfMessage( 'notificationemail_body_' . $change,
2730 $this->getRequest()->getIP(),
2737 $this->setEmail( $str );
2739 if ( $str !== '' && $wgEmailAuthentication ) {
2740 // Send a confirmation request to the new address if needed
2741 $result = $this->sendConfirmationMail( $type );
2743 if ( $notificationResult !== null ) {
2744 $result->merge( $notificationResult );
2747 if ( $result->isGood() ) {
2748 // Say to the caller that a confirmation and notification mail has been sent
2749 $result->value
= 'eauth';
2752 $result = Status
::newGood( true );
2759 * Get the user's real name
2760 * @return string User's real name
2762 public function getRealName() {
2763 if ( !$this->isItemLoaded( 'realname' ) ) {
2767 return $this->mRealName
;
2771 * Set the user's real name
2772 * @param string $str New real name
2774 public function setRealName( $str ) {
2776 $this->mRealName
= $str;
2780 * Get the user's current setting for a given option.
2782 * @param string $oname The option to check
2783 * @param string $defaultOverride A default value returned if the option does not exist
2784 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2785 * @return string|null User's current value for the option
2786 * @see getBoolOption()
2787 * @see getIntOption()
2789 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2790 global $wgHiddenPrefs;
2791 $this->loadOptions();
2793 # We want 'disabled' preferences to always behave as the default value for
2794 # users, even if they have set the option explicitly in their settings (ie they
2795 # set it, and then it was disabled removing their ability to change it). But
2796 # we don't want to erase the preferences in the database in case the preference
2797 # is re-enabled again. So don't touch $mOptions, just override the returned value
2798 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2799 return self
::getDefaultOption( $oname );
2802 if ( array_key_exists( $oname, $this->mOptions
) ) {
2803 return $this->mOptions
[$oname];
2805 return $defaultOverride;
2810 * Get all user's options
2812 * @param int $flags Bitwise combination of:
2813 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2814 * to the default value. (Since 1.25)
2817 public function getOptions( $flags = 0 ) {
2818 global $wgHiddenPrefs;
2819 $this->loadOptions();
2820 $options = $this->mOptions
;
2822 # We want 'disabled' preferences to always behave as the default value for
2823 # users, even if they have set the option explicitly in their settings (ie they
2824 # set it, and then it was disabled removing their ability to change it). But
2825 # we don't want to erase the preferences in the database in case the preference
2826 # is re-enabled again. So don't touch $mOptions, just override the returned value
2827 foreach ( $wgHiddenPrefs as $pref ) {
2828 $default = self
::getDefaultOption( $pref );
2829 if ( $default !== null ) {
2830 $options[$pref] = $default;
2834 if ( $flags & self
::GETOPTIONS_EXCLUDE_DEFAULTS
) {
2835 $options = array_diff_assoc( $options, self
::getDefaultOptions() );
2842 * Get the user's current setting for a given option, as a boolean value.
2844 * @param string $oname The option to check
2845 * @return bool User's current value for the option
2848 public function getBoolOption( $oname ) {
2849 return (bool)$this->getOption( $oname );
2853 * Get the user's current setting for a given option, as an integer value.
2855 * @param string $oname The option to check
2856 * @param int $defaultOverride A default value returned if the option does not exist
2857 * @return int User's current value for the option
2860 public function getIntOption( $oname, $defaultOverride = 0 ) {
2861 $val = $this->getOption( $oname );
2863 $val = $defaultOverride;
2865 return intval( $val );
2869 * Set the given option for a user.
2871 * You need to call saveSettings() to actually write to the database.
2873 * @param string $oname The option to set
2874 * @param mixed $val New value to set
2876 public function setOption( $oname, $val ) {
2877 $this->loadOptions();
2879 // Explicitly NULL values should refer to defaults
2880 if ( is_null( $val ) ) {
2881 $val = self
::getDefaultOption( $oname );
2884 $this->mOptions
[$oname] = $val;
2888 * Get a token stored in the preferences (like the watchlist one),
2889 * resetting it if it's empty (and saving changes).
2891 * @param string $oname The option name to retrieve the token from
2892 * @return string|bool User's current value for the option, or false if this option is disabled.
2893 * @see resetTokenFromOption()
2895 * @deprecated since 1.26 Applications should use the OAuth extension
2897 public function getTokenFromOption( $oname ) {
2898 global $wgHiddenPrefs;
2900 $id = $this->getId();
2901 if ( !$id ||
in_array( $oname, $wgHiddenPrefs ) ) {
2905 $token = $this->getOption( $oname );
2907 // Default to a value based on the user token to avoid space
2908 // wasted on storing tokens for all users. When this option
2909 // is set manually by the user, only then is it stored.
2910 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
2917 * Reset a token stored in the preferences (like the watchlist one).
2918 * *Does not* save user's preferences (similarly to setOption()).
2920 * @param string $oname The option name to reset the token in
2921 * @return string|bool New token value, or false if this option is disabled.
2922 * @see getTokenFromOption()
2925 public function resetTokenFromOption( $oname ) {
2926 global $wgHiddenPrefs;
2927 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2931 $token = MWCryptRand
::generateHex( 40 );
2932 $this->setOption( $oname, $token );
2937 * Return a list of the types of user options currently returned by
2938 * User::getOptionKinds().
2940 * Currently, the option kinds are:
2941 * - 'registered' - preferences which are registered in core MediaWiki or
2942 * by extensions using the UserGetDefaultOptions hook.
2943 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2944 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2945 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2946 * be used by user scripts.
2947 * - 'special' - "preferences" that are not accessible via User::getOptions
2948 * or User::setOptions.
2949 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2950 * These are usually legacy options, removed in newer versions.
2952 * The API (and possibly others) use this function to determine the possible
2953 * option types for validation purposes, so make sure to update this when a
2954 * new option kind is added.
2956 * @see User::getOptionKinds
2957 * @return array Option kinds
2959 public static function listOptionKinds() {
2962 'registered-multiselect',
2963 'registered-checkmatrix',
2971 * Return an associative array mapping preferences keys to the kind of a preference they're
2972 * used for. Different kinds are handled differently when setting or reading preferences.
2974 * See User::listOptionKinds for the list of valid option types that can be provided.
2976 * @see User::listOptionKinds
2977 * @param IContextSource $context
2978 * @param array $options Assoc. array with options keys to check as keys.
2979 * Defaults to $this->mOptions.
2980 * @return array The key => kind mapping data
2982 public function getOptionKinds( IContextSource
$context, $options = null ) {
2983 $this->loadOptions();
2984 if ( $options === null ) {
2985 $options = $this->mOptions
;
2988 $prefs = Preferences
::getPreferences( $this, $context );
2991 // Pull out the "special" options, so they don't get converted as
2992 // multiselect or checkmatrix.
2993 $specialOptions = array_fill_keys( Preferences
::getSaveBlacklist(), true );
2994 foreach ( $specialOptions as $name => $value ) {
2995 unset( $prefs[$name] );
2998 // Multiselect and checkmatrix options are stored in the database with
2999 // one key per option, each having a boolean value. Extract those keys.
3000 $multiselectOptions = [];
3001 foreach ( $prefs as $name => $info ) {
3002 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
3003 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
3004 $opts = HTMLFormField
::flattenOptions( $info['options'] );
3005 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
3007 foreach ( $opts as $value ) {
3008 $multiselectOptions["$prefix$value"] = true;
3011 unset( $prefs[$name] );
3014 $checkmatrixOptions = [];
3015 foreach ( $prefs as $name => $info ) {
3016 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
3017 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
3018 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
3019 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
3020 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
3022 foreach ( $columns as $column ) {
3023 foreach ( $rows as $row ) {
3024 $checkmatrixOptions["$prefix$column-$row"] = true;
3028 unset( $prefs[$name] );
3032 // $value is ignored
3033 foreach ( $options as $key => $value ) {
3034 if ( isset( $prefs[$key] ) ) {
3035 $mapping[$key] = 'registered';
3036 } elseif ( isset( $multiselectOptions[$key] ) ) {
3037 $mapping[$key] = 'registered-multiselect';
3038 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
3039 $mapping[$key] = 'registered-checkmatrix';
3040 } elseif ( isset( $specialOptions[$key] ) ) {
3041 $mapping[$key] = 'special';
3042 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
3043 $mapping[$key] = 'userjs';
3045 $mapping[$key] = 'unused';
3053 * Reset certain (or all) options to the site defaults
3055 * The optional parameter determines which kinds of preferences will be reset.
3056 * Supported values are everything that can be reported by getOptionKinds()
3057 * and 'all', which forces a reset of *all* preferences and overrides everything else.
3059 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
3060 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
3061 * for backwards-compatibility.
3062 * @param IContextSource|null $context Context source used when $resetKinds
3063 * does not contain 'all', passed to getOptionKinds().
3064 * Defaults to RequestContext::getMain() when null.
3066 public function resetOptions(
3067 $resetKinds = [ 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ],
3068 IContextSource
$context = null
3071 $defaultOptions = self
::getDefaultOptions();
3073 if ( !is_array( $resetKinds ) ) {
3074 $resetKinds = [ $resetKinds ];
3077 if ( in_array( 'all', $resetKinds ) ) {
3078 $newOptions = $defaultOptions;
3080 if ( $context === null ) {
3081 $context = RequestContext
::getMain();
3084 $optionKinds = $this->getOptionKinds( $context );
3085 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
3088 // Use default values for the options that should be deleted, and
3089 // copy old values for the ones that shouldn't.
3090 foreach ( $this->mOptions
as $key => $value ) {
3091 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
3092 if ( array_key_exists( $key, $defaultOptions ) ) {
3093 $newOptions[$key] = $defaultOptions[$key];
3096 $newOptions[$key] = $value;
3101 Hooks
::run( 'UserResetAllOptions', [ $this, &$newOptions, $this->mOptions
, $resetKinds ] );
3103 $this->mOptions
= $newOptions;
3104 $this->mOptionsLoaded
= true;
3108 * Get the user's preferred date format.
3109 * @return string User's preferred date format
3111 public function getDatePreference() {
3112 // Important migration for old data rows
3113 if ( is_null( $this->mDatePreference
) ) {
3115 $value = $this->getOption( 'date' );
3116 $map = $wgLang->getDatePreferenceMigrationMap();
3117 if ( isset( $map[$value] ) ) {
3118 $value = $map[$value];
3120 $this->mDatePreference
= $value;
3122 return $this->mDatePreference
;
3126 * Determine based on the wiki configuration and the user's options,
3127 * whether this user must be over HTTPS no matter what.
3131 public function requiresHTTPS() {
3132 global $wgSecureLogin;
3133 if ( !$wgSecureLogin ) {
3136 $https = $this->getBoolOption( 'prefershttps' );
3137 Hooks
::run( 'UserRequiresHTTPS', [ $this, &$https ] );
3139 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
3146 * Get the user preferred stub threshold
3150 public function getStubThreshold() {
3151 global $wgMaxArticleSize; # Maximum article size, in Kb
3152 $threshold = $this->getIntOption( 'stubthreshold' );
3153 if ( $threshold > $wgMaxArticleSize * 1024 ) {
3154 // If they have set an impossible value, disable the preference
3155 // so we can use the parser cache again.
3162 * Get the permissions this user has.
3163 * @return array Array of String permission names
3165 public function getRights() {
3166 if ( is_null( $this->mRights
) ) {
3167 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
3168 Hooks
::run( 'UserGetRights', [ $this, &$this->mRights
] );
3170 // Deny any rights denied by the user's session, unless this
3171 // endpoint has no sessions.
3172 if ( !defined( 'MW_NO_SESSION' ) ) {
3173 $allowedRights = $this->getRequest()->getSession()->getAllowedUserRights();
3174 if ( $allowedRights !== null ) {
3175 $this->mRights
= array_intersect( $this->mRights
, $allowedRights );
3179 // Force reindexation of rights when a hook has unset one of them
3180 $this->mRights
= array_values( array_unique( $this->mRights
) );
3182 // If block disables login, we should also remove any
3183 // extra rights blocked users might have, in case the
3184 // blocked user has a pre-existing session (T129738).
3185 // This is checked here for cases where people only call
3186 // $user->isAllowed(). It is also checked in Title::checkUserBlock()
3187 // to give a better error message in the common case.
3188 $config = RequestContext
::getMain()->getConfig();
3190 $this->isLoggedIn() &&
3191 $config->get( 'BlockDisablesLogin' ) &&
3195 $this->mRights
= array_intersect( $this->mRights
, $anon->getRights() );
3198 return $this->mRights
;
3202 * Get the list of explicit group memberships this user has.
3203 * The implicit * and user groups are not included.
3204 * @return array Array of String internal group names
3206 public function getGroups() {
3208 $this->loadGroups();
3209 return $this->mGroups
;
3213 * Get the list of implicit group memberships this user has.
3214 * This includes all explicit groups, plus 'user' if logged in,
3215 * '*' for all accounts, and autopromoted groups
3216 * @param bool $recache Whether to avoid the cache
3217 * @return array Array of String internal group names
3219 public function getEffectiveGroups( $recache = false ) {
3220 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
3221 $this->mEffectiveGroups
= array_unique( array_merge(
3222 $this->getGroups(), // explicit groups
3223 $this->getAutomaticGroups( $recache ) // implicit groups
3225 // Avoid PHP 7.1 warning of passing $this by reference
3227 // Hook for additional groups
3228 Hooks
::run( 'UserEffectiveGroups', [ &$user, &$this->mEffectiveGroups
] );
3229 // Force reindexation of groups when a hook has unset one of them
3230 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
3232 return $this->mEffectiveGroups
;
3236 * Get the list of implicit group memberships this user has.
3237 * This includes 'user' if logged in, '*' for all accounts,
3238 * and autopromoted groups
3239 * @param bool $recache Whether to avoid the cache
3240 * @return array Array of String internal group names
3242 public function getAutomaticGroups( $recache = false ) {
3243 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
3244 $this->mImplicitGroups
= [ '*' ];
3245 if ( $this->getId() ) {
3246 $this->mImplicitGroups
[] = 'user';
3248 $this->mImplicitGroups
= array_unique( array_merge(
3249 $this->mImplicitGroups
,
3250 Autopromote
::getAutopromoteGroups( $this )
3254 // Assure data consistency with rights/groups,
3255 // as getEffectiveGroups() depends on this function
3256 $this->mEffectiveGroups
= null;
3259 return $this->mImplicitGroups
;
3263 * Returns the groups the user has belonged to.
3265 * The user may still belong to the returned groups. Compare with getGroups().
3267 * The function will not return groups the user had belonged to before MW 1.17
3269 * @return array Names of the groups the user has belonged to.
3271 public function getFormerGroups() {
3274 if ( is_null( $this->mFormerGroups
) ) {
3275 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3276 ?
wfGetDB( DB_MASTER
)
3277 : wfGetDB( DB_REPLICA
);
3278 $res = $db->select( 'user_former_groups',
3280 [ 'ufg_user' => $this->mId
],
3282 $this->mFormerGroups
= [];
3283 foreach ( $res as $row ) {
3284 $this->mFormerGroups
[] = $row->ufg_group
;
3288 return $this->mFormerGroups
;
3292 * Get the user's edit count.
3293 * @return int|null Null for anonymous users
3295 public function getEditCount() {
3296 if ( !$this->getId() ) {
3300 if ( $this->mEditCount
=== null ) {
3301 /* Populate the count, if it has not been populated yet */
3302 $dbr = wfGetDB( DB_REPLICA
);
3303 // check if the user_editcount field has been initialized
3304 $count = $dbr->selectField(
3305 'user', 'user_editcount',
3306 [ 'user_id' => $this->mId
],
3310 if ( $count === null ) {
3311 // it has not been initialized. do so.
3312 $count = $this->initEditCount();
3314 $this->mEditCount
= $count;
3316 return (int)$this->mEditCount
;
3320 * Add the user to the given group.
3321 * This takes immediate effect.
3322 * @param string $group Name of the group to add
3325 public function addGroup( $group ) {
3328 if ( !Hooks
::run( 'UserAddGroup', [ $this, &$group ] ) ) {
3332 $dbw = wfGetDB( DB_MASTER
);
3333 if ( $this->getId() ) {
3334 $dbw->insert( 'user_groups',
3336 'ug_user' => $this->getId(),
3337 'ug_group' => $group,
3343 $this->loadGroups();
3344 $this->mGroups
[] = $group;
3345 // In case loadGroups was not called before, we now have the right twice.
3346 // Get rid of the duplicate.
3347 $this->mGroups
= array_unique( $this->mGroups
);
3349 // Refresh the groups caches, and clear the rights cache so it will be
3350 // refreshed on the next call to $this->getRights().
3351 $this->getEffectiveGroups( true );
3352 $this->mRights
= null;
3354 $this->invalidateCache();
3360 * Remove the user from the given group.
3361 * This takes immediate effect.
3362 * @param string $group Name of the group to remove
3365 public function removeGroup( $group ) {
3367 if ( !Hooks
::run( 'UserRemoveGroup', [ $this, &$group ] ) ) {
3371 $dbw = wfGetDB( DB_MASTER
);
3372 $dbw->delete( 'user_groups',
3374 'ug_user' => $this->getId(),
3375 'ug_group' => $group,
3378 // Remember that the user was in this group
3379 $dbw->insert( 'user_former_groups',
3381 'ufg_user' => $this->getId(),
3382 'ufg_group' => $group,
3388 $this->loadGroups();
3389 $this->mGroups
= array_diff( $this->mGroups
, [ $group ] );
3391 // Refresh the groups caches, and clear the rights cache so it will be
3392 // refreshed on the next call to $this->getRights().
3393 $this->getEffectiveGroups( true );
3394 $this->mRights
= null;
3396 $this->invalidateCache();
3402 * Get whether the user is logged in
3405 public function isLoggedIn() {
3406 return $this->getId() != 0;
3410 * Get whether the user is anonymous
3413 public function isAnon() {
3414 return !$this->isLoggedIn();
3418 * @return bool Whether this user is flagged as being a bot role account
3421 public function isBot() {
3422 if ( in_array( 'bot', $this->getGroups() ) && $this->isAllowed( 'bot' ) ) {
3427 Hooks
::run( "UserIsBot", [ $this, &$isBot ] );
3433 * Check if user is allowed to access a feature / make an action
3435 * @param string ... Permissions to test
3436 * @return bool True if user is allowed to perform *any* of the given actions
3438 public function isAllowedAny() {
3439 $permissions = func_get_args();
3440 foreach ( $permissions as $permission ) {
3441 if ( $this->isAllowed( $permission ) ) {
3450 * @param string ... Permissions to test
3451 * @return bool True if the user is allowed to perform *all* of the given actions
3453 public function isAllowedAll() {
3454 $permissions = func_get_args();
3455 foreach ( $permissions as $permission ) {
3456 if ( !$this->isAllowed( $permission ) ) {
3464 * Internal mechanics of testing a permission
3465 * @param string $action
3468 public function isAllowed( $action = '' ) {
3469 if ( $action === '' ) {
3470 return true; // In the spirit of DWIM
3472 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3473 // by misconfiguration: 0 == 'foo'
3474 return in_array( $action, $this->getRights(), true );
3478 * Check whether to enable recent changes patrol features for this user
3479 * @return bool True or false
3481 public function useRCPatrol() {
3482 global $wgUseRCPatrol;
3483 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3487 * Check whether to enable new pages patrol features for this user
3488 * @return bool True or false
3490 public function useNPPatrol() {
3491 global $wgUseRCPatrol, $wgUseNPPatrol;
3493 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3494 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3499 * Check whether to enable new files patrol features for this user
3500 * @return bool True or false
3502 public function useFilePatrol() {
3503 global $wgUseRCPatrol, $wgUseFilePatrol;
3505 ( $wgUseRCPatrol ||
$wgUseFilePatrol )
3506 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3511 * Get the WebRequest object to use with this object
3513 * @return WebRequest
3515 public function getRequest() {
3516 if ( $this->mRequest
) {
3517 return $this->mRequest
;
3525 * Check the watched status of an article.
3526 * @since 1.22 $checkRights parameter added
3527 * @param Title $title Title of the article to look at
3528 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3529 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3532 public function isWatched( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3533 if ( $title->isWatchable() && ( !$checkRights ||
$this->isAllowed( 'viewmywatchlist' ) ) ) {
3534 return MediaWikiServices
::getInstance()->getWatchedItemStore()->isWatched( $this, $title );
3541 * @since 1.22 $checkRights parameter added
3542 * @param Title $title Title of the article to look at
3543 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3544 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3546 public function addWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3547 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3548 MediaWikiServices
::getInstance()->getWatchedItemStore()->addWatchBatchForUser(
3550 [ $title->getSubjectPage(), $title->getTalkPage() ]
3553 $this->invalidateCache();
3557 * Stop watching an article.
3558 * @since 1.22 $checkRights parameter added
3559 * @param Title $title Title of the article to look at
3560 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3561 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3563 public function removeWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3564 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3565 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
3566 $store->removeWatch( $this, $title->getSubjectPage() );
3567 $store->removeWatch( $this, $title->getTalkPage() );
3569 $this->invalidateCache();
3573 * Clear the user's notification timestamp for the given title.
3574 * If e-notif e-mails are on, they will receive notification mails on
3575 * the next change of the page if it's watched etc.
3576 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3577 * @param Title $title Title of the article to look at
3578 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3580 public function clearNotification( &$title, $oldid = 0 ) {
3581 global $wgUseEnotif, $wgShowUpdatedMarker;
3583 // Do nothing if the database is locked to writes
3584 if ( wfReadOnly() ) {
3588 // Do nothing if not allowed to edit the watchlist
3589 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3593 // If we're working on user's talk page, we should update the talk page message indicator
3594 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3595 // Avoid PHP 7.1 warning of passing $this by reference
3597 if ( !Hooks
::run( 'UserClearNewTalkNotification', [ &$user, $oldid ] ) ) {
3601 // Try to update the DB post-send and only if needed...
3602 DeferredUpdates
::addCallableUpdate( function() use ( $title, $oldid ) {
3603 if ( !$this->getNewtalk() ) {
3604 return; // no notifications to clear
3607 // Delete the last notifications (they stack up)
3608 $this->setNewtalk( false );
3610 // If there is a new, unseen, revision, use its timestamp
3612 ?
$title->getNextRevisionID( $oldid, Title
::GAID_FOR_UPDATE
)
3615 $this->setNewtalk( true, Revision
::newFromId( $nextid ) );
3620 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3624 if ( $this->isAnon() ) {
3625 // Nothing else to do...
3629 // Only update the timestamp if the page is being watched.
3630 // The query to find out if it is watched is cached both in memcached and per-invocation,
3631 // and when it does have to be executed, it can be on a replica DB
3632 // If this is the user's newtalk page, we always update the timestamp
3634 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3638 MediaWikiServices
::getInstance()->getWatchedItemStore()
3639 ->resetNotificationTimestamp( $this, $title, $force, $oldid );
3643 * Resets all of the given user's page-change notification timestamps.
3644 * If e-notif e-mails are on, they will receive notification mails on
3645 * the next change of any watched page.
3646 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3648 public function clearAllNotifications() {
3649 global $wgUseEnotif, $wgShowUpdatedMarker;
3650 // Do nothing if not allowed to edit the watchlist
3651 if ( wfReadOnly() ||
!$this->isAllowed( 'editmywatchlist' ) ) {
3655 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3656 $this->setNewtalk( false );
3660 $id = $this->getId();
3665 $dbw = wfGetDB( DB_MASTER
);
3666 $asOfTimes = array_unique( $dbw->selectFieldValues(
3668 'wl_notificationtimestamp',
3669 [ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ],
3671 [ 'ORDER BY' => 'wl_notificationtimestamp DESC', 'LIMIT' => 500 ]
3673 if ( !$asOfTimes ) {
3676 // Immediately update the most recent touched rows, which hopefully covers what
3677 // the user sees on the watchlist page before pressing "mark all pages visited"....
3680 [ 'wl_notificationtimestamp' => null ],
3681 [ 'wl_user' => $id, 'wl_notificationtimestamp' => $asOfTimes ],
3684 // ...and finish the older ones in a post-send update with lag checks...
3685 DeferredUpdates
::addUpdate( new AutoCommitUpdate(
3688 function () use ( $dbw, $id ) {
3689 global $wgUpdateRowsPerQuery;
3691 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
3692 $ticket = $lbFactory->getEmptyTransactionTicket( __METHOD__
);
3693 $asOfTimes = array_unique( $dbw->selectFieldValues(
3695 'wl_notificationtimestamp',
3696 [ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ],
3699 foreach ( array_chunk( $asOfTimes, $wgUpdateRowsPerQuery ) as $asOfTimeBatch ) {
3702 [ 'wl_notificationtimestamp' => null ],
3703 [ 'wl_user' => $id, 'wl_notificationtimestamp' => $asOfTimeBatch ],
3706 $lbFactory->commitAndWaitForReplication( __METHOD__
, $ticket );
3710 // We also need to clear here the "you have new message" notification for the own
3711 // user_talk page; it's cleared one page view later in WikiPage::doViewUpdates().
3715 * Set a cookie on the user's client. Wrapper for
3716 * WebResponse::setCookie
3717 * @deprecated since 1.27
3718 * @param string $name Name of the cookie to set
3719 * @param string $value Value to set
3720 * @param int $exp Expiration time, as a UNIX time value;
3721 * if 0 or not specified, use the default $wgCookieExpiration
3722 * @param bool $secure
3723 * true: Force setting the secure attribute when setting the cookie
3724 * false: Force NOT setting the secure attribute when setting the cookie
3725 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3726 * @param array $params Array of options sent passed to WebResponse::setcookie()
3727 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3730 protected function setCookie(
3731 $name, $value, $exp = 0, $secure = null, $params = [], $request = null
3733 wfDeprecated( __METHOD__
, '1.27' );
3734 if ( $request === null ) {
3735 $request = $this->getRequest();
3737 $params['secure'] = $secure;
3738 $request->response()->setCookie( $name, $value, $exp, $params );
3742 * Clear a cookie on the user's client
3743 * @deprecated since 1.27
3744 * @param string $name Name of the cookie to clear
3745 * @param bool $secure
3746 * true: Force setting the secure attribute when setting the cookie
3747 * false: Force NOT setting the secure attribute when setting the cookie
3748 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3749 * @param array $params Array of options sent passed to WebResponse::setcookie()
3751 protected function clearCookie( $name, $secure = null, $params = [] ) {
3752 wfDeprecated( __METHOD__
, '1.27' );
3753 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3757 * Set an extended login cookie on the user's client. The expiry of the cookie
3758 * is controlled by the $wgExtendedLoginCookieExpiration configuration
3761 * @see User::setCookie
3763 * @deprecated since 1.27
3764 * @param string $name Name of the cookie to set
3765 * @param string $value Value to set
3766 * @param bool $secure
3767 * true: Force setting the secure attribute when setting the cookie
3768 * false: Force NOT setting the secure attribute when setting the cookie
3769 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3771 protected function setExtendedLoginCookie( $name, $value, $secure ) {
3772 global $wgExtendedLoginCookieExpiration, $wgCookieExpiration;
3774 wfDeprecated( __METHOD__
, '1.27' );
3777 $exp +
= $wgExtendedLoginCookieExpiration !== null
3778 ?
$wgExtendedLoginCookieExpiration
3779 : $wgCookieExpiration;
3781 $this->setCookie( $name, $value, $exp, $secure );
3785 * Persist this user's session (e.g. set cookies)
3787 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3789 * @param bool $secure Whether to force secure/insecure cookies or use default
3790 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3792 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3794 if ( 0 == $this->mId
) {
3798 $session = $this->getRequest()->getSession();
3799 if ( $request && $session->getRequest() !== $request ) {
3800 $session = $session->sessionWithRequest( $request );
3802 $delay = $session->delaySave();
3804 if ( !$session->getUser()->equals( $this ) ) {
3805 if ( !$session->canSetUser() ) {
3806 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3807 ->warning( __METHOD__
.
3808 ": Cannot save user \"$this\" to a user \"{$session->getUser()}\"'s immutable session"
3812 $session->setUser( $this );
3815 $session->setRememberUser( $rememberMe );
3816 if ( $secure !== null ) {
3817 $session->setForceHTTPS( $secure );
3820 $session->persist();
3822 ScopedCallback
::consume( $delay );
3826 * Log this user out.
3828 public function logout() {
3829 // Avoid PHP 7.1 warning of passing $this by reference
3831 if ( Hooks
::run( 'UserLogout', [ &$user ] ) ) {
3837 * Clear the user's session, and reset the instance cache.
3840 public function doLogout() {
3841 $session = $this->getRequest()->getSession();
3842 if ( !$session->canSetUser() ) {
3843 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3844 ->warning( __METHOD__
. ": Cannot log out of an immutable session" );
3845 $error = 'immutable';
3846 } elseif ( !$session->getUser()->equals( $this ) ) {
3847 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3848 ->warning( __METHOD__
.
3849 ": Cannot log user \"$this\" out of a user \"{$session->getUser()}\"'s session"
3851 // But we still may as well make this user object anon
3852 $this->clearInstanceCache( 'defaults' );
3853 $error = 'wronguser';
3855 $this->clearInstanceCache( 'defaults' );
3856 $delay = $session->delaySave();
3857 $session->unpersist(); // Clear cookies (T127436)
3858 $session->setLoggedOutTimestamp( time() );
3859 $session->setUser( new User
);
3860 $session->set( 'wsUserID', 0 ); // Other code expects this
3861 $session->resetAllTokens();
3862 ScopedCallback
::consume( $delay );
3865 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authevents' )->info( 'Logout', [
3866 'event' => 'logout',
3867 'successful' => $error === false,
3868 'status' => $error ?
: 'success',
3873 * Save this user's settings into the database.
3874 * @todo Only rarely do all these fields need to be set!
3876 public function saveSettings() {
3877 if ( wfReadOnly() ) {
3878 // @TODO: caller should deal with this instead!
3879 // This should really just be an exception.
3880 MWExceptionHandler
::logException( new DBExpectedError(
3882 "Could not update user with ID '{$this->mId}'; DB is read-only."
3888 if ( 0 == $this->mId
) {
3892 // Get a new user_touched that is higher than the old one.
3893 // This will be used for a CAS check as a last-resort safety
3894 // check against race conditions and replica DB lag.
3895 $newTouched = $this->newTouchedTimestamp();
3897 $dbw = wfGetDB( DB_MASTER
);
3898 $dbw->update( 'user',
3900 'user_name' => $this->mName
,
3901 'user_real_name' => $this->mRealName
,
3902 'user_email' => $this->mEmail
,
3903 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3904 'user_touched' => $dbw->timestamp( $newTouched ),
3905 'user_token' => strval( $this->mToken
),
3906 'user_email_token' => $this->mEmailToken
,
3907 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
3908 ], $this->makeUpdateConditions( $dbw, [ /* WHERE */
3909 'user_id' => $this->mId
,
3913 if ( !$dbw->affectedRows() ) {
3914 // Maybe the problem was a missed cache update; clear it to be safe
3915 $this->clearSharedCache( 'refresh' );
3916 // User was changed in the meantime or loaded with stale data
3917 $from = ( $this->queryFlagsUsed
& self
::READ_LATEST
) ?
'master' : 'replica';
3918 throw new MWException(
3919 "CAS update failed on user_touched for user ID '{$this->mId}' (read from $from);" .
3920 " the version of the user to be saved is older than the current version."
3924 $this->mTouched
= $newTouched;
3925 $this->saveOptions();
3927 Hooks
::run( 'UserSaveSettings', [ $this ] );
3928 $this->clearSharedCache();
3929 $this->getUserPage()->invalidateCache();
3933 * If only this user's username is known, and it exists, return the user ID.
3935 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
3938 public function idForName( $flags = 0 ) {
3939 $s = trim( $this->getName() );
3944 $db = ( ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
)
3945 ?
wfGetDB( DB_MASTER
)
3946 : wfGetDB( DB_REPLICA
);
3948 $options = ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
)
3949 ?
[ 'LOCK IN SHARE MODE' ]
3952 $id = $db->selectField( 'user',
3953 'user_id', [ 'user_name' => $s ], __METHOD__
, $options );
3959 * Add a user to the database, return the user object
3961 * @param string $name Username to add
3962 * @param array $params Array of Strings Non-default parameters to save to
3963 * the database as user_* fields:
3964 * - email: The user's email address.
3965 * - email_authenticated: The email authentication timestamp.
3966 * - real_name: The user's real name.
3967 * - options: An associative array of non-default options.
3968 * - token: Random authentication token. Do not set.
3969 * - registration: Registration timestamp. Do not set.
3971 * @return User|null User object, or null if the username already exists.
3973 public static function createNew( $name, $params = [] ) {
3974 foreach ( [ 'password', 'newpassword', 'newpass_time', 'password_expires' ] as $field ) {
3975 if ( isset( $params[$field] ) ) {
3976 wfDeprecated( __METHOD__
. " with param '$field'", '1.27' );
3977 unset( $params[$field] );
3983 $user->setToken(); // init token
3984 if ( isset( $params['options'] ) ) {
3985 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
3986 unset( $params['options'] );
3988 $dbw = wfGetDB( DB_MASTER
);
3989 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3991 $noPass = PasswordFactory
::newInvalidPassword()->toString();
3994 'user_id' => $seqVal,
3995 'user_name' => $name,
3996 'user_password' => $noPass,
3997 'user_newpassword' => $noPass,
3998 'user_email' => $user->mEmail
,
3999 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
4000 'user_real_name' => $user->mRealName
,
4001 'user_token' => strval( $user->mToken
),
4002 'user_registration' => $dbw->timestamp( $user->mRegistration
),
4003 'user_editcount' => 0,
4004 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
4006 foreach ( $params as $name => $value ) {
4007 $fields["user_$name"] = $value;
4009 $dbw->insert( 'user', $fields, __METHOD__
, [ 'IGNORE' ] );
4010 if ( $dbw->affectedRows() ) {
4011 $newUser = User
::newFromId( $dbw->insertId() );
4019 * Add this existing user object to the database. If the user already
4020 * exists, a fatal status object is returned, and the user object is
4021 * initialised with the data from the database.
4023 * Previously, this function generated a DB error due to a key conflict
4024 * if the user already existed. Many extension callers use this function
4025 * in code along the lines of:
4027 * $user = User::newFromName( $name );
4028 * if ( !$user->isLoggedIn() ) {
4029 * $user->addToDatabase();
4031 * // do something with $user...
4033 * However, this was vulnerable to a race condition (bug 16020). By
4034 * initialising the user object if the user exists, we aim to support this
4035 * calling sequence as far as possible.
4037 * Note that if the user exists, this function will acquire a write lock,
4038 * so it is still advisable to make the call conditional on isLoggedIn(),
4039 * and to commit the transaction after calling.
4041 * @throws MWException
4044 public function addToDatabase() {
4046 if ( !$this->mToken
) {
4047 $this->setToken(); // init token
4050 $this->mTouched
= $this->newTouchedTimestamp();
4052 $noPass = PasswordFactory
::newInvalidPassword()->toString();
4054 $dbw = wfGetDB( DB_MASTER
);
4055 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
4056 $dbw->insert( 'user',
4058 'user_id' => $seqVal,
4059 'user_name' => $this->mName
,
4060 'user_password' => $noPass,
4061 'user_newpassword' => $noPass,
4062 'user_email' => $this->mEmail
,
4063 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
4064 'user_real_name' => $this->mRealName
,
4065 'user_token' => strval( $this->mToken
),
4066 'user_registration' => $dbw->timestamp( $this->mRegistration
),
4067 'user_editcount' => 0,
4068 'user_touched' => $dbw->timestamp( $this->mTouched
),
4072 if ( !$dbw->affectedRows() ) {
4073 // Use locking reads to bypass any REPEATABLE-READ snapshot.
4074 $this->mId
= $dbw->selectField(
4077 [ 'user_name' => $this->mName
],
4079 [ 'LOCK IN SHARE MODE' ]
4083 if ( $this->loadFromDatabase( self
::READ_LOCKING
) ) {
4088 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
4089 "to insert user '{$this->mName}' row, but it was not present in select!" );
4091 return Status
::newFatal( 'userexists' );
4093 $this->mId
= $dbw->insertId();
4094 self
::$idCacheByName[$this->mName
] = $this->mId
;
4096 // Clear instance cache other than user table data, which is already accurate
4097 $this->clearInstanceCache();
4099 $this->saveOptions();
4100 return Status
::newGood();
4104 * If this user is logged-in and blocked,
4105 * block any IP address they've successfully logged in from.
4106 * @return bool A block was spread
4108 public function spreadAnyEditBlock() {
4109 if ( $this->isLoggedIn() && $this->isBlocked() ) {
4110 return $this->spreadBlock();
4117 * If this (non-anonymous) user is blocked,
4118 * block the IP address they've successfully logged in from.
4119 * @return bool A block was spread
4121 protected function spreadBlock() {
4122 wfDebug( __METHOD__
. "()\n" );
4124 if ( $this->mId
== 0 ) {
4128 $userblock = Block
::newFromTarget( $this->getName() );
4129 if ( !$userblock ) {
4133 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
4137 * Get whether the user is explicitly blocked from account creation.
4138 * @return bool|Block
4140 public function isBlockedFromCreateAccount() {
4141 $this->getBlockedStatus();
4142 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
4143 return $this->mBlock
;
4146 # bug 13611: if the IP address the user is trying to create an account from is
4147 # blocked with createaccount disabled, prevent new account creation there even
4148 # when the user is logged in
4149 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
4150 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
4152 return $this->mBlockedFromCreateAccount
instanceof Block
4153 && $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
4154 ?
$this->mBlockedFromCreateAccount
4159 * Get whether the user is blocked from using Special:Emailuser.
4162 public function isBlockedFromEmailuser() {
4163 $this->getBlockedStatus();
4164 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
4168 * Get whether the user is allowed to create an account.
4171 public function isAllowedToCreateAccount() {
4172 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
4176 * Get this user's personal page title.
4178 * @return Title User's personal page title
4180 public function getUserPage() {
4181 return Title
::makeTitle( NS_USER
, $this->getName() );
4185 * Get this user's talk page title.
4187 * @return Title User's talk page title
4189 public function getTalkPage() {
4190 $title = $this->getUserPage();
4191 return $title->getTalkPage();
4195 * Determine whether the user is a newbie. Newbies are either
4196 * anonymous IPs, or the most recently created accounts.
4199 public function isNewbie() {
4200 return !$this->isAllowed( 'autoconfirmed' );
4204 * Check to see if the given clear-text password is one of the accepted passwords
4205 * @deprecated since 1.27, use AuthManager instead
4206 * @param string $password User password
4207 * @return bool True if the given password is correct, otherwise False
4209 public function checkPassword( $password ) {
4210 $manager = AuthManager
::singleton();
4211 $reqs = AuthenticationRequest
::loadRequestsFromSubmission(
4212 $manager->getAuthenticationRequests( AuthManager
::ACTION_LOGIN
),
4214 'username' => $this->getName(),
4215 'password' => $password,
4218 $res = AuthManager
::singleton()->beginAuthentication( $reqs, 'null:' );
4219 switch ( $res->status
) {
4220 case AuthenticationResponse
::PASS
:
4222 case AuthenticationResponse
::FAIL
:
4223 // Hope it's not a PreAuthenticationProvider that failed...
4224 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
4225 ->info( __METHOD__
. ': Authentication failed: ' . $res->message
->plain() );
4228 throw new BadMethodCallException(
4229 'AuthManager returned a response unsupported by ' . __METHOD__
4235 * Check if the given clear-text password matches the temporary password
4236 * sent by e-mail for password reset operations.
4238 * @deprecated since 1.27, use AuthManager instead
4239 * @param string $plaintext
4240 * @return bool True if matches, false otherwise
4242 public function checkTemporaryPassword( $plaintext ) {
4243 // Can't check the temporary password individually.
4244 return $this->checkPassword( $plaintext );
4248 * Initialize (if necessary) and return a session token value
4249 * which can be used in edit forms to show that the user's
4250 * login credentials aren't being hijacked with a foreign form
4254 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4255 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4256 * @return MediaWiki\Session\Token The new edit token
4258 public function getEditTokenObject( $salt = '', $request = null ) {
4259 if ( $this->isAnon() ) {
4260 return new LoggedOutEditToken();
4264 $request = $this->getRequest();
4266 return $request->getSession()->getToken( $salt );
4270 * Initialize (if necessary) and return a session token value
4271 * which can be used in edit forms to show that the user's
4272 * login credentials aren't being hijacked with a foreign form
4275 * The $salt for 'edit' and 'csrf' tokens is the default (empty string).
4278 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4279 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4280 * @return string The new edit token
4282 public function getEditToken( $salt = '', $request = null ) {
4283 return $this->getEditTokenObject( $salt, $request )->toString();
4287 * Get the embedded timestamp from a token.
4288 * @deprecated since 1.27, use \MediaWiki\Session\Token::getTimestamp instead.
4289 * @param string $val Input token
4292 public static function getEditTokenTimestamp( $val ) {
4293 wfDeprecated( __METHOD__
, '1.27' );
4294 return MediaWiki\Session\Token
::getTimestamp( $val );
4298 * Check given value against the token value stored in the session.
4299 * A match should confirm that the form was submitted from the
4300 * user's own login session, not a form submission from a third-party
4303 * @param string $val Input value to compare
4304 * @param string $salt Optional function-specific data for hashing
4305 * @param WebRequest|null $request Object to use or null to use $wgRequest
4306 * @param int $maxage Fail tokens older than this, in seconds
4307 * @return bool Whether the token matches
4309 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4310 return $this->getEditTokenObject( $salt, $request )->match( $val, $maxage );
4314 * Check given value against the token value stored in the session,
4315 * ignoring the suffix.
4317 * @param string $val Input value to compare
4318 * @param string $salt Optional function-specific data for hashing
4319 * @param WebRequest|null $request Object to use or null to use $wgRequest
4320 * @param int $maxage Fail tokens older than this, in seconds
4321 * @return bool Whether the token matches
4323 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4324 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . Token
::SUFFIX
;
4325 return $this->matchEditToken( $val, $salt, $request, $maxage );
4329 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4330 * mail to the user's given address.
4332 * @param string $type Message to send, either "created", "changed" or "set"
4335 public function sendConfirmationMail( $type = 'created' ) {
4337 $expiration = null; // gets passed-by-ref and defined in next line.
4338 $token = $this->confirmationToken( $expiration );
4339 $url = $this->confirmationTokenUrl( $token );
4340 $invalidateURL = $this->invalidationTokenUrl( $token );
4341 $this->saveSettings();
4343 if ( $type == 'created' ||
$type === false ) {
4344 $message = 'confirmemail_body';
4345 } elseif ( $type === true ) {
4346 $message = 'confirmemail_body_changed';
4348 // Messages: confirmemail_body_changed, confirmemail_body_set
4349 $message = 'confirmemail_body_' . $type;
4352 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4353 wfMessage( $message,
4354 $this->getRequest()->getIP(),
4357 $wgLang->userTimeAndDate( $expiration, $this ),
4359 $wgLang->userDate( $expiration, $this ),
4360 $wgLang->userTime( $expiration, $this ) )->text() );
4364 * Send an e-mail to this user's account. Does not check for
4365 * confirmed status or validity.
4367 * @param string $subject Message subject
4368 * @param string $body Message body
4369 * @param User|null $from Optional sending user; if unspecified, default
4370 * $wgPasswordSender will be used.
4371 * @param string $replyto Reply-To address
4374 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4375 global $wgPasswordSender;
4377 if ( $from instanceof User
) {
4378 $sender = MailAddress
::newFromUser( $from );
4380 $sender = new MailAddress( $wgPasswordSender,
4381 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4383 $to = MailAddress
::newFromUser( $this );
4385 return UserMailer
::send( $to, $sender, $subject, $body, [
4386 'replyTo' => $replyto,
4391 * Generate, store, and return a new e-mail confirmation code.
4392 * A hash (unsalted, since it's used as a key) is stored.
4394 * @note Call saveSettings() after calling this function to commit
4395 * this change to the database.
4397 * @param string &$expiration Accepts the expiration time
4398 * @return string New token
4400 protected function confirmationToken( &$expiration ) {
4401 global $wgUserEmailConfirmationTokenExpiry;
4403 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4404 $expiration = wfTimestamp( TS_MW
, $expires );
4406 $token = MWCryptRand
::generateHex( 32 );
4407 $hash = md5( $token );
4408 $this->mEmailToken
= $hash;
4409 $this->mEmailTokenExpires
= $expiration;
4414 * Return a URL the user can use to confirm their email address.
4415 * @param string $token Accepts the email confirmation token
4416 * @return string New token URL
4418 protected function confirmationTokenUrl( $token ) {
4419 return $this->getTokenUrl( 'ConfirmEmail', $token );
4423 * Return a URL the user can use to invalidate their email address.
4424 * @param string $token Accepts the email confirmation token
4425 * @return string New token URL
4427 protected function invalidationTokenUrl( $token ) {
4428 return $this->getTokenUrl( 'InvalidateEmail', $token );
4432 * Internal function to format the e-mail validation/invalidation URLs.
4433 * This uses a quickie hack to use the
4434 * hardcoded English names of the Special: pages, for ASCII safety.
4436 * @note Since these URLs get dropped directly into emails, using the
4437 * short English names avoids insanely long URL-encoded links, which
4438 * also sometimes can get corrupted in some browsers/mailers
4439 * (bug 6957 with Gmail and Internet Explorer).
4441 * @param string $page Special page
4442 * @param string $token Token
4443 * @return string Formatted URL
4445 protected function getTokenUrl( $page, $token ) {
4446 // Hack to bypass localization of 'Special:'
4447 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4448 return $title->getCanonicalURL();
4452 * Mark the e-mail address confirmed.
4454 * @note Call saveSettings() after calling this function to commit the change.
4458 public function confirmEmail() {
4459 // Check if it's already confirmed, so we don't touch the database
4460 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4461 if ( !$this->isEmailConfirmed() ) {
4462 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4463 Hooks
::run( 'ConfirmEmailComplete', [ $this ] );
4469 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4470 * address if it was already confirmed.
4472 * @note Call saveSettings() after calling this function to commit the change.
4473 * @return bool Returns true
4475 public function invalidateEmail() {
4477 $this->mEmailToken
= null;
4478 $this->mEmailTokenExpires
= null;
4479 $this->setEmailAuthenticationTimestamp( null );
4481 Hooks
::run( 'InvalidateEmailComplete', [ $this ] );
4486 * Set the e-mail authentication timestamp.
4487 * @param string $timestamp TS_MW timestamp
4489 public function setEmailAuthenticationTimestamp( $timestamp ) {
4491 $this->mEmailAuthenticated
= $timestamp;
4492 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
4496 * Is this user allowed to send e-mails within limits of current
4497 * site configuration?
4500 public function canSendEmail() {
4501 global $wgEnableEmail, $wgEnableUserEmail;
4502 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4505 $canSend = $this->isEmailConfirmed();
4506 // Avoid PHP 7.1 warning of passing $this by reference
4508 Hooks
::run( 'UserCanSendEmail', [ &$user, &$canSend ] );
4513 * Is this user allowed to receive e-mails within limits of current
4514 * site configuration?
4517 public function canReceiveEmail() {
4518 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4522 * Is this user's e-mail address valid-looking and confirmed within
4523 * limits of the current site configuration?
4525 * @note If $wgEmailAuthentication is on, this may require the user to have
4526 * confirmed their address by returning a code or using a password
4527 * sent to the address from the wiki.
4531 public function isEmailConfirmed() {
4532 global $wgEmailAuthentication;
4534 // Avoid PHP 7.1 warning of passing $this by reference
4537 if ( Hooks
::run( 'EmailConfirmed', [ &$user, &$confirmed ] ) ) {
4538 if ( $this->isAnon() ) {
4541 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4544 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4554 * Check whether there is an outstanding request for e-mail confirmation.
4557 public function isEmailConfirmationPending() {
4558 global $wgEmailAuthentication;
4559 return $wgEmailAuthentication &&
4560 !$this->isEmailConfirmed() &&
4561 $this->mEmailToken
&&
4562 $this->mEmailTokenExpires
> wfTimestamp();
4566 * Get the timestamp of account creation.
4568 * @return string|bool|null Timestamp of account creation, false for
4569 * non-existent/anonymous user accounts, or null if existing account
4570 * but information is not in database.
4572 public function getRegistration() {
4573 if ( $this->isAnon() ) {
4577 return $this->mRegistration
;
4581 * Get the timestamp of the first edit
4583 * @return string|bool Timestamp of first edit, or false for
4584 * non-existent/anonymous user accounts.
4586 public function getFirstEditTimestamp() {
4587 if ( $this->getId() == 0 ) {
4588 return false; // anons
4590 $dbr = wfGetDB( DB_REPLICA
);
4591 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4592 [ 'rev_user' => $this->getId() ],
4594 [ 'ORDER BY' => 'rev_timestamp ASC' ]
4597 return false; // no edits
4599 return wfTimestamp( TS_MW
, $time );
4603 * Get the permissions associated with a given list of groups
4605 * @param array $groups Array of Strings List of internal group names
4606 * @return array Array of Strings List of permission key names for given groups combined
4608 public static function getGroupPermissions( $groups ) {
4609 global $wgGroupPermissions, $wgRevokePermissions;
4611 // grant every granted permission first
4612 foreach ( $groups as $group ) {
4613 if ( isset( $wgGroupPermissions[$group] ) ) {
4614 $rights = array_merge( $rights,
4615 // array_filter removes empty items
4616 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4619 // now revoke the revoked permissions
4620 foreach ( $groups as $group ) {
4621 if ( isset( $wgRevokePermissions[$group] ) ) {
4622 $rights = array_diff( $rights,
4623 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4626 return array_unique( $rights );
4630 * Get all the groups who have a given permission
4632 * @param string $role Role to check
4633 * @return array Array of Strings List of internal group names with the given permission
4635 public static function getGroupsWithPermission( $role ) {
4636 global $wgGroupPermissions;
4637 $allowedGroups = [];
4638 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4639 if ( self
::groupHasPermission( $group, $role ) ) {
4640 $allowedGroups[] = $group;
4643 return $allowedGroups;
4647 * Check, if the given group has the given permission
4649 * If you're wanting to check whether all users have a permission, use
4650 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4654 * @param string $group Group to check
4655 * @param string $role Role to check
4658 public static function groupHasPermission( $group, $role ) {
4659 global $wgGroupPermissions, $wgRevokePermissions;
4660 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4661 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4665 * Check if all users may be assumed to have the given permission
4667 * We generally assume so if the right is granted to '*' and isn't revoked
4668 * on any group. It doesn't attempt to take grants or other extension
4669 * limitations on rights into account in the general case, though, as that
4670 * would require it to always return false and defeat the purpose.
4671 * Specifically, session-based rights restrictions (such as OAuth or bot
4672 * passwords) are applied based on the current session.
4675 * @param string $right Right to check
4678 public static function isEveryoneAllowed( $right ) {
4679 global $wgGroupPermissions, $wgRevokePermissions;
4682 // Use the cached results, except in unit tests which rely on
4683 // being able change the permission mid-request
4684 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4685 return $cache[$right];
4688 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4689 $cache[$right] = false;
4693 // If it's revoked anywhere, then everyone doesn't have it
4694 foreach ( $wgRevokePermissions as $rights ) {
4695 if ( isset( $rights[$right] ) && $rights[$right] ) {
4696 $cache[$right] = false;
4701 // Remove any rights that aren't allowed to the global-session user,
4702 // unless there are no sessions for this endpoint.
4703 if ( !defined( 'MW_NO_SESSION' ) ) {
4704 $allowedRights = SessionManager
::getGlobalSession()->getAllowedUserRights();
4705 if ( $allowedRights !== null && !in_array( $right, $allowedRights, true ) ) {
4706 $cache[$right] = false;
4711 // Allow extensions to say false
4712 if ( !Hooks
::run( 'UserIsEveryoneAllowed', [ $right ] ) ) {
4713 $cache[$right] = false;
4717 $cache[$right] = true;
4722 * Get the localized descriptive name for a group, if it exists
4724 * @param string $group Internal group name
4725 * @return string Localized descriptive group name
4727 public static function getGroupName( $group ) {
4728 $msg = wfMessage( "group-$group" );
4729 return $msg->isBlank() ?
$group : $msg->text();
4733 * Get the localized descriptive name for a member of a group, if it exists
4735 * @param string $group Internal group name
4736 * @param string $username Username for gender (since 1.19)
4737 * @return string Localized name for group member
4739 public static function getGroupMember( $group, $username = '#' ) {
4740 $msg = wfMessage( "group-$group-member", $username );
4741 return $msg->isBlank() ?
$group : $msg->text();
4745 * Return the set of defined explicit groups.
4746 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4747 * are not included, as they are defined automatically, not in the database.
4748 * @return array Array of internal group names
4750 public static function getAllGroups() {
4751 global $wgGroupPermissions, $wgRevokePermissions;
4753 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4754 self
::getImplicitGroups()
4759 * Get a list of all available permissions.
4760 * @return string[] Array of permission names
4762 public static function getAllRights() {
4763 if ( self
::$mAllRights === false ) {
4764 global $wgAvailableRights;
4765 if ( count( $wgAvailableRights ) ) {
4766 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
4768 self
::$mAllRights = self
::$mCoreRights;
4770 Hooks
::run( 'UserGetAllRights', [ &self
::$mAllRights ] );
4772 return self
::$mAllRights;
4776 * Get a list of implicit groups
4777 * @return array Array of Strings Array of internal group names
4779 public static function getImplicitGroups() {
4780 global $wgImplicitGroups;
4782 $groups = $wgImplicitGroups;
4783 # Deprecated, use $wgImplicitGroups instead
4784 Hooks
::run( 'UserGetImplicitGroups', [ &$groups ], '1.25' );
4790 * Get the title of a page describing a particular group
4792 * @param string $group Internal group name
4793 * @return Title|bool Title of the page if it exists, false otherwise
4795 public static function getGroupPage( $group ) {
4796 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4797 if ( $msg->exists() ) {
4798 $title = Title
::newFromText( $msg->text() );
4799 if ( is_object( $title ) ) {
4807 * Create a link to the group in HTML, if available;
4808 * else return the group name.
4810 * @param string $group Internal name of the group
4811 * @param string $text The text of the link
4812 * @return string HTML link to the group
4814 public static function makeGroupLinkHTML( $group, $text = '' ) {
4815 if ( $text == '' ) {
4816 $text = self
::getGroupName( $group );
4818 $title = self
::getGroupPage( $group );
4820 return Linker
::link( $title, htmlspecialchars( $text ) );
4822 return htmlspecialchars( $text );
4827 * Create a link to the group in Wikitext, if available;
4828 * else return the group name.
4830 * @param string $group Internal name of the group
4831 * @param string $text The text of the link
4832 * @return string Wikilink to the group
4834 public static function makeGroupLinkWiki( $group, $text = '' ) {
4835 if ( $text == '' ) {
4836 $text = self
::getGroupName( $group );
4838 $title = self
::getGroupPage( $group );
4840 $page = $title->getFullText();
4841 return "[[$page|$text]]";
4848 * Returns an array of the groups that a particular group can add/remove.
4850 * @param string $group The group to check for whether it can add/remove
4851 * @return array Array( 'add' => array( addablegroups ),
4852 * 'remove' => array( removablegroups ),
4853 * 'add-self' => array( addablegroups to self),
4854 * 'remove-self' => array( removable groups from self) )
4856 public static function changeableByGroup( $group ) {
4857 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4866 if ( empty( $wgAddGroups[$group] ) ) {
4867 // Don't add anything to $groups
4868 } elseif ( $wgAddGroups[$group] === true ) {
4869 // You get everything
4870 $groups['add'] = self
::getAllGroups();
4871 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4872 $groups['add'] = $wgAddGroups[$group];
4875 // Same thing for remove
4876 if ( empty( $wgRemoveGroups[$group] ) ) {
4878 } elseif ( $wgRemoveGroups[$group] === true ) {
4879 $groups['remove'] = self
::getAllGroups();
4880 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4881 $groups['remove'] = $wgRemoveGroups[$group];
4884 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4885 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4886 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4887 if ( is_int( $key ) ) {
4888 $wgGroupsAddToSelf['user'][] = $value;
4893 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
4894 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4895 if ( is_int( $key ) ) {
4896 $wgGroupsRemoveFromSelf['user'][] = $value;
4901 // Now figure out what groups the user can add to him/herself
4902 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4904 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4905 // No idea WHY this would be used, but it's there
4906 $groups['add-self'] = User
::getAllGroups();
4907 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4908 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4911 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4913 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4914 $groups['remove-self'] = User
::getAllGroups();
4915 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4916 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4923 * Returns an array of groups that this user can add and remove
4924 * @return array Array( 'add' => array( addablegroups ),
4925 * 'remove' => array( removablegroups ),
4926 * 'add-self' => array( addablegroups to self),
4927 * 'remove-self' => array( removable groups from self) )
4929 public function changeableGroups() {
4930 if ( $this->isAllowed( 'userrights' ) ) {
4931 // This group gives the right to modify everything (reverse-
4932 // compatibility with old "userrights lets you change
4934 // Using array_merge to make the groups reindexed
4935 $all = array_merge( User
::getAllGroups() );
4944 // Okay, it's not so simple, we will have to go through the arrays
4951 $addergroups = $this->getEffectiveGroups();
4953 foreach ( $addergroups as $addergroup ) {
4954 $groups = array_merge_recursive(
4955 $groups, $this->changeableByGroup( $addergroup )
4957 $groups['add'] = array_unique( $groups['add'] );
4958 $groups['remove'] = array_unique( $groups['remove'] );
4959 $groups['add-self'] = array_unique( $groups['add-self'] );
4960 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4966 * Deferred version of incEditCountImmediate()
4968 public function incEditCount() {
4969 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle(
4971 $this->incEditCountImmediate();
4978 * Increment the user's edit-count field.
4979 * Will have no effect for anonymous users.
4982 public function incEditCountImmediate() {
4983 if ( $this->isAnon() ) {
4987 $dbw = wfGetDB( DB_MASTER
);
4988 // No rows will be "affected" if user_editcount is NULL
4991 [ 'user_editcount=user_editcount+1' ],
4992 [ 'user_id' => $this->getId(), 'user_editcount IS NOT NULL' ],
4995 // Lazy initialization check...
4996 if ( $dbw->affectedRows() == 0 ) {
4997 // Now here's a goddamn hack...
4998 $dbr = wfGetDB( DB_REPLICA
);
4999 if ( $dbr !== $dbw ) {
5000 // If we actually have a replica DB server, the count is
5001 // at least one behind because the current transaction
5002 // has not been committed and replicated.
5003 $this->mEditCount
= $this->initEditCount( 1 );
5005 // But if DB_REPLICA is selecting the master, then the
5006 // count we just read includes the revision that was
5007 // just added in the working transaction.
5008 $this->mEditCount
= $this->initEditCount();
5011 if ( $this->mEditCount
=== null ) {
5012 $this->getEditCount();
5013 $dbr = wfGetDB( DB_REPLICA
);
5014 $this->mEditCount +
= ( $dbr !== $dbw ) ?
1 : 0;
5016 $this->mEditCount++
;
5019 // Edit count in user cache too
5020 $this->invalidateCache();
5024 * Initialize user_editcount from data out of the revision table
5026 * @param int $add Edits to add to the count from the revision table
5027 * @return int Number of edits
5029 protected function initEditCount( $add = 0 ) {
5030 // Pull from a replica DB to be less cruel to servers
5031 // Accuracy isn't the point anyway here
5032 $dbr = wfGetDB( DB_REPLICA
);
5033 $count = (int)$dbr->selectField(
5036 [ 'rev_user' => $this->getId() ],
5039 $count = $count +
$add;
5041 $dbw = wfGetDB( DB_MASTER
);
5044 [ 'user_editcount' => $count ],
5045 [ 'user_id' => $this->getId() ],
5053 * Get the description of a given right
5056 * @param string $right Right to query
5057 * @return string Localized description of the right
5059 public static function getRightDescription( $right ) {
5060 $key = "right-$right";
5061 $msg = wfMessage( $key );
5062 return $msg->isDisabled() ?
$right : $msg->text();
5066 * Get the name of a given grant
5069 * @param string $grant Grant to query
5070 * @return string Localized name of the grant
5072 public static function getGrantName( $grant ) {
5073 $key = "grant-$grant";
5074 $msg = wfMessage( $key );
5075 return $msg->isDisabled() ?
$grant : $msg->text();
5079 * Make a new-style password hash
5081 * @param string $password Plain-text password
5082 * @param bool|string $salt Optional salt, may be random or the user ID.
5083 * If unspecified or false, will generate one automatically
5084 * @return string Password hash
5085 * @deprecated since 1.24, use Password class
5087 public static function crypt( $password, $salt = false ) {
5088 wfDeprecated( __METHOD__
, '1.24' );
5089 $passwordFactory = new PasswordFactory();
5090 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
5091 $hash = $passwordFactory->newFromPlaintext( $password );
5092 return $hash->toString();
5096 * Compare a password hash with a plain-text password. Requires the user
5097 * ID if there's a chance that the hash is an old-style hash.
5099 * @param string $hash Password hash
5100 * @param string $password Plain-text password to compare
5101 * @param string|bool $userId User ID for old-style password salt
5104 * @deprecated since 1.24, use Password class
5106 public static function comparePasswords( $hash, $password, $userId = false ) {
5107 wfDeprecated( __METHOD__
, '1.24' );
5109 // Check for *really* old password hashes that don't even have a type
5110 // The old hash format was just an md5 hex hash, with no type information
5111 if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) {
5112 global $wgPasswordSalt;
5113 if ( $wgPasswordSalt ) {
5114 $password = ":B:{$userId}:{$hash}";
5116 $password = ":A:{$hash}";
5120 $passwordFactory = new PasswordFactory();
5121 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
5122 $hash = $passwordFactory->newFromCiphertext( $hash );
5123 return $hash->equals( $password );
5127 * Add a newuser log entry for this user.
5128 * Before 1.19 the return value was always true.
5130 * @deprecated since 1.27, AuthManager handles logging
5131 * @param string|bool $action Account creation type.
5132 * - String, one of the following values:
5133 * - 'create' for an anonymous user creating an account for himself.
5134 * This will force the action's performer to be the created user itself,
5135 * no matter the value of $wgUser
5136 * - 'create2' for a logged in user creating an account for someone else
5137 * - 'byemail' when the created user will receive its password by e-mail
5138 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
5139 * - Boolean means whether the account was created by e-mail (deprecated):
5140 * - true will be converted to 'byemail'
5141 * - false will be converted to 'create' if this object is the same as
5142 * $wgUser and to 'create2' otherwise
5143 * @param string $reason User supplied reason
5146 public function addNewUserLogEntry( $action = false, $reason = '' ) {
5147 return true; // disabled
5151 * Add an autocreate newuser log entry for this user
5152 * Used by things like CentralAuth and perhaps other authplugins.
5153 * Consider calling addNewUserLogEntry() directly instead.
5155 * @deprecated since 1.27, AuthManager handles logging
5158 public function addNewUserLogEntryAutoCreate() {
5159 $this->addNewUserLogEntry( 'autocreate' );
5165 * Load the user options either from cache, the database or an array
5167 * @param array $data Rows for the current user out of the user_properties table
5169 protected function loadOptions( $data = null ) {
5174 if ( $this->mOptionsLoaded
) {
5178 $this->mOptions
= self
::getDefaultOptions();
5180 if ( !$this->getId() ) {
5181 // For unlogged-in users, load language/variant options from request.
5182 // There's no need to do it for logged-in users: they can set preferences,
5183 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5184 // so don't override user's choice (especially when the user chooses site default).
5185 $variant = $wgContLang->getDefaultVariant();
5186 $this->mOptions
['variant'] = $variant;
5187 $this->mOptions
['language'] = $variant;
5188 $this->mOptionsLoaded
= true;
5192 // Maybe load from the object
5193 if ( !is_null( $this->mOptionOverrides
) ) {
5194 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5195 foreach ( $this->mOptionOverrides
as $key => $value ) {
5196 $this->mOptions
[$key] = $value;
5199 if ( !is_array( $data ) ) {
5200 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5201 // Load from database
5202 $dbr = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
5203 ?
wfGetDB( DB_MASTER
)
5204 : wfGetDB( DB_REPLICA
);
5206 $res = $dbr->select(
5208 [ 'up_property', 'up_value' ],
5209 [ 'up_user' => $this->getId() ],
5213 $this->mOptionOverrides
= [];
5215 foreach ( $res as $row ) {
5216 $data[$row->up_property
] = $row->up_value
;
5219 foreach ( $data as $property => $value ) {
5220 $this->mOptionOverrides
[$property] = $value;
5221 $this->mOptions
[$property] = $value;
5225 $this->mOptionsLoaded
= true;
5227 Hooks
::run( 'UserLoadOptions', [ $this, &$this->mOptions
] );
5231 * Saves the non-default options for this user, as previously set e.g. via
5232 * setOption(), in the database's "user_properties" (preferences) table.
5233 * Usually used via saveSettings().
5235 protected function saveOptions() {
5236 $this->loadOptions();
5238 // Not using getOptions(), to keep hidden preferences in database
5239 $saveOptions = $this->mOptions
;
5241 // Allow hooks to abort, for instance to save to a global profile.
5242 // Reset options to default state before saving.
5243 if ( !Hooks
::run( 'UserSaveOptions', [ $this, &$saveOptions ] ) ) {
5247 $userId = $this->getId();
5249 $insert_rows = []; // all the new preference rows
5250 foreach ( $saveOptions as $key => $value ) {
5251 // Don't bother storing default values
5252 $defaultOption = self
::getDefaultOption( $key );
5253 if ( ( $defaultOption === null && $value !== false && $value !== null )
5254 ||
$value != $defaultOption
5257 'up_user' => $userId,
5258 'up_property' => $key,
5259 'up_value' => $value,
5264 $dbw = wfGetDB( DB_MASTER
);
5266 $res = $dbw->select( 'user_properties',
5267 [ 'up_property', 'up_value' ], [ 'up_user' => $userId ], __METHOD__
);
5269 // Find prior rows that need to be removed or updated. These rows will
5270 // all be deleted (the latter so that INSERT IGNORE applies the new values).
5272 foreach ( $res as $row ) {
5273 if ( !isset( $saveOptions[$row->up_property
] )
5274 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
5276 $keysDelete[] = $row->up_property
;
5280 if ( count( $keysDelete ) ) {
5281 // Do the DELETE by PRIMARY KEY for prior rows.
5282 // In the past a very large portion of calls to this function are for setting
5283 // 'rememberpassword' for new accounts (a preference that has since been removed).
5284 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5285 // caused gap locks on [max user ID,+infinity) which caused high contention since
5286 // updates would pile up on each other as they are for higher (newer) user IDs.
5287 // It might not be necessary these days, but it shouldn't hurt either.
5288 $dbw->delete( 'user_properties',
5289 [ 'up_user' => $userId, 'up_property' => $keysDelete ], __METHOD__
);
5291 // Insert the new preference rows
5292 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, [ 'IGNORE' ] );
5296 * Lazily instantiate and return a factory object for making passwords
5298 * @deprecated since 1.27, create a PasswordFactory directly instead
5299 * @return PasswordFactory
5301 public static function getPasswordFactory() {
5302 wfDeprecated( __METHOD__
, '1.27' );
5303 $ret = new PasswordFactory();
5304 $ret->init( RequestContext
::getMain()->getConfig() );
5309 * Provide an array of HTML5 attributes to put on an input element
5310 * intended for the user to enter a new password. This may include
5311 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
5313 * Do *not* use this when asking the user to enter his current password!
5314 * Regardless of configuration, users may have invalid passwords for whatever
5315 * reason (e.g., they were set before requirements were tightened up).
5316 * Only use it when asking for a new password, like on account creation or
5319 * Obviously, you still need to do server-side checking.
5321 * NOTE: A combination of bugs in various browsers means that this function
5322 * actually just returns array() unconditionally at the moment. May as
5323 * well keep it around for when the browser bugs get fixed, though.
5325 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
5327 * @deprecated since 1.27
5328 * @return array Array of HTML attributes suitable for feeding to
5329 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
5330 * That will get confused by the boolean attribute syntax used.)
5332 public static function passwordChangeInputAttribs() {
5333 global $wgMinimalPasswordLength;
5335 if ( $wgMinimalPasswordLength == 0 ) {
5339 # Note that the pattern requirement will always be satisfied if the
5340 # input is empty, so we need required in all cases.
5342 # @todo FIXME: Bug 23769: This needs to not claim the password is required
5343 # if e-mail confirmation is being used. Since HTML5 input validation
5344 # is b0rked anyway in some browsers, just return nothing. When it's
5345 # re-enabled, fix this code to not output required for e-mail
5347 # $ret = array( 'required' );
5350 # We can't actually do this right now, because Opera 9.6 will print out
5351 # the entered password visibly in its error message! When other
5352 # browsers add support for this attribute, or Opera fixes its support,
5353 # we can add support with a version check to avoid doing this on Opera
5354 # versions where it will be a problem. Reported to Opera as
5355 # DSK-262266, but they don't have a public bug tracker for us to follow.
5357 if ( $wgMinimalPasswordLength > 1 ) {
5358 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
5359 $ret['title'] = wfMessage( 'passwordtooshort' )
5360 ->numParams( $wgMinimalPasswordLength )->text();
5368 * Return the list of user fields that should be selected to create
5369 * a new user object.
5372 public static function selectFields() {
5380 'user_email_authenticated',
5382 'user_email_token_expires',
5383 'user_registration',
5389 * Factory function for fatal permission-denied errors
5392 * @param string $permission User right required
5395 static function newFatalPermissionDeniedStatus( $permission ) {
5398 $groups = array_map(
5399 [ 'User', 'makeGroupLinkWiki' ],
5400 User
::getGroupsWithPermission( $permission )
5404 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5406 return Status
::newFatal( 'badaccess-group0' );
5411 * Get a new instance of this user that was loaded from the master via a locking read
5413 * Use this instead of the main context User when updating that user. This avoids races
5414 * where that user was loaded from a replica DB or even the master but without proper locks.
5416 * @return User|null Returns null if the user was not found in the DB
5419 public function getInstanceForUpdate() {
5420 if ( !$this->getId() ) {
5421 return null; // anon
5424 $user = self
::newFromId( $this->getId() );
5425 if ( !$user->loadFromId( self
::READ_EXCLUSIVE
) ) {
5433 * Checks if two user objects point to the same user.
5439 public function equals( User
$user ) {
5440 return $this->getName() === $user->getName();