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
;
30 use Wikimedia\Rdbms\Database
;
31 use Wikimedia\Rdbms\DBExpectedError
;
34 * String Some punctuation to prevent editing from broken text-mangling proxies.
35 * @deprecated since 1.27, use \MediaWiki\Session\Token::SUFFIX
38 define( 'EDIT_TOKEN_SUFFIX', Token
::SUFFIX
);
41 * The User object encapsulates all of the user-specific settings (user_id,
42 * name, rights, email address, options, last login time). Client
43 * classes use the getXXX() functions to access these fields. These functions
44 * do all the work of determining whether the user is logged in,
45 * whether the requested option can be satisfied from cookies or
46 * whether a database query is needed. Most of the settings needed
47 * for rendering normal pages are set in the cookie to minimize use
50 class User
implements IDBAccessObject
{
52 * @const int Number of characters in user_token field.
54 const TOKEN_LENGTH
= 32;
57 * @const string An invalid value for user_token
59 const INVALID_TOKEN
= '*** INVALID ***';
62 * Global constant made accessible as class constants so that autoloader
64 * @deprecated since 1.27, use \MediaWiki\Session\Token::SUFFIX
66 const EDIT_TOKEN_SUFFIX
= EDIT_TOKEN_SUFFIX
;
69 * @const int Serialized record version.
74 * Exclude user options that are set to their default value.
77 const GETOPTIONS_EXCLUDE_DEFAULTS
= 1;
82 const CHECK_USER_RIGHTS
= true;
87 const IGNORE_USER_RIGHTS
= false;
90 * Array of Strings List of member variables which are saved to the
91 * shared cache (memcached). Any operation which changes the
92 * corresponding database fields must call a cache-clearing function.
95 protected static $mCacheVars = [
103 'mEmailAuthenticated',
105 'mEmailTokenExpires',
110 // user_properties table
115 * Array of Strings Core rights.
116 * Each of these should have a corresponding message of the form
120 protected static $mCoreRights = [
163 'move-categorypages',
164 'move-rootuserpages',
168 'override-export-depth',
190 'userrights-interwiki',
198 * String Cached results of getAllRights()
200 protected static $mAllRights = false;
202 /** Cache variables */
213 /** @var string TS_MW timestamp from the DB */
215 /** @var string TS_MW timestamp from cache */
216 protected $mQuickTouched;
220 public $mEmailAuthenticated;
222 protected $mEmailToken;
224 protected $mEmailTokenExpires;
226 protected $mRegistration;
228 protected $mEditCount;
230 * @var array No longer used since 1.29; use User::getGroups() instead
231 * @deprecated since 1.29
234 /** @var array Associative array of (group name => UserGroupMembership object) */
235 protected $mGroupMemberships;
237 protected $mOptionOverrides;
241 * Bool Whether the cache variables have been loaded.
244 public $mOptionsLoaded;
247 * Array with already loaded items or true if all items have been loaded.
249 protected $mLoadedItems = [];
253 * String Initialization data source if mLoadedItems!==true. May be one of:
254 * - 'defaults' anonymous user initialised from class defaults
255 * - 'name' initialise from mName
256 * - 'id' initialise from mId
257 * - 'session' log in from session if possible
259 * Use the User::newFrom*() family of functions to set this.
264 * Lazy-initialized variables, invalidated with clearInstanceCache
268 protected $mDatePreference;
276 protected $mBlockreason;
278 protected $mEffectiveGroups;
280 protected $mImplicitGroups;
282 protected $mFormerGroups;
284 protected $mGlobalBlock;
292 /** @var WebRequest */
299 protected $mAllowUsertalk;
302 private $mBlockedFromCreateAccount = false;
304 /** @var integer User::READ_* constant bitfield used to load data */
305 protected $queryFlagsUsed = self
::READ_NORMAL
;
307 /** @var string Indicates type of block (used for eventlogging)
308 * Permitted values: 'cookie-block', 'proxy-block', 'openproxy-block', 'xff-block',
311 public $blockTrigger = false;
313 public static $idCacheByName = [];
316 * Lightweight constructor for an anonymous user.
317 * Use the User::newFrom* factory functions for other kinds of users.
321 * @see newFromConfirmationCode()
322 * @see newFromSession()
325 public function __construct() {
326 $this->clearInstanceCache( 'defaults' );
332 public function __toString() {
333 return (string)$this->getName();
337 * Test if it's safe to load this User object.
339 * You should typically check this before using $wgUser or
340 * RequestContext::getUser in a method that might be called before the
341 * system has been fully initialized. If the object is unsafe, you should
342 * use an anonymous user:
344 * $user = $wgUser->isSafeToLoad() ? $wgUser : new User;
350 public function isSafeToLoad() {
351 global $wgFullyInitialised;
353 // The user is safe to load if:
354 // * MW_NO_SESSION is undefined AND $wgFullyInitialised is true (safe to use session data)
355 // * mLoadedItems === true (already loaded)
356 // * mFrom !== 'session' (sessions not involved at all)
358 return ( !defined( 'MW_NO_SESSION' ) && $wgFullyInitialised ) ||
359 $this->mLoadedItems
=== true ||
$this->mFrom
!== 'session';
363 * Load the user table data for this object from the source given by mFrom.
365 * @param integer $flags User::READ_* constant bitfield
367 public function load( $flags = self
::READ_NORMAL
) {
368 global $wgFullyInitialised;
370 if ( $this->mLoadedItems
=== true ) {
374 // Set it now to avoid infinite recursion in accessors
375 $oldLoadedItems = $this->mLoadedItems
;
376 $this->mLoadedItems
= true;
377 $this->queryFlagsUsed
= $flags;
379 // If this is called too early, things are likely to break.
380 if ( !$wgFullyInitialised && $this->mFrom
=== 'session' ) {
381 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
382 ->warning( 'User::loadFromSession called before the end of Setup.php', [
383 'exception' => new Exception( 'User::loadFromSession called before the end of Setup.php' ),
385 $this->loadDefaults();
386 $this->mLoadedItems
= $oldLoadedItems;
390 switch ( $this->mFrom
) {
392 $this->loadDefaults();
395 // Make sure this thread sees its own changes
396 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
397 $flags |
= self
::READ_LATEST
;
398 $this->queryFlagsUsed
= $flags;
401 $this->mId
= self
::idFromName( $this->mName
, $flags );
403 // Nonexistent user placeholder object
404 $this->loadDefaults( $this->mName
);
406 $this->loadFromId( $flags );
410 $this->loadFromId( $flags );
413 if ( !$this->loadFromSession() ) {
414 // Loading from session failed. Load defaults.
415 $this->loadDefaults();
417 Hooks
::run( 'UserLoadAfterLoadFromSession', [ $this ] );
420 throw new UnexpectedValueException(
421 "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
426 * Load user table data, given mId has already been set.
427 * @param integer $flags User::READ_* constant bitfield
428 * @return bool False if the ID does not exist, true otherwise
430 public function loadFromId( $flags = self
::READ_NORMAL
) {
431 if ( $this->mId
== 0 ) {
432 // Anonymous users are not in the database (don't need cache)
433 $this->loadDefaults();
437 // Try cache (unless this needs data from the master DB).
438 // NOTE: if this thread called saveSettings(), the cache was cleared.
439 $latest = DBAccessObjectUtils
::hasFlags( $flags, self
::READ_LATEST
);
441 if ( !$this->loadFromDatabase( $flags ) ) {
442 // Can't load from ID
446 $this->loadFromCache();
449 $this->mLoadedItems
= true;
450 $this->queryFlagsUsed
= $flags;
457 * @param string $wikiId
458 * @param integer $userId
460 public static function purge( $wikiId, $userId ) {
461 $cache = ObjectCache
::getMainWANInstance();
462 $key = $cache->makeGlobalKey( 'user', 'id', $wikiId, $userId );
463 $cache->delete( $key );
468 * @param WANObjectCache $cache
471 protected function getCacheKey( WANObjectCache
$cache ) {
472 return $cache->makeGlobalKey( 'user', 'id', wfWikiID(), $this->mId
);
476 * @param WANObjectCache $cache
480 public function getMutableCacheKeys( WANObjectCache
$cache ) {
481 $id = $this->getId();
483 return $id ?
[ $this->getCacheKey( $cache ) ] : [];
487 * Load user data from shared cache, given mId has already been set.
492 protected function loadFromCache() {
493 $cache = ObjectCache
::getMainWANInstance();
494 $data = $cache->getWithSetCallback(
495 $this->getCacheKey( $cache ),
497 function ( $oldValue, &$ttl, array &$setOpts ) use ( $cache ) {
498 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
499 wfDebug( "User: cache miss for user {$this->mId}\n" );
501 $this->loadFromDatabase( self
::READ_NORMAL
);
503 $this->loadOptions();
506 foreach ( self
::$mCacheVars as $name ) {
507 $data[$name] = $this->$name;
510 $ttl = $cache->adaptiveTTL( wfTimestamp( TS_UNIX
, $this->mTouched
), $ttl );
515 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'version' => self
::VERSION
]
518 // Restore from cache
519 foreach ( self
::$mCacheVars as $name ) {
520 $this->$name = $data[$name];
526 /** @name newFrom*() static factory methods */
530 * Static factory method for creation from username.
532 * This is slightly less efficient than newFromId(), so use newFromId() if
533 * you have both an ID and a name handy.
535 * @param string $name Username, validated by Title::newFromText()
536 * @param string|bool $validate Validate username. Takes the same parameters as
537 * User::getCanonicalName(), except that true is accepted as an alias
538 * for 'valid', for BC.
540 * @return User|bool User object, or false if the username is invalid
541 * (e.g. if it contains illegal characters or is an IP address). If the
542 * username is not present in the database, the result will be a user object
543 * with a name, zero user ID and default settings.
545 public static function newFromName( $name, $validate = 'valid' ) {
546 if ( $validate === true ) {
549 $name = self
::getCanonicalName( $name, $validate );
550 if ( $name === false ) {
553 // Create unloaded user object
557 $u->setItemLoaded( 'name' );
563 * Static factory method for creation from a given user ID.
565 * @param int $id Valid user ID
566 * @return User The corresponding User object
568 public static function newFromId( $id ) {
572 $u->setItemLoaded( 'id' );
577 * Factory method to fetch whichever user has a given email confirmation code.
578 * This code is generated when an account is created or its e-mail address
581 * If the code is invalid or has expired, returns NULL.
583 * @param string $code Confirmation code
584 * @param int $flags User::READ_* bitfield
587 public static function newFromConfirmationCode( $code, $flags = 0 ) {
588 $db = ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
589 ?
wfGetDB( DB_MASTER
)
590 : wfGetDB( DB_REPLICA
);
592 $id = $db->selectField(
596 'user_email_token' => md5( $code ),
597 'user_email_token_expires > ' . $db->addQuotes( $db->timestamp() ),
601 return $id ? User
::newFromId( $id ) : null;
605 * Create a new user object using data from session. If the login
606 * credentials are invalid, the result is an anonymous user.
608 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
611 public static function newFromSession( WebRequest
$request = null ) {
613 $user->mFrom
= 'session';
614 $user->mRequest
= $request;
619 * Create a new user object from a user row.
620 * The row should have the following fields from the user table in it:
621 * - either user_name or user_id to load further data if needed (or both)
623 * - all other fields (email, etc.)
624 * It is useless to provide the remaining fields if either user_id,
625 * user_name and user_real_name are not provided because the whole row
626 * will be loaded once more from the database when accessing them.
628 * @param stdClass $row A row from the user table
629 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
632 public static function newFromRow( $row, $data = null ) {
634 $user->loadFromRow( $row, $data );
639 * Static factory method for creation of a "system" user from username.
641 * A "system" user is an account that's used to attribute logged actions
642 * taken by MediaWiki itself, as opposed to a bot or human user. Examples
643 * might include the 'Maintenance script' or 'Conversion script' accounts
644 * used by various scripts in the maintenance/ directory or accounts such
645 * as 'MediaWiki message delivery' used by the MassMessage extension.
647 * This can optionally create the user if it doesn't exist, and "steal" the
648 * account if it does exist.
650 * "Stealing" an existing user is intended to make it impossible for normal
651 * authentication processes to use the account, effectively disabling the
652 * account for normal use:
653 * - Email is invalidated, to prevent account recovery by emailing a
654 * temporary password and to disassociate the account from the existing
656 * - The token is set to a magic invalid value, to kill existing sessions
657 * and to prevent $this->setToken() calls from resetting the token to a
659 * - SessionManager is instructed to prevent new sessions for the user, to
660 * do things like deauthorizing OAuth consumers.
661 * - AuthManager is instructed to revoke access, to invalidate or remove
662 * passwords and other credentials.
664 * @param string $name Username
665 * @param array $options Options are:
666 * - validate: As for User::getCanonicalName(), default 'valid'
667 * - create: Whether to create the user if it doesn't already exist, default true
668 * - steal: Whether to "disable" the account for normal use if it already
669 * exists, default false
673 public static function newSystemUser( $name, $options = [] ) {
675 'validate' => 'valid',
680 $name = self
::getCanonicalName( $name, $options['validate'] );
681 if ( $name === false ) {
685 $fields = self
::selectFields();
687 $dbw = wfGetDB( DB_MASTER
);
688 $row = $dbw->selectRow(
691 [ 'user_name' => $name ],
695 // No user. Create it?
696 return $options['create'] ? self
::createNew( $name, [ 'token' => self
::INVALID_TOKEN
] ) : null;
698 $user = self
::newFromRow( $row );
700 // A user is considered to exist as a non-system user if it can
701 // authenticate, or has an email set, or has a non-invalid token.
702 if ( $user->mEmail ||
$user->mToken
!== self
::INVALID_TOKEN ||
703 AuthManager
::singleton()->userCanAuthenticate( $name )
705 // User exists. Steal it?
706 if ( !$options['steal'] ) {
710 AuthManager
::singleton()->revokeAccessForUser( $name );
712 $user->invalidateEmail();
713 $user->mToken
= self
::INVALID_TOKEN
;
714 $user->saveSettings();
715 SessionManager
::singleton()->preventSessionsForUser( $user->getName() );
724 * Get the username corresponding to a given user ID
725 * @param int $id User ID
726 * @return string|bool The corresponding username
728 public static function whoIs( $id ) {
729 return UserCache
::singleton()->getProp( $id, 'name' );
733 * Get the real name of a user given their user ID
735 * @param int $id User ID
736 * @return string|bool The corresponding user's real name
738 public static function whoIsReal( $id ) {
739 return UserCache
::singleton()->getProp( $id, 'real_name' );
743 * Get database id given a user name
744 * @param string $name Username
745 * @param integer $flags User::READ_* constant bitfield
746 * @return int|null The corresponding user's ID, or null if user is nonexistent
748 public static function idFromName( $name, $flags = self
::READ_NORMAL
) {
749 $nt = Title
::makeTitleSafe( NS_USER
, $name );
750 if ( is_null( $nt ) ) {
755 if ( !( $flags & self
::READ_LATEST
) && isset( self
::$idCacheByName[$name] ) ) {
756 return self
::$idCacheByName[$name];
759 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
760 $db = wfGetDB( $index );
765 [ 'user_name' => $nt->getText() ],
770 if ( $s === false ) {
773 $result = $s->user_id
;
776 self
::$idCacheByName[$name] = $result;
778 if ( count( self
::$idCacheByName ) > 1000 ) {
779 self
::$idCacheByName = [];
786 * Reset the cache used in idFromName(). For use in tests.
788 public static function resetIdByNameCache() {
789 self
::$idCacheByName = [];
793 * Does the string match an anonymous IP address?
795 * This function exists for username validation, in order to reject
796 * usernames which are similar in form to IP addresses. Strings such
797 * as 300.300.300.300 will return true because it looks like an IP
798 * address, despite not being strictly valid.
800 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
801 * address because the usemod software would "cloak" anonymous IP
802 * addresses like this, if we allowed accounts like this to be created
803 * new users could get the old edits of these anonymous users.
805 * @param string $name Name to match
808 public static function isIP( $name ) {
809 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
810 || IP
::isIPv6( $name );
814 * Is the input a valid username?
816 * Checks if the input is a valid username, we don't want an empty string,
817 * an IP address, anything that contains slashes (would mess up subpages),
818 * is longer than the maximum allowed username size or doesn't begin with
821 * @param string $name Name to match
824 public static function isValidUserName( $name ) {
825 global $wgContLang, $wgMaxNameChars;
828 || User
::isIP( $name )
829 ||
strpos( $name, '/' ) !== false
830 ||
strlen( $name ) > $wgMaxNameChars
831 ||
$name != $wgContLang->ucfirst( $name )
836 // Ensure that the name can't be misresolved as a different title,
837 // such as with extra namespace keys at the start.
838 $parsed = Title
::newFromText( $name );
839 if ( is_null( $parsed )
840 ||
$parsed->getNamespace()
841 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
845 // Check an additional blacklist of troublemaker characters.
846 // Should these be merged into the title char list?
847 $unicodeBlacklist = '/[' .
848 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
849 '\x{00a0}' . # non-breaking space
850 '\x{2000}-\x{200f}' . # various whitespace
851 '\x{2028}-\x{202f}' . # breaks and control chars
852 '\x{3000}' . # ideographic space
853 '\x{e000}-\x{f8ff}' . # private use
855 if ( preg_match( $unicodeBlacklist, $name ) ) {
863 * Usernames which fail to pass this function will be blocked
864 * from user login and new account registrations, but may be used
865 * internally by batch processes.
867 * If an account already exists in this form, login will be blocked
868 * by a failure to pass this function.
870 * @param string $name Name to match
873 public static function isUsableName( $name ) {
874 global $wgReservedUsernames;
875 // Must be a valid username, obviously ;)
876 if ( !self
::isValidUserName( $name ) ) {
880 static $reservedUsernames = false;
881 if ( !$reservedUsernames ) {
882 $reservedUsernames = $wgReservedUsernames;
883 Hooks
::run( 'UserGetReservedNames', [ &$reservedUsernames ] );
886 // Certain names may be reserved for batch processes.
887 foreach ( $reservedUsernames as $reserved ) {
888 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
889 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
891 if ( $reserved == $name ) {
899 * Return the users who are members of the given group(s). In case of multiple groups,
900 * users who are members of at least one of them are returned.
902 * @param string|array $groups A single group name or an array of group names
903 * @param int $limit Max number of users to return. The actual limit will never exceed 5000
904 * records; larger values are ignored.
905 * @param int $after ID the user to start after
906 * @return UserArrayFromResult
908 public static function findUsersByGroup( $groups, $limit = 5000, $after = null ) {
909 if ( $groups === [] ) {
910 return UserArrayFromResult
::newFromIDs( [] );
913 $groups = array_unique( (array)$groups );
914 $limit = min( 5000, $limit );
916 $conds = [ 'ug_group' => $groups ];
917 if ( $after !== null ) {
918 $conds[] = 'ug_user > ' . (int)$after;
921 $dbr = wfGetDB( DB_REPLICA
);
922 $ids = $dbr->selectFieldValues(
929 'ORDER BY' => 'ug_user',
933 return UserArray
::newFromIDs( $ids );
937 * Usernames which fail to pass this function will be blocked
938 * from new account registrations, but may be used internally
939 * either by batch processes or by user accounts which have
940 * already been created.
942 * Additional blacklisting may be added here rather than in
943 * isValidUserName() to avoid disrupting existing accounts.
945 * @param string $name String to match
948 public static function isCreatableName( $name ) {
949 global $wgInvalidUsernameCharacters;
951 // Ensure that the username isn't longer than 235 bytes, so that
952 // (at least for the builtin skins) user javascript and css files
953 // will work. (T25080)
954 if ( strlen( $name ) > 235 ) {
955 wfDebugLog( 'username', __METHOD__
.
956 ": '$name' invalid due to length" );
960 // Preg yells if you try to give it an empty string
961 if ( $wgInvalidUsernameCharacters !== '' ) {
962 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
963 wfDebugLog( 'username', __METHOD__
.
964 ": '$name' invalid due to wgInvalidUsernameCharacters" );
969 return self
::isUsableName( $name );
973 * Is the input a valid password for this user?
975 * @param string $password Desired password
978 public function isValidPassword( $password ) {
979 // simple boolean wrapper for getPasswordValidity
980 return $this->getPasswordValidity( $password ) === true;
984 * Given unvalidated password input, return error message on failure.
986 * @param string $password Desired password
987 * @return bool|string|array True on success, string or array of error message on failure
989 public function getPasswordValidity( $password ) {
990 $result = $this->checkPasswordValidity( $password );
991 if ( $result->isGood() ) {
995 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
996 $messages[] = $error['message'];
998 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
999 $messages[] = $warning['message'];
1001 if ( count( $messages ) === 1 ) {
1002 return $messages[0];
1009 * Check if this is a valid password for this user
1011 * Create a Status object based on the password's validity.
1012 * The Status should be set to fatal if the user should not
1013 * be allowed to log in, and should have any errors that
1014 * would block changing the password.
1016 * If the return value of this is not OK, the password
1017 * should not be checked. If the return value is not Good,
1018 * the password can be checked, but the user should not be
1019 * able to set their password to this.
1021 * @param string $password Desired password
1025 public function checkPasswordValidity( $password ) {
1026 global $wgPasswordPolicy;
1028 $upp = new UserPasswordPolicy(
1029 $wgPasswordPolicy['policies'],
1030 $wgPasswordPolicy['checks']
1033 $status = Status
::newGood();
1034 $result = false; // init $result to false for the internal checks
1036 if ( !Hooks
::run( 'isValidPassword', [ $password, &$result, $this ] ) ) {
1037 $status->error( $result );
1041 if ( $result === false ) {
1042 $status->merge( $upp->checkUserPassword( $this, $password ) );
1044 } elseif ( $result === true ) {
1047 $status->error( $result );
1048 return $status; // the isValidPassword hook set a string $result and returned true
1053 * Given unvalidated user input, return a canonical username, or false if
1054 * the username is invalid.
1055 * @param string $name User input
1056 * @param string|bool $validate Type of validation to use:
1057 * - false No validation
1058 * - 'valid' Valid for batch processes
1059 * - 'usable' Valid for batch processes and login
1060 * - 'creatable' Valid for batch processes, login and account creation
1062 * @throws InvalidArgumentException
1063 * @return bool|string
1065 public static function getCanonicalName( $name, $validate = 'valid' ) {
1066 // Force usernames to capital
1068 $name = $wgContLang->ucfirst( $name );
1070 # Reject names containing '#'; these will be cleaned up
1071 # with title normalisation, but then it's too late to
1073 if ( strpos( $name, '#' ) !== false ) {
1077 // Clean up name according to title rules,
1078 // but only when validation is requested (T14654)
1079 $t = ( $validate !== false ) ?
1080 Title
::newFromText( $name, NS_USER
) : Title
::makeTitle( NS_USER
, $name );
1081 // Check for invalid titles
1082 if ( is_null( $t ) ||
$t->getNamespace() !== NS_USER ||
$t->isExternal() ) {
1086 // Reject various classes of invalid names
1087 $name = AuthManager
::callLegacyAuthPlugin(
1088 'getCanonicalName', [ $t->getText() ], $t->getText()
1091 switch ( $validate ) {
1095 if ( !User
::isValidUserName( $name ) ) {
1100 if ( !User
::isUsableName( $name ) ) {
1105 if ( !User
::isCreatableName( $name ) ) {
1110 throw new InvalidArgumentException(
1111 'Invalid parameter value for $validate in ' . __METHOD__
);
1117 * Return a random password.
1119 * @deprecated since 1.27, use PasswordFactory::generateRandomPasswordString()
1120 * @return string New random password
1122 public static function randomPassword() {
1123 global $wgMinimalPasswordLength;
1124 return PasswordFactory
::generateRandomPasswordString( $wgMinimalPasswordLength );
1128 * Set cached properties to default.
1130 * @note This no longer clears uncached lazy-initialised properties;
1131 * the constructor does that instead.
1133 * @param string|bool $name
1135 public function loadDefaults( $name = false ) {
1137 $this->mName
= $name;
1138 $this->mRealName
= '';
1140 $this->mOptionOverrides
= null;
1141 $this->mOptionsLoaded
= false;
1143 $loggedOut = $this->mRequest
&& !defined( 'MW_NO_SESSION' )
1144 ?
$this->mRequest
->getSession()->getLoggedOutTimestamp() : 0;
1145 if ( $loggedOut !== 0 ) {
1146 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1148 $this->mTouched
= '1'; # Allow any pages to be cached
1151 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1152 $this->mEmailAuthenticated
= null;
1153 $this->mEmailToken
= '';
1154 $this->mEmailTokenExpires
= null;
1155 $this->mRegistration
= wfTimestamp( TS_MW
);
1156 $this->mGroupMemberships
= [];
1158 Hooks
::run( 'UserLoadDefaults', [ $this, $name ] );
1162 * Return whether an item has been loaded.
1164 * @param string $item Item to check. Current possibilities:
1168 * @param string $all 'all' to check if the whole object has been loaded
1169 * or any other string to check if only the item is available (e.g.
1173 public function isItemLoaded( $item, $all = 'all' ) {
1174 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1175 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1179 * Set that an item has been loaded
1181 * @param string $item
1183 protected function setItemLoaded( $item ) {
1184 if ( is_array( $this->mLoadedItems
) ) {
1185 $this->mLoadedItems
[$item] = true;
1190 * Load user data from the session.
1192 * @return bool True if the user is logged in, false otherwise.
1194 private function loadFromSession() {
1197 Hooks
::run( 'UserLoadFromSession', [ $this, &$result ], '1.27' );
1198 if ( $result !== null ) {
1202 // MediaWiki\Session\Session already did the necessary authentication of the user
1203 // returned here, so just use it if applicable.
1204 $session = $this->getRequest()->getSession();
1205 $user = $session->getUser();
1206 if ( $user->isLoggedIn() ) {
1207 $this->loadFromUserObject( $user );
1209 // If this user is autoblocked, set a cookie to track the Block. This has to be done on
1210 // every session load, because an autoblocked editor might not edit again from the same
1211 // IP address after being blocked.
1212 $config = RequestContext
::getMain()->getConfig();
1213 if ( $config->get( 'CookieSetOnAutoblock' ) === true ) {
1214 $block = $this->getBlock();
1215 $shouldSetCookie = $this->getRequest()->getCookie( 'BlockID' ) === null
1217 && $block->getType() === Block
::TYPE_USER
1218 && $block->isAutoblocking();
1219 if ( $shouldSetCookie ) {
1220 wfDebug( __METHOD__
. ': User is autoblocked, setting cookie to track' );
1221 $block->setCookie( $this->getRequest()->response() );
1225 // Other code expects these to be set in the session, so set them.
1226 $session->set( 'wsUserID', $this->getId() );
1227 $session->set( 'wsUserName', $this->getName() );
1228 $session->set( 'wsToken', $this->getToken() );
1235 * Load user and user_group data from the database.
1236 * $this->mId must be set, this is how the user is identified.
1238 * @param integer $flags User::READ_* constant bitfield
1239 * @return bool True if the user exists, false if the user is anonymous
1241 public function loadFromDatabase( $flags = self
::READ_LATEST
) {
1243 $this->mId
= intval( $this->mId
);
1245 if ( !$this->mId
) {
1246 // Anonymous users are not in the database
1247 $this->loadDefaults();
1251 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
1252 $db = wfGetDB( $index );
1254 $s = $db->selectRow(
1256 self
::selectFields(),
1257 [ 'user_id' => $this->mId
],
1262 $this->queryFlagsUsed
= $flags;
1263 Hooks
::run( 'UserLoadFromDatabase', [ $this, &$s ] );
1265 if ( $s !== false ) {
1266 // Initialise user table data
1267 $this->loadFromRow( $s );
1268 $this->mGroupMemberships
= null; // deferred
1269 $this->getEditCount(); // revalidation for nulls
1274 $this->loadDefaults();
1280 * Initialize this object from a row from the user table.
1282 * @param stdClass $row Row from the user table to load.
1283 * @param array $data Further user data to load into the object
1285 * user_groups Array of arrays or stdClass result rows out of the user_groups
1286 * table. Previously you were supposed to pass an array of strings
1287 * here, but we also need expiry info nowadays, so an array of
1288 * strings is ignored.
1289 * user_properties Array with properties out of the user_properties table
1291 protected function loadFromRow( $row, $data = null ) {
1294 $this->mGroupMemberships
= null; // deferred
1296 if ( isset( $row->user_name
) ) {
1297 $this->mName
= $row->user_name
;
1298 $this->mFrom
= 'name';
1299 $this->setItemLoaded( 'name' );
1304 if ( isset( $row->user_real_name
) ) {
1305 $this->mRealName
= $row->user_real_name
;
1306 $this->setItemLoaded( 'realname' );
1311 if ( isset( $row->user_id
) ) {
1312 $this->mId
= intval( $row->user_id
);
1313 $this->mFrom
= 'id';
1314 $this->setItemLoaded( 'id' );
1319 if ( isset( $row->user_id
) && isset( $row->user_name
) ) {
1320 self
::$idCacheByName[$row->user_name
] = $row->user_id
;
1323 if ( isset( $row->user_editcount
) ) {
1324 $this->mEditCount
= $row->user_editcount
;
1329 if ( isset( $row->user_touched
) ) {
1330 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1335 if ( isset( $row->user_token
) ) {
1336 // The definition for the column is binary(32), so trim the NULs
1337 // that appends. The previous definition was char(32), so trim
1339 $this->mToken
= rtrim( $row->user_token
, " \0" );
1340 if ( $this->mToken
=== '' ) {
1341 $this->mToken
= null;
1347 if ( isset( $row->user_email
) ) {
1348 $this->mEmail
= $row->user_email
;
1349 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1350 $this->mEmailToken
= $row->user_email_token
;
1351 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1352 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1358 $this->mLoadedItems
= true;
1361 if ( is_array( $data ) ) {
1362 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1363 if ( !count( $data['user_groups'] ) ) {
1364 $this->mGroupMemberships
= [];
1366 $firstGroup = reset( $data['user_groups'] );
1367 if ( is_array( $firstGroup ) ||
is_object( $firstGroup ) ) {
1368 $this->mGroupMemberships
= [];
1369 foreach ( $data['user_groups'] as $row ) {
1370 $ugm = UserGroupMembership
::newFromRow( (object)$row );
1371 $this->mGroupMemberships
[$ugm->getGroup()] = $ugm;
1376 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1377 $this->loadOptions( $data['user_properties'] );
1383 * Load the data for this user object from another user object.
1387 protected function loadFromUserObject( $user ) {
1389 foreach ( self
::$mCacheVars as $var ) {
1390 $this->$var = $user->$var;
1395 * Load the groups from the database if they aren't already loaded.
1397 private function loadGroups() {
1398 if ( is_null( $this->mGroupMemberships
) ) {
1399 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
1400 ?
wfGetDB( DB_MASTER
)
1401 : wfGetDB( DB_REPLICA
);
1402 $this->mGroupMemberships
= UserGroupMembership
::getMembershipsForUser(
1408 * Add the user to the group if he/she meets given criteria.
1410 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1411 * possible to remove manually via Special:UserRights. In such case it
1412 * will not be re-added automatically. The user will also not lose the
1413 * group if they no longer meet the criteria.
1415 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1417 * @return array Array of groups the user has been promoted to.
1419 * @see $wgAutopromoteOnce
1421 public function addAutopromoteOnceGroups( $event ) {
1422 global $wgAutopromoteOnceLogInRC;
1424 if ( wfReadOnly() ||
!$this->getId() ) {
1428 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1429 if ( !count( $toPromote ) ) {
1433 if ( !$this->checkAndSetTouched() ) {
1434 return []; // raced out (bug T48834)
1437 $oldGroups = $this->getGroups(); // previous groups
1438 foreach ( $toPromote as $group ) {
1439 $this->addGroup( $group );
1441 // update groups in external authentication database
1442 Hooks
::run( 'UserGroupsChanged', [ $this, $toPromote, [], false, false ] );
1443 AuthManager
::callLegacyAuthPlugin( 'updateExternalDBGroups', [ $this, $toPromote ] );
1445 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1447 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1448 $logEntry->setPerformer( $this );
1449 $logEntry->setTarget( $this->getUserPage() );
1450 $logEntry->setParameters( [
1451 '4::oldgroups' => $oldGroups,
1452 '5::newgroups' => $newGroups,
1454 $logid = $logEntry->insert();
1455 if ( $wgAutopromoteOnceLogInRC ) {
1456 $logEntry->publish( $logid );
1463 * Builds update conditions. Additional conditions may be added to $conditions to
1464 * protected against race conditions using a compare-and-set (CAS) mechanism
1465 * based on comparing $this->mTouched with the user_touched field.
1467 * @param Database $db
1468 * @param array $conditions WHERE conditions for use with Database::update
1469 * @return array WHERE conditions for use with Database::update
1471 protected function makeUpdateConditions( Database
$db, array $conditions ) {
1472 if ( $this->mTouched
) {
1473 // CAS check: only update if the row wasn't changed sicne it was loaded.
1474 $conditions['user_touched'] = $db->timestamp( $this->mTouched
);
1481 * Bump user_touched if it didn't change since this object was loaded
1483 * On success, the mTouched field is updated.
1484 * The user serialization cache is always cleared.
1486 * @return bool Whether user_touched was actually updated
1489 protected function checkAndSetTouched() {
1492 if ( !$this->mId
) {
1493 return false; // anon
1496 // Get a new user_touched that is higher than the old one
1497 $newTouched = $this->newTouchedTimestamp();
1499 $dbw = wfGetDB( DB_MASTER
);
1500 $dbw->update( 'user',
1501 [ 'user_touched' => $dbw->timestamp( $newTouched ) ],
1502 $this->makeUpdateConditions( $dbw, [
1503 'user_id' => $this->mId
,
1507 $success = ( $dbw->affectedRows() > 0 );
1510 $this->mTouched
= $newTouched;
1511 $this->clearSharedCache();
1513 // Clears on failure too since that is desired if the cache is stale
1514 $this->clearSharedCache( 'refresh' );
1521 * Clear various cached data stored in this object. The cache of the user table
1522 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1524 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1525 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1527 public function clearInstanceCache( $reloadFrom = false ) {
1528 $this->mNewtalk
= -1;
1529 $this->mDatePreference
= null;
1530 $this->mBlockedby
= -1; # Unset
1531 $this->mHash
= false;
1532 $this->mRights
= null;
1533 $this->mEffectiveGroups
= null;
1534 $this->mImplicitGroups
= null;
1535 $this->mGroupMemberships
= null;
1536 $this->mOptions
= null;
1537 $this->mOptionsLoaded
= false;
1538 $this->mEditCount
= null;
1540 if ( $reloadFrom ) {
1541 $this->mLoadedItems
= [];
1542 $this->mFrom
= $reloadFrom;
1547 * Combine the language default options with any site-specific options
1548 * and add the default language variants.
1550 * @return array Array of String options
1552 public static function getDefaultOptions() {
1553 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1555 static $defOpt = null;
1556 static $defOptLang = null;
1558 if ( $defOpt !== null && $defOptLang === $wgContLang->getCode() ) {
1559 // $wgContLang does not change (and should not change) mid-request,
1560 // but the unit tests change it anyway, and expect this method to
1561 // return values relevant to the current $wgContLang.
1565 $defOpt = $wgDefaultUserOptions;
1566 // Default language setting
1567 $defOptLang = $wgContLang->getCode();
1568 $defOpt['language'] = $defOptLang;
1569 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1570 $defOpt[$langCode == $wgContLang->getCode() ?
'variant' : "variant-$langCode"] = $langCode;
1573 // NOTE: don't use SearchEngineConfig::getSearchableNamespaces here,
1574 // since extensions may change the set of searchable namespaces depending
1575 // on user groups/permissions.
1576 foreach ( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
1577 $defOpt['searchNs' . $nsnum] = (boolean
)$val;
1579 $defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1581 Hooks
::run( 'UserGetDefaultOptions', [ &$defOpt ] );
1587 * Get a given default option value.
1589 * @param string $opt Name of option to retrieve
1590 * @return string Default option value
1592 public static function getDefaultOption( $opt ) {
1593 $defOpts = self
::getDefaultOptions();
1594 if ( isset( $defOpts[$opt] ) ) {
1595 return $defOpts[$opt];
1602 * Get blocking information
1603 * @param bool $bFromSlave Whether to check the replica DB first.
1604 * To improve performance, non-critical checks are done against replica DBs.
1605 * Check when actually saving should be done against master.
1607 private function getBlockedStatus( $bFromSlave = true ) {
1608 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff, $wgSoftBlockRanges;
1610 if ( -1 != $this->mBlockedby
) {
1614 wfDebug( __METHOD__
. ": checking...\n" );
1616 // Initialize data...
1617 // Otherwise something ends up stomping on $this->mBlockedby when
1618 // things get lazy-loaded later, causing false positive block hits
1619 // due to -1 !== 0. Probably session-related... Nothing should be
1620 // overwriting mBlockedby, surely?
1623 # We only need to worry about passing the IP address to the Block generator if the
1624 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1625 # know which IP address they're actually coming from
1627 if ( !$this->isAllowed( 'ipblock-exempt' ) ) {
1628 // $wgUser->getName() only works after the end of Setup.php. Until
1629 // then, assume it's a logged-out user.
1630 $globalUserName = $wgUser->isSafeToLoad()
1631 ?
$wgUser->getName()
1632 : IP
::sanitizeIP( $wgUser->getRequest()->getIP() );
1633 if ( $this->getName() === $globalUserName ) {
1634 $ip = $this->getRequest()->getIP();
1639 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1642 if ( !$block instanceof Block
) {
1643 $block = $this->getBlockFromCookieValue( $this->getRequest()->getCookie( 'BlockID' ) );
1647 if ( !$block instanceof Block
&& $ip !== null && !in_array( $ip, $wgProxyWhitelist ) ) {
1649 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1650 $block = new Block( [
1651 'byText' => wfMessage( 'proxyblocker' )->text(),
1652 'reason' => wfMessage( 'proxyblockreason' )->text(),
1654 'systemBlock' => 'proxy',
1656 $this->blockTrigger
= 'proxy-block';
1657 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1658 $block = new Block( [
1659 'byText' => wfMessage( 'sorbs' )->text(),
1660 'reason' => wfMessage( 'sorbsreason' )->text(),
1662 'systemBlock' => 'dnsbl',
1664 $this->blockTrigger
= 'openproxy-block';
1668 // (T25343) Apply IP blocks to the contents of XFF headers, if enabled
1669 if ( !$block instanceof Block
1670 && $wgApplyIpBlocksToXff
1672 && !in_array( $ip, $wgProxyWhitelist )
1674 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1675 $xff = array_map( 'trim', explode( ',', $xff ) );
1676 $xff = array_diff( $xff, [ $ip ] );
1677 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1678 $block = Block
::chooseBlock( $xffblocks, $xff );
1679 if ( $block instanceof Block
) {
1680 # Mangle the reason to alert the user that the block
1681 # originated from matching the X-Forwarded-For header.
1682 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->text();
1683 $this->blockTrigger
= 'xff-block';
1687 if ( !$block instanceof Block
1690 && IP
::isInRanges( $ip, $wgSoftBlockRanges )
1692 $block = new Block( [
1694 'byText' => 'MediaWiki default',
1695 'reason' => wfMessage( 'softblockrangesreason', $ip )->text(),
1697 'systemBlock' => 'wgSoftBlockRanges',
1699 $this->blockTrigger
= 'config-block';
1702 if ( $block instanceof Block
) {
1703 wfDebug( __METHOD__
. ": Found block.\n" );
1704 $this->mBlock
= $block;
1705 $this->mBlockedby
= $block->getByName();
1706 $this->mBlockreason
= $block->mReason
;
1707 $this->mHideName
= $block->mHideName
;
1708 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1710 $this->mBlockedby
= '';
1711 $this->mHideName
= 0;
1712 $this->mAllowUsertalk
= false;
1713 $this->blockTrigger
= false;
1716 // Avoid PHP 7.1 warning of passing $this by reference
1719 Hooks
::run( 'GetBlockedStatus', [ &$user ] );
1723 * Try to load a Block from an ID given in a cookie value.
1724 * @param string|null $blockCookieVal The cookie value to check.
1725 * @return Block|bool The Block object, or false if none could be loaded.
1727 protected function getBlockFromCookieValue( $blockCookieVal ) {
1728 // Make sure there's something to check. The cookie value must start with a number.
1729 if ( strlen( $blockCookieVal ) < 1 ||
!is_numeric( substr( $blockCookieVal, 0, 1 ) ) ) {
1732 // Load the Block from the ID in the cookie.
1733 $blockCookieId = Block
::getIdFromCookieValue( $blockCookieVal );
1734 if ( $blockCookieId !== null ) {
1735 // An ID was found in the cookie.
1736 $tmpBlock = Block
::newFromID( $blockCookieId );
1737 if ( $tmpBlock instanceof Block
) {
1738 // Check the validity of the block.
1739 $blockIsValid = $tmpBlock->getType() == Block
::TYPE_USER
1740 && !$tmpBlock->isExpired()
1741 && $tmpBlock->isAutoblocking();
1742 $config = RequestContext
::getMain()->getConfig();
1743 $useBlockCookie = ( $config->get( 'CookieSetOnAutoblock' ) === true );
1744 if ( $blockIsValid && $useBlockCookie ) {
1746 $this->blockTrigger
= 'cookie-block';
1749 // If the block is not valid, remove the cookie.
1750 Block
::clearCookie( $this->getRequest()->response() );
1753 // If the block doesn't exist, remove the cookie.
1754 Block
::clearCookie( $this->getRequest()->response() );
1761 * Whether the given IP is in a DNS blacklist.
1763 * @param string $ip IP to check
1764 * @param bool $checkWhitelist Whether to check the whitelist first
1765 * @return bool True if blacklisted.
1767 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1768 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1770 if ( !$wgEnableDnsBlacklist ) {
1774 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1778 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1782 * Whether the given IP is in a given DNS blacklist.
1784 * @param string $ip IP to check
1785 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1786 * @return bool True if blacklisted.
1788 public function inDnsBlacklist( $ip, $bases ) {
1790 // @todo FIXME: IPv6 ??? (https://bugs.php.net/bug.php?id=33170)
1791 if ( IP
::isIPv4( $ip ) ) {
1792 // Reverse IP, T23255
1793 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1795 foreach ( (array)$bases as $base ) {
1797 // If we have an access key, use that too (ProjectHoneypot, etc.)
1799 if ( is_array( $base ) ) {
1800 if ( count( $base ) >= 2 ) {
1801 // Access key is 1, base URL is 0
1802 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1804 $host = "$ipReversed.{$base[0]}";
1806 $basename = $base[0];
1808 $host = "$ipReversed.$base";
1812 $ipList = gethostbynamel( $host );
1815 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
1819 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
1828 * Check if an IP address is in the local proxy list
1834 public static function isLocallyBlockedProxy( $ip ) {
1835 global $wgProxyList;
1837 if ( !$wgProxyList ) {
1841 if ( !is_array( $wgProxyList ) ) {
1842 // Load values from the specified file
1843 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1846 if ( is_array( $wgProxyList ) ) {
1848 // Look for IP as value
1849 array_search( $ip, $wgProxyList ) !== false ||
1850 // Look for IP as key (for backwards-compatility)
1851 array_key_exists( $ip, $wgProxyList )
1861 * Is this user subject to rate limiting?
1863 * @return bool True if rate limited
1865 public function isPingLimitable() {
1866 global $wgRateLimitsExcludedIPs;
1867 if ( IP
::isInRanges( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1868 // No other good way currently to disable rate limits
1869 // for specific IPs. :P
1870 // But this is a crappy hack and should die.
1873 return !$this->isAllowed( 'noratelimit' );
1877 * Primitive rate limits: enforce maximum actions per time period
1878 * to put a brake on flooding.
1880 * The method generates both a generic profiling point and a per action one
1881 * (suffix being "-$action".
1883 * @note When using a shared cache like memcached, IP-address
1884 * last-hit counters will be shared across wikis.
1886 * @param string $action Action to enforce; 'edit' if unspecified
1887 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1888 * @return bool True if a rate limiter was tripped
1890 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1891 // Avoid PHP 7.1 warning of passing $this by reference
1893 // Call the 'PingLimiter' hook
1895 if ( !Hooks
::run( 'PingLimiter', [ &$user, $action, &$result, $incrBy ] ) ) {
1899 global $wgRateLimits;
1900 if ( !isset( $wgRateLimits[$action] ) ) {
1904 $limits = array_merge(
1905 [ '&can-bypass' => true ],
1906 $wgRateLimits[$action]
1909 // Some groups shouldn't trigger the ping limiter, ever
1910 if ( $limits['&can-bypass'] && !$this->isPingLimitable() ) {
1915 $id = $this->getId();
1917 $isNewbie = $this->isNewbie();
1921 if ( isset( $limits['anon'] ) ) {
1922 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1925 // limits for logged-in users
1926 if ( isset( $limits['user'] ) ) {
1927 $userLimit = $limits['user'];
1929 // limits for newbie logged-in users
1930 if ( $isNewbie && isset( $limits['newbie'] ) ) {
1931 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1935 // limits for anons and for newbie logged-in users
1938 if ( isset( $limits['ip'] ) ) {
1939 $ip = $this->getRequest()->getIP();
1940 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1942 // subnet-based limits
1943 if ( isset( $limits['subnet'] ) ) {
1944 $ip = $this->getRequest()->getIP();
1945 $subnet = IP
::getSubnet( $ip );
1946 if ( $subnet !== false ) {
1947 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1952 // Check for group-specific permissions
1953 // If more than one group applies, use the group with the highest limit ratio (max/period)
1954 foreach ( $this->getGroups() as $group ) {
1955 if ( isset( $limits[$group] ) ) {
1956 if ( $userLimit === false
1957 ||
$limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1959 $userLimit = $limits[$group];
1964 // Set the user limit key
1965 if ( $userLimit !== false ) {
1966 list( $max, $period ) = $userLimit;
1967 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
1968 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1971 // ip-based limits for all ping-limitable users
1972 if ( isset( $limits['ip-all'] ) ) {
1973 $ip = $this->getRequest()->getIP();
1974 // ignore if user limit is more permissive
1975 if ( $isNewbie ||
$userLimit === false
1976 ||
$limits['ip-all'][0] / $limits['ip-all'][1] > $userLimit[0] / $userLimit[1] ) {
1977 $keys["mediawiki:limiter:$action:ip-all:$ip"] = $limits['ip-all'];
1981 // subnet-based limits for all ping-limitable users
1982 if ( isset( $limits['subnet-all'] ) ) {
1983 $ip = $this->getRequest()->getIP();
1984 $subnet = IP
::getSubnet( $ip );
1985 if ( $subnet !== false ) {
1986 // ignore if user limit is more permissive
1987 if ( $isNewbie ||
$userLimit === false
1988 ||
$limits['ip-all'][0] / $limits['ip-all'][1]
1989 > $userLimit[0] / $userLimit[1] ) {
1990 $keys["mediawiki:limiter:$action:subnet-all:$subnet"] = $limits['subnet-all'];
1995 $cache = ObjectCache
::getLocalClusterInstance();
1998 foreach ( $keys as $key => $limit ) {
1999 list( $max, $period ) = $limit;
2000 $summary = "(limit $max in {$period}s)";
2001 $count = $cache->get( $key );
2004 if ( $count >= $max ) {
2005 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
2006 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
2009 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
2012 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
2013 if ( $incrBy > 0 ) {
2014 $cache->add( $key, 0, intval( $period ) ); // first ping
2017 if ( $incrBy > 0 ) {
2018 $cache->incr( $key, $incrBy );
2026 * Check if user is blocked
2028 * @param bool $bFromSlave Whether to check the replica DB instead of
2029 * the master. Hacked from false due to horrible probs on site.
2030 * @return bool True if blocked, false otherwise
2032 public function isBlocked( $bFromSlave = true ) {
2033 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
2037 * Get the block affecting the user, or null if the user is not blocked
2039 * @param bool $bFromSlave Whether to check the replica DB instead of the master
2040 * @return Block|null
2042 public function getBlock( $bFromSlave = true ) {
2043 $this->getBlockedStatus( $bFromSlave );
2044 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
2048 * Check if user is blocked from editing a particular article
2050 * @param Title $title Title to check
2051 * @param bool $bFromSlave Whether to check the replica DB instead of the master
2054 public function isBlockedFrom( $title, $bFromSlave = false ) {
2055 global $wgBlockAllowsUTEdit;
2057 $blocked = $this->isBlocked( $bFromSlave );
2058 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
2059 // If a user's name is suppressed, they cannot make edits anywhere
2060 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName()
2061 && $title->getNamespace() == NS_USER_TALK
) {
2063 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
2066 Hooks
::run( 'UserIsBlockedFrom', [ $this, $title, &$blocked, &$allowUsertalk ] );
2072 * If user is blocked, return the name of the user who placed the block
2073 * @return string Name of blocker
2075 public function blockedBy() {
2076 $this->getBlockedStatus();
2077 return $this->mBlockedby
;
2081 * If user is blocked, return the specified reason for the block
2082 * @return string Blocking reason
2084 public function blockedFor() {
2085 $this->getBlockedStatus();
2086 return $this->mBlockreason
;
2090 * If user is blocked, return the ID for the block
2091 * @return int Block ID
2093 public function getBlockId() {
2094 $this->getBlockedStatus();
2095 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
2099 * Check if user is blocked on all wikis.
2100 * Do not use for actual edit permission checks!
2101 * This is intended for quick UI checks.
2103 * @param string $ip IP address, uses current client if none given
2104 * @return bool True if blocked, false otherwise
2106 public function isBlockedGlobally( $ip = '' ) {
2107 return $this->getGlobalBlock( $ip ) instanceof Block
;
2111 * Check if user is blocked on all wikis.
2112 * Do not use for actual edit permission checks!
2113 * This is intended for quick UI checks.
2115 * @param string $ip IP address, uses current client if none given
2116 * @return Block|null Block object if blocked, null otherwise
2117 * @throws FatalError
2118 * @throws MWException
2120 public function getGlobalBlock( $ip = '' ) {
2121 if ( $this->mGlobalBlock
!== null ) {
2122 return $this->mGlobalBlock ?
: null;
2124 // User is already an IP?
2125 if ( IP
::isIPAddress( $this->getName() ) ) {
2126 $ip = $this->getName();
2128 $ip = $this->getRequest()->getIP();
2130 // Avoid PHP 7.1 warning of passing $this by reference
2134 Hooks
::run( 'UserIsBlockedGlobally', [ &$user, $ip, &$blocked, &$block ] );
2136 if ( $blocked && $block === null ) {
2137 // back-compat: UserIsBlockedGlobally didn't have $block param first
2138 $block = new Block( [
2140 'systemBlock' => 'global-block'
2144 $this->mGlobalBlock
= $blocked ?
$block : false;
2145 return $this->mGlobalBlock ?
: null;
2149 * Check if user account is locked
2151 * @return bool True if locked, false otherwise
2153 public function isLocked() {
2154 if ( $this->mLocked
!== null ) {
2155 return $this->mLocked
;
2157 // Avoid PHP 7.1 warning of passing $this by reference
2159 $authUser = AuthManager
::callLegacyAuthPlugin( 'getUserInstance', [ &$user ], null );
2160 $this->mLocked
= $authUser && $authUser->isLocked();
2161 Hooks
::run( 'UserIsLocked', [ $this, &$this->mLocked
] );
2162 return $this->mLocked
;
2166 * Check if user account is hidden
2168 * @return bool True if hidden, false otherwise
2170 public function isHidden() {
2171 if ( $this->mHideName
!== null ) {
2172 return $this->mHideName
;
2174 $this->getBlockedStatus();
2175 if ( !$this->mHideName
) {
2176 // Avoid PHP 7.1 warning of passing $this by reference
2178 $authUser = AuthManager
::callLegacyAuthPlugin( 'getUserInstance', [ &$user ], null );
2179 $this->mHideName
= $authUser && $authUser->isHidden();
2180 Hooks
::run( 'UserIsHidden', [ $this, &$this->mHideName
] );
2182 return $this->mHideName
;
2186 * Get the user's ID.
2187 * @return int The user's ID; 0 if the user is anonymous or nonexistent
2189 public function getId() {
2190 if ( $this->mId
=== null && $this->mName
!== null && User
::isIP( $this->mName
) ) {
2191 // Special case, we know the user is anonymous
2193 } elseif ( !$this->isItemLoaded( 'id' ) ) {
2194 // Don't load if this was initialized from an ID
2198 return (int)$this->mId
;
2202 * Set the user and reload all fields according to a given ID
2203 * @param int $v User ID to reload
2205 public function setId( $v ) {
2207 $this->clearInstanceCache( 'id' );
2211 * Get the user name, or the IP of an anonymous user
2212 * @return string User's name or IP address
2214 public function getName() {
2215 if ( $this->isItemLoaded( 'name', 'only' ) ) {
2216 // Special case optimisation
2217 return $this->mName
;
2220 if ( $this->mName
=== false ) {
2222 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
2224 return $this->mName
;
2229 * Set the user name.
2231 * This does not reload fields from the database according to the given
2232 * name. Rather, it is used to create a temporary "nonexistent user" for
2233 * later addition to the database. It can also be used to set the IP
2234 * address for an anonymous user to something other than the current
2237 * @note User::newFromName() has roughly the same function, when the named user
2239 * @param string $str New user name to set
2241 public function setName( $str ) {
2243 $this->mName
= $str;
2247 * Get the user's name escaped by underscores.
2248 * @return string Username escaped by underscores.
2250 public function getTitleKey() {
2251 return str_replace( ' ', '_', $this->getName() );
2255 * Check if the user has new messages.
2256 * @return bool True if the user has new messages
2258 public function getNewtalk() {
2261 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2262 if ( $this->mNewtalk
=== -1 ) {
2263 $this->mNewtalk
= false; # reset talk page status
2265 // Check memcached separately for anons, who have no
2266 // entire User object stored in there.
2267 if ( !$this->mId
) {
2268 global $wgDisableAnonTalk;
2269 if ( $wgDisableAnonTalk ) {
2270 // Anon newtalk disabled by configuration.
2271 $this->mNewtalk
= false;
2273 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
2276 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2280 return (bool)$this->mNewtalk
;
2284 * Return the data needed to construct links for new talk page message
2285 * alerts. If there are new messages, this will return an associative array
2286 * with the following data:
2287 * wiki: The database name of the wiki
2288 * link: Root-relative link to the user's talk page
2289 * rev: The last talk page revision that the user has seen or null. This
2290 * is useful for building diff links.
2291 * If there are no new messages, it returns an empty array.
2292 * @note This function was designed to accomodate multiple talk pages, but
2293 * currently only returns a single link and revision.
2296 public function getNewMessageLinks() {
2297 // Avoid PHP 7.1 warning of passing $this by reference
2300 if ( !Hooks
::run( 'UserRetrieveNewTalks', [ &$user, &$talks ] ) ) {
2302 } elseif ( !$this->getNewtalk() ) {
2305 $utp = $this->getTalkPage();
2306 $dbr = wfGetDB( DB_REPLICA
);
2307 // Get the "last viewed rev" timestamp from the oldest message notification
2308 $timestamp = $dbr->selectField( 'user_newtalk',
2309 'MIN(user_last_timestamp)',
2310 $this->isAnon() ?
[ 'user_ip' => $this->getName() ] : [ 'user_id' => $this->getId() ],
2312 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2313 return [ [ 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ] ];
2317 * Get the revision ID for the last talk page revision viewed by the talk
2319 * @return int|null Revision ID or null
2321 public function getNewMessageRevisionId() {
2322 $newMessageRevisionId = null;
2323 $newMessageLinks = $this->getNewMessageLinks();
2324 if ( $newMessageLinks ) {
2325 // Note: getNewMessageLinks() never returns more than a single link
2326 // and it is always for the same wiki, but we double-check here in
2327 // case that changes some time in the future.
2328 if ( count( $newMessageLinks ) === 1
2329 && $newMessageLinks[0]['wiki'] === wfWikiID()
2330 && $newMessageLinks[0]['rev']
2332 /** @var Revision $newMessageRevision */
2333 $newMessageRevision = $newMessageLinks[0]['rev'];
2334 $newMessageRevisionId = $newMessageRevision->getId();
2337 return $newMessageRevisionId;
2341 * Internal uncached check for new messages
2344 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2345 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2346 * @return bool True if the user has new messages
2348 protected function checkNewtalk( $field, $id ) {
2349 $dbr = wfGetDB( DB_REPLICA
);
2351 $ok = $dbr->selectField( 'user_newtalk', $field, [ $field => $id ], __METHOD__
);
2353 return $ok !== false;
2357 * Add or update the new messages flag
2358 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2359 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2360 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2361 * @return bool True if successful, false otherwise
2363 protected function updateNewtalk( $field, $id, $curRev = null ) {
2364 // Get timestamp of the talk page revision prior to the current one
2365 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2366 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2367 // Mark the user as having new messages since this revision
2368 $dbw = wfGetDB( DB_MASTER
);
2369 $dbw->insert( 'user_newtalk',
2370 [ $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ],
2373 if ( $dbw->affectedRows() ) {
2374 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2377 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2383 * Clear the new messages flag for the given user
2384 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2385 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2386 * @return bool True if successful, false otherwise
2388 protected function deleteNewtalk( $field, $id ) {
2389 $dbw = wfGetDB( DB_MASTER
);
2390 $dbw->delete( 'user_newtalk',
2393 if ( $dbw->affectedRows() ) {
2394 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2397 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2403 * Update the 'You have new messages!' status.
2404 * @param bool $val Whether the user has new messages
2405 * @param Revision $curRev New, as yet unseen revision of the user talk
2406 * page. Ignored if null or !$val.
2408 public function setNewtalk( $val, $curRev = null ) {
2409 if ( wfReadOnly() ) {
2414 $this->mNewtalk
= $val;
2416 if ( $this->isAnon() ) {
2418 $id = $this->getName();
2421 $id = $this->getId();
2425 $changed = $this->updateNewtalk( $field, $id, $curRev );
2427 $changed = $this->deleteNewtalk( $field, $id );
2431 $this->invalidateCache();
2436 * Generate a current or new-future timestamp to be stored in the
2437 * user_touched field when we update things.
2438 * @return string Timestamp in TS_MW format
2440 private function newTouchedTimestamp() {
2441 global $wgClockSkewFudge;
2443 $time = wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2444 if ( $this->mTouched
&& $time <= $this->mTouched
) {
2445 $time = wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $this->mTouched
) +
1 );
2452 * Clear user data from memcached
2454 * Use after applying updates to the database; caller's
2455 * responsibility to update user_touched if appropriate.
2457 * Called implicitly from invalidateCache() and saveSettings().
2459 * @param string $mode Use 'refresh' to clear now; otherwise before DB commit
2461 public function clearSharedCache( $mode = 'changed' ) {
2462 if ( !$this->getId() ) {
2466 $cache = ObjectCache
::getMainWANInstance();
2467 $key = $this->getCacheKey( $cache );
2468 if ( $mode === 'refresh' ) {
2469 $cache->delete( $key, 1 );
2471 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle(
2472 function() use ( $cache, $key ) {
2473 $cache->delete( $key );
2481 * Immediately touch the user data cache for this account
2483 * Calls touch() and removes account data from memcached
2485 public function invalidateCache() {
2487 $this->clearSharedCache();
2491 * Update the "touched" timestamp for the user
2493 * This is useful on various login/logout events when making sure that
2494 * a browser or proxy that has multiple tenants does not suffer cache
2495 * pollution where the new user sees the old users content. The value
2496 * of getTouched() is checked when determining 304 vs 200 responses.
2497 * Unlike invalidateCache(), this preserves the User object cache and
2498 * avoids database writes.
2502 public function touch() {
2503 $id = $this->getId();
2505 $key = wfMemcKey( 'user-quicktouched', 'id', $id );
2506 ObjectCache
::getMainWANInstance()->touchCheckKey( $key );
2507 $this->mQuickTouched
= null;
2512 * Validate the cache for this account.
2513 * @param string $timestamp A timestamp in TS_MW format
2516 public function validateCache( $timestamp ) {
2517 return ( $timestamp >= $this->getTouched() );
2521 * Get the user touched timestamp
2523 * Use this value only to validate caches via inequalities
2524 * such as in the case of HTTP If-Modified-Since response logic
2526 * @return string TS_MW Timestamp
2528 public function getTouched() {
2532 if ( $this->mQuickTouched
=== null ) {
2533 $key = wfMemcKey( 'user-quicktouched', 'id', $this->mId
);
2534 $cache = ObjectCache
::getMainWANInstance();
2536 $this->mQuickTouched
= wfTimestamp( TS_MW
, $cache->getCheckKeyTime( $key ) );
2539 return max( $this->mTouched
, $this->mQuickTouched
);
2542 return $this->mTouched
;
2546 * Get the user_touched timestamp field (time of last DB updates)
2547 * @return string TS_MW Timestamp
2550 public function getDBTouched() {
2553 return $this->mTouched
;
2557 * Set the password and reset the random token.
2558 * Calls through to authentication plugin if necessary;
2559 * will have no effect if the auth plugin refuses to
2560 * pass the change through or if the legal password
2563 * As a special case, setting the password to null
2564 * wipes it, so the account cannot be logged in until
2565 * a new password is set, for instance via e-mail.
2567 * @deprecated since 1.27, use AuthManager instead
2568 * @param string $str New password to set
2569 * @throws PasswordError On failure
2572 public function setPassword( $str ) {
2573 return $this->setPasswordInternal( $str );
2577 * Set the password and reset the random token unconditionally.
2579 * @deprecated since 1.27, use AuthManager instead
2580 * @param string|null $str New password to set or null to set an invalid
2581 * password hash meaning that the user will not be able to log in
2582 * through the web interface.
2584 public function setInternalPassword( $str ) {
2585 $this->setPasswordInternal( $str );
2589 * Actually set the password and such
2590 * @since 1.27 cannot set a password for a user not in the database
2591 * @param string|null $str New password to set or null to set an invalid
2592 * password hash meaning that the user will not be able to log in
2593 * through the web interface.
2594 * @return bool Success
2596 private function setPasswordInternal( $str ) {
2597 $manager = AuthManager
::singleton();
2599 // If the user doesn't exist yet, fail
2600 if ( !$manager->userExists( $this->getName() ) ) {
2601 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2604 $status = $this->changeAuthenticationData( [
2605 'username' => $this->getName(),
2609 if ( !$status->isGood() ) {
2610 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
2611 ->info( __METHOD__
. ': Password change rejected: '
2612 . $status->getWikiText( null, null, 'en' ) );
2616 $this->setOption( 'watchlisttoken', false );
2617 SessionManager
::singleton()->invalidateSessionsForUser( $this );
2623 * Changes credentials of the user.
2625 * This is a convenience wrapper around AuthManager::changeAuthenticationData.
2626 * Note that this can return a status that isOK() but not isGood() on certain types of failures,
2627 * e.g. when no provider handled the change.
2629 * @param array $data A set of authentication data in fieldname => value format. This is the
2630 * same data you would pass the changeauthenticationdata API - 'username', 'password' etc.
2634 public function changeAuthenticationData( array $data ) {
2635 $manager = AuthManager
::singleton();
2636 $reqs = $manager->getAuthenticationRequests( AuthManager
::ACTION_CHANGE
, $this );
2637 $reqs = AuthenticationRequest
::loadRequestsFromSubmission( $reqs, $data );
2639 $status = Status
::newGood( 'ignored' );
2640 foreach ( $reqs as $req ) {
2641 $status->merge( $manager->allowsAuthenticationDataChange( $req ), true );
2643 if ( $status->getValue() === 'ignored' ) {
2644 $status->warning( 'authenticationdatachange-ignored' );
2647 if ( $status->isGood() ) {
2648 foreach ( $reqs as $req ) {
2649 $manager->changeAuthenticationData( $req );
2656 * Get the user's current token.
2657 * @param bool $forceCreation Force the generation of a new token if the
2658 * user doesn't have one (default=true for backwards compatibility).
2659 * @return string|null Token
2661 public function getToken( $forceCreation = true ) {
2662 global $wgAuthenticationTokenVersion;
2665 if ( !$this->mToken
&& $forceCreation ) {
2669 if ( !$this->mToken
) {
2670 // The user doesn't have a token, return null to indicate that.
2672 } elseif ( $this->mToken
=== self
::INVALID_TOKEN
) {
2673 // We return a random value here so existing token checks are very
2675 return MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2676 } elseif ( $wgAuthenticationTokenVersion === null ) {
2677 // $wgAuthenticationTokenVersion not in use, so return the raw secret
2678 return $this->mToken
;
2680 // $wgAuthenticationTokenVersion in use, so hmac it.
2681 $ret = MWCryptHash
::hmac( $wgAuthenticationTokenVersion, $this->mToken
, false );
2683 // The raw hash can be overly long. Shorten it up.
2684 $len = max( 32, self
::TOKEN_LENGTH
);
2685 if ( strlen( $ret ) < $len ) {
2686 // Should never happen, even md5 is 128 bits
2687 throw new \
UnexpectedValueException( 'Hmac returned less than 128 bits' );
2689 return substr( $ret, -$len );
2694 * Set the random token (used for persistent authentication)
2695 * Called from loadDefaults() among other places.
2697 * @param string|bool $token If specified, set the token to this value
2699 public function setToken( $token = false ) {
2701 if ( $this->mToken
=== self
::INVALID_TOKEN
) {
2702 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
2703 ->debug( __METHOD__
. ": Ignoring attempt to set token for system user \"$this\"" );
2704 } elseif ( !$token ) {
2705 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2707 $this->mToken
= $token;
2712 * Set the password for a password reminder or new account email
2714 * @deprecated Removed in 1.27. Use PasswordReset instead.
2715 * @param string $str New password to set or null to set an invalid
2716 * password hash meaning that the user will not be able to use it
2717 * @param bool $throttle If true, reset the throttle timestamp to the present
2719 public function setNewpassword( $str, $throttle = true ) {
2720 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2724 * Get the user's e-mail address
2725 * @return string User's email address
2727 public function getEmail() {
2729 Hooks
::run( 'UserGetEmail', [ $this, &$this->mEmail
] );
2730 return $this->mEmail
;
2734 * Get the timestamp of the user's e-mail authentication
2735 * @return string TS_MW timestamp
2737 public function getEmailAuthenticationTimestamp() {
2739 Hooks
::run( 'UserGetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
2740 return $this->mEmailAuthenticated
;
2744 * Set the user's e-mail address
2745 * @param string $str New e-mail address
2747 public function setEmail( $str ) {
2749 if ( $str == $this->mEmail
) {
2752 $this->invalidateEmail();
2753 $this->mEmail
= $str;
2754 Hooks
::run( 'UserSetEmail', [ $this, &$this->mEmail
] );
2758 * Set the user's e-mail address and a confirmation mail if needed.
2761 * @param string $str New e-mail address
2764 public function setEmailWithConfirmation( $str ) {
2765 global $wgEnableEmail, $wgEmailAuthentication;
2767 if ( !$wgEnableEmail ) {
2768 return Status
::newFatal( 'emaildisabled' );
2771 $oldaddr = $this->getEmail();
2772 if ( $str === $oldaddr ) {
2773 return Status
::newGood( true );
2776 $type = $oldaddr != '' ?
'changed' : 'set';
2777 $notificationResult = null;
2779 if ( $wgEmailAuthentication ) {
2780 // Send the user an email notifying the user of the change in registered
2781 // email address on their previous email address
2782 if ( $type == 'changed' ) {
2783 $change = $str != '' ?
'changed' : 'removed';
2784 $notificationResult = $this->sendMail(
2785 wfMessage( 'notificationemail_subject_' . $change )->text(),
2786 wfMessage( 'notificationemail_body_' . $change,
2787 $this->getRequest()->getIP(),
2794 $this->setEmail( $str );
2796 if ( $str !== '' && $wgEmailAuthentication ) {
2797 // Send a confirmation request to the new address if needed
2798 $result = $this->sendConfirmationMail( $type );
2800 if ( $notificationResult !== null ) {
2801 $result->merge( $notificationResult );
2804 if ( $result->isGood() ) {
2805 // Say to the caller that a confirmation and notification mail has been sent
2806 $result->value
= 'eauth';
2809 $result = Status
::newGood( true );
2816 * Get the user's real name
2817 * @return string User's real name
2819 public function getRealName() {
2820 if ( !$this->isItemLoaded( 'realname' ) ) {
2824 return $this->mRealName
;
2828 * Set the user's real name
2829 * @param string $str New real name
2831 public function setRealName( $str ) {
2833 $this->mRealName
= $str;
2837 * Get the user's current setting for a given option.
2839 * @param string $oname The option to check
2840 * @param string $defaultOverride A default value returned if the option does not exist
2841 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2842 * @return string|null User's current value for the option
2843 * @see getBoolOption()
2844 * @see getIntOption()
2846 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2847 global $wgHiddenPrefs;
2848 $this->loadOptions();
2850 # We want 'disabled' preferences to always behave as the default value for
2851 # users, even if they have set the option explicitly in their settings (ie they
2852 # set it, and then it was disabled removing their ability to change it). But
2853 # we don't want to erase the preferences in the database in case the preference
2854 # is re-enabled again. So don't touch $mOptions, just override the returned value
2855 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2856 return self
::getDefaultOption( $oname );
2859 if ( array_key_exists( $oname, $this->mOptions
) ) {
2860 return $this->mOptions
[$oname];
2862 return $defaultOverride;
2867 * Get all user's options
2869 * @param int $flags Bitwise combination of:
2870 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2871 * to the default value. (Since 1.25)
2874 public function getOptions( $flags = 0 ) {
2875 global $wgHiddenPrefs;
2876 $this->loadOptions();
2877 $options = $this->mOptions
;
2879 # We want 'disabled' preferences to always behave as the default value for
2880 # users, even if they have set the option explicitly in their settings (ie they
2881 # set it, and then it was disabled removing their ability to change it). But
2882 # we don't want to erase the preferences in the database in case the preference
2883 # is re-enabled again. So don't touch $mOptions, just override the returned value
2884 foreach ( $wgHiddenPrefs as $pref ) {
2885 $default = self
::getDefaultOption( $pref );
2886 if ( $default !== null ) {
2887 $options[$pref] = $default;
2891 if ( $flags & self
::GETOPTIONS_EXCLUDE_DEFAULTS
) {
2892 $options = array_diff_assoc( $options, self
::getDefaultOptions() );
2899 * Get the user's current setting for a given option, as a boolean value.
2901 * @param string $oname The option to check
2902 * @return bool User's current value for the option
2905 public function getBoolOption( $oname ) {
2906 return (bool)$this->getOption( $oname );
2910 * Get the user's current setting for a given option, as an integer value.
2912 * @param string $oname The option to check
2913 * @param int $defaultOverride A default value returned if the option does not exist
2914 * @return int User's current value for the option
2917 public function getIntOption( $oname, $defaultOverride = 0 ) {
2918 $val = $this->getOption( $oname );
2920 $val = $defaultOverride;
2922 return intval( $val );
2926 * Set the given option for a user.
2928 * You need to call saveSettings() to actually write to the database.
2930 * @param string $oname The option to set
2931 * @param mixed $val New value to set
2933 public function setOption( $oname, $val ) {
2934 $this->loadOptions();
2936 // Explicitly NULL values should refer to defaults
2937 if ( is_null( $val ) ) {
2938 $val = self
::getDefaultOption( $oname );
2941 $this->mOptions
[$oname] = $val;
2945 * Get a token stored in the preferences (like the watchlist one),
2946 * resetting it if it's empty (and saving changes).
2948 * @param string $oname The option name to retrieve the token from
2949 * @return string|bool User's current value for the option, or false if this option is disabled.
2950 * @see resetTokenFromOption()
2952 * @deprecated since 1.26 Applications should use the OAuth extension
2954 public function getTokenFromOption( $oname ) {
2955 global $wgHiddenPrefs;
2957 $id = $this->getId();
2958 if ( !$id ||
in_array( $oname, $wgHiddenPrefs ) ) {
2962 $token = $this->getOption( $oname );
2964 // Default to a value based on the user token to avoid space
2965 // wasted on storing tokens for all users. When this option
2966 // is set manually by the user, only then is it stored.
2967 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
2974 * Reset a token stored in the preferences (like the watchlist one).
2975 * *Does not* save user's preferences (similarly to setOption()).
2977 * @param string $oname The option name to reset the token in
2978 * @return string|bool New token value, or false if this option is disabled.
2979 * @see getTokenFromOption()
2982 public function resetTokenFromOption( $oname ) {
2983 global $wgHiddenPrefs;
2984 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2988 $token = MWCryptRand
::generateHex( 40 );
2989 $this->setOption( $oname, $token );
2994 * Return a list of the types of user options currently returned by
2995 * User::getOptionKinds().
2997 * Currently, the option kinds are:
2998 * - 'registered' - preferences which are registered in core MediaWiki or
2999 * by extensions using the UserGetDefaultOptions hook.
3000 * - 'registered-multiselect' - as above, using the 'multiselect' type.
3001 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
3002 * - 'userjs' - preferences with names starting with 'userjs-', intended to
3003 * be used by user scripts.
3004 * - 'special' - "preferences" that are not accessible via User::getOptions
3005 * or User::setOptions.
3006 * - 'unused' - preferences about which MediaWiki doesn't know anything.
3007 * These are usually legacy options, removed in newer versions.
3009 * The API (and possibly others) use this function to determine the possible
3010 * option types for validation purposes, so make sure to update this when a
3011 * new option kind is added.
3013 * @see User::getOptionKinds
3014 * @return array Option kinds
3016 public static function listOptionKinds() {
3019 'registered-multiselect',
3020 'registered-checkmatrix',
3028 * Return an associative array mapping preferences keys to the kind of a preference they're
3029 * used for. Different kinds are handled differently when setting or reading preferences.
3031 * See User::listOptionKinds for the list of valid option types that can be provided.
3033 * @see User::listOptionKinds
3034 * @param IContextSource $context
3035 * @param array $options Assoc. array with options keys to check as keys.
3036 * Defaults to $this->mOptions.
3037 * @return array The key => kind mapping data
3039 public function getOptionKinds( IContextSource
$context, $options = null ) {
3040 $this->loadOptions();
3041 if ( $options === null ) {
3042 $options = $this->mOptions
;
3045 $prefs = Preferences
::getPreferences( $this, $context );
3048 // Pull out the "special" options, so they don't get converted as
3049 // multiselect or checkmatrix.
3050 $specialOptions = array_fill_keys( Preferences
::getSaveBlacklist(), true );
3051 foreach ( $specialOptions as $name => $value ) {
3052 unset( $prefs[$name] );
3055 // Multiselect and checkmatrix options are stored in the database with
3056 // one key per option, each having a boolean value. Extract those keys.
3057 $multiselectOptions = [];
3058 foreach ( $prefs as $name => $info ) {
3059 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
3060 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
3061 $opts = HTMLFormField
::flattenOptions( $info['options'] );
3062 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
3064 foreach ( $opts as $value ) {
3065 $multiselectOptions["$prefix$value"] = true;
3068 unset( $prefs[$name] );
3071 $checkmatrixOptions = [];
3072 foreach ( $prefs as $name => $info ) {
3073 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
3074 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
3075 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
3076 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
3077 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
3079 foreach ( $columns as $column ) {
3080 foreach ( $rows as $row ) {
3081 $checkmatrixOptions["$prefix$column-$row"] = true;
3085 unset( $prefs[$name] );
3089 // $value is ignored
3090 foreach ( $options as $key => $value ) {
3091 if ( isset( $prefs[$key] ) ) {
3092 $mapping[$key] = 'registered';
3093 } elseif ( isset( $multiselectOptions[$key] ) ) {
3094 $mapping[$key] = 'registered-multiselect';
3095 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
3096 $mapping[$key] = 'registered-checkmatrix';
3097 } elseif ( isset( $specialOptions[$key] ) ) {
3098 $mapping[$key] = 'special';
3099 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
3100 $mapping[$key] = 'userjs';
3102 $mapping[$key] = 'unused';
3110 * Reset certain (or all) options to the site defaults
3112 * The optional parameter determines which kinds of preferences will be reset.
3113 * Supported values are everything that can be reported by getOptionKinds()
3114 * and 'all', which forces a reset of *all* preferences and overrides everything else.
3116 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
3117 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
3118 * for backwards-compatibility.
3119 * @param IContextSource|null $context Context source used when $resetKinds
3120 * does not contain 'all', passed to getOptionKinds().
3121 * Defaults to RequestContext::getMain() when null.
3123 public function resetOptions(
3124 $resetKinds = [ 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ],
3125 IContextSource
$context = null
3128 $defaultOptions = self
::getDefaultOptions();
3130 if ( !is_array( $resetKinds ) ) {
3131 $resetKinds = [ $resetKinds ];
3134 if ( in_array( 'all', $resetKinds ) ) {
3135 $newOptions = $defaultOptions;
3137 if ( $context === null ) {
3138 $context = RequestContext
::getMain();
3141 $optionKinds = $this->getOptionKinds( $context );
3142 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
3145 // Use default values for the options that should be deleted, and
3146 // copy old values for the ones that shouldn't.
3147 foreach ( $this->mOptions
as $key => $value ) {
3148 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
3149 if ( array_key_exists( $key, $defaultOptions ) ) {
3150 $newOptions[$key] = $defaultOptions[$key];
3153 $newOptions[$key] = $value;
3158 Hooks
::run( 'UserResetAllOptions', [ $this, &$newOptions, $this->mOptions
, $resetKinds ] );
3160 $this->mOptions
= $newOptions;
3161 $this->mOptionsLoaded
= true;
3165 * Get the user's preferred date format.
3166 * @return string User's preferred date format
3168 public function getDatePreference() {
3169 // Important migration for old data rows
3170 if ( is_null( $this->mDatePreference
) ) {
3172 $value = $this->getOption( 'date' );
3173 $map = $wgLang->getDatePreferenceMigrationMap();
3174 if ( isset( $map[$value] ) ) {
3175 $value = $map[$value];
3177 $this->mDatePreference
= $value;
3179 return $this->mDatePreference
;
3183 * Determine based on the wiki configuration and the user's options,
3184 * whether this user must be over HTTPS no matter what.
3188 public function requiresHTTPS() {
3189 global $wgSecureLogin;
3190 if ( !$wgSecureLogin ) {
3193 $https = $this->getBoolOption( 'prefershttps' );
3194 Hooks
::run( 'UserRequiresHTTPS', [ $this, &$https ] );
3196 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
3203 * Get the user preferred stub threshold
3207 public function getStubThreshold() {
3208 global $wgMaxArticleSize; # Maximum article size, in Kb
3209 $threshold = $this->getIntOption( 'stubthreshold' );
3210 if ( $threshold > $wgMaxArticleSize * 1024 ) {
3211 // If they have set an impossible value, disable the preference
3212 // so we can use the parser cache again.
3219 * Get the permissions this user has.
3220 * @return string[] permission names
3222 public function getRights() {
3223 if ( is_null( $this->mRights
) ) {
3224 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
3225 Hooks
::run( 'UserGetRights', [ $this, &$this->mRights
] );
3227 // Deny any rights denied by the user's session, unless this
3228 // endpoint has no sessions.
3229 if ( !defined( 'MW_NO_SESSION' ) ) {
3230 $allowedRights = $this->getRequest()->getSession()->getAllowedUserRights();
3231 if ( $allowedRights !== null ) {
3232 $this->mRights
= array_intersect( $this->mRights
, $allowedRights );
3236 // Force reindexation of rights when a hook has unset one of them
3237 $this->mRights
= array_values( array_unique( $this->mRights
) );
3239 // If block disables login, we should also remove any
3240 // extra rights blocked users might have, in case the
3241 // blocked user has a pre-existing session (T129738).
3242 // This is checked here for cases where people only call
3243 // $user->isAllowed(). It is also checked in Title::checkUserBlock()
3244 // to give a better error message in the common case.
3245 $config = RequestContext
::getMain()->getConfig();
3247 $this->isLoggedIn() &&
3248 $config->get( 'BlockDisablesLogin' ) &&
3252 $this->mRights
= array_intersect( $this->mRights
, $anon->getRights() );
3255 return $this->mRights
;
3259 * Get the list of explicit group memberships this user has.
3260 * The implicit * and user groups are not included.
3261 * @return array Array of String internal group names
3263 public function getGroups() {
3265 $this->loadGroups();
3266 return array_keys( $this->mGroupMemberships
);
3270 * Get the list of explicit group memberships this user has, stored as
3271 * UserGroupMembership objects. Implicit groups are not included.
3273 * @return array Associative array of (group name as string => UserGroupMembership object)
3276 public function getGroupMemberships() {
3278 $this->loadGroups();
3279 return $this->mGroupMemberships
;
3283 * Get the list of implicit group memberships this user has.
3284 * This includes all explicit groups, plus 'user' if logged in,
3285 * '*' for all accounts, and autopromoted groups
3286 * @param bool $recache Whether to avoid the cache
3287 * @return array Array of String internal group names
3289 public function getEffectiveGroups( $recache = false ) {
3290 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
3291 $this->mEffectiveGroups
= array_unique( array_merge(
3292 $this->getGroups(), // explicit groups
3293 $this->getAutomaticGroups( $recache ) // implicit groups
3295 // Avoid PHP 7.1 warning of passing $this by reference
3297 // Hook for additional groups
3298 Hooks
::run( 'UserEffectiveGroups', [ &$user, &$this->mEffectiveGroups
] );
3299 // Force reindexation of groups when a hook has unset one of them
3300 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
3302 return $this->mEffectiveGroups
;
3306 * Get the list of implicit group memberships this user has.
3307 * This includes 'user' if logged in, '*' for all accounts,
3308 * and autopromoted groups
3309 * @param bool $recache Whether to avoid the cache
3310 * @return array Array of String internal group names
3312 public function getAutomaticGroups( $recache = false ) {
3313 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
3314 $this->mImplicitGroups
= [ '*' ];
3315 if ( $this->getId() ) {
3316 $this->mImplicitGroups
[] = 'user';
3318 $this->mImplicitGroups
= array_unique( array_merge(
3319 $this->mImplicitGroups
,
3320 Autopromote
::getAutopromoteGroups( $this )
3324 // Assure data consistency with rights/groups,
3325 // as getEffectiveGroups() depends on this function
3326 $this->mEffectiveGroups
= null;
3329 return $this->mImplicitGroups
;
3333 * Returns the groups the user has belonged to.
3335 * The user may still belong to the returned groups. Compare with getGroups().
3337 * The function will not return groups the user had belonged to before MW 1.17
3339 * @return array Names of the groups the user has belonged to.
3341 public function getFormerGroups() {
3344 if ( is_null( $this->mFormerGroups
) ) {
3345 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3346 ?
wfGetDB( DB_MASTER
)
3347 : wfGetDB( DB_REPLICA
);
3348 $res = $db->select( 'user_former_groups',
3350 [ 'ufg_user' => $this->mId
],
3352 $this->mFormerGroups
= [];
3353 foreach ( $res as $row ) {
3354 $this->mFormerGroups
[] = $row->ufg_group
;
3358 return $this->mFormerGroups
;
3362 * Get the user's edit count.
3363 * @return int|null Null for anonymous users
3365 public function getEditCount() {
3366 if ( !$this->getId() ) {
3370 if ( $this->mEditCount
=== null ) {
3371 /* Populate the count, if it has not been populated yet */
3372 $dbr = wfGetDB( DB_REPLICA
);
3373 // check if the user_editcount field has been initialized
3374 $count = $dbr->selectField(
3375 'user', 'user_editcount',
3376 [ 'user_id' => $this->mId
],
3380 if ( $count === null ) {
3381 // it has not been initialized. do so.
3382 $count = $this->initEditCount();
3384 $this->mEditCount
= $count;
3386 return (int)$this->mEditCount
;
3390 * Add the user to the given group. This takes immediate effect.
3391 * If the user is already in the group, the expiry time will be updated to the new
3392 * expiry time. (If $expiry is omitted or null, the membership will be altered to
3395 * @param string $group Name of the group to add
3396 * @param string $expiry Optional expiry timestamp in any format acceptable to
3397 * wfTimestamp(), or null if the group assignment should not expire
3400 public function addGroup( $group, $expiry = null ) {
3402 $this->loadGroups();
3405 $expiry = wfTimestamp( TS_MW
, $expiry );
3408 if ( !Hooks
::run( 'UserAddGroup', [ $this, &$group, &$expiry ] ) ) {
3412 // create the new UserGroupMembership and put it in the DB
3413 $ugm = new UserGroupMembership( $this->mId
, $group, $expiry );
3414 if ( !$ugm->insert( true ) ) {
3418 $this->mGroupMemberships
[$group] = $ugm;
3420 // Refresh the groups caches, and clear the rights cache so it will be
3421 // refreshed on the next call to $this->getRights().
3422 $this->getEffectiveGroups( true );
3423 $this->mRights
= null;
3425 $this->invalidateCache();
3431 * Remove the user from the given group.
3432 * This takes immediate effect.
3433 * @param string $group Name of the group to remove
3436 public function removeGroup( $group ) {
3439 if ( !Hooks
::run( 'UserRemoveGroup', [ $this, &$group ] ) ) {
3443 $ugm = UserGroupMembership
::getMembership( $this->mId
, $group );
3444 // delete the membership entry
3445 if ( !$ugm ||
!$ugm->delete() ) {
3449 $this->loadGroups();
3450 unset( $this->mGroupMemberships
[$group] );
3452 // Refresh the groups caches, and clear the rights cache so it will be
3453 // refreshed on the next call to $this->getRights().
3454 $this->getEffectiveGroups( true );
3455 $this->mRights
= null;
3457 $this->invalidateCache();
3463 * Get whether the user is logged in
3466 public function isLoggedIn() {
3467 return $this->getId() != 0;
3471 * Get whether the user is anonymous
3474 public function isAnon() {
3475 return !$this->isLoggedIn();
3479 * @return bool Whether this user is flagged as being a bot role account
3482 public function isBot() {
3483 if ( in_array( 'bot', $this->getGroups() ) && $this->isAllowed( 'bot' ) ) {
3488 Hooks
::run( "UserIsBot", [ $this, &$isBot ] );
3494 * Check if user is allowed to access a feature / make an action
3496 * @param string ... Permissions to test
3497 * @return bool True if user is allowed to perform *any* of the given actions
3499 public function isAllowedAny() {
3500 $permissions = func_get_args();
3501 foreach ( $permissions as $permission ) {
3502 if ( $this->isAllowed( $permission ) ) {
3511 * @param string ... Permissions to test
3512 * @return bool True if the user is allowed to perform *all* of the given actions
3514 public function isAllowedAll() {
3515 $permissions = func_get_args();
3516 foreach ( $permissions as $permission ) {
3517 if ( !$this->isAllowed( $permission ) ) {
3525 * Internal mechanics of testing a permission
3526 * @param string $action
3529 public function isAllowed( $action = '' ) {
3530 if ( $action === '' ) {
3531 return true; // In the spirit of DWIM
3533 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3534 // by misconfiguration: 0 == 'foo'
3535 return in_array( $action, $this->getRights(), true );
3539 * Check whether to enable recent changes patrol features for this user
3540 * @return bool True or false
3542 public function useRCPatrol() {
3543 global $wgUseRCPatrol;
3544 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3548 * Check whether to enable new pages patrol features for this user
3549 * @return bool True or false
3551 public function useNPPatrol() {
3552 global $wgUseRCPatrol, $wgUseNPPatrol;
3554 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3555 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3560 * Check whether to enable new files patrol features for this user
3561 * @return bool True or false
3563 public function useFilePatrol() {
3564 global $wgUseRCPatrol, $wgUseFilePatrol;
3566 ( $wgUseRCPatrol ||
$wgUseFilePatrol )
3567 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3572 * Get the WebRequest object to use with this object
3574 * @return WebRequest
3576 public function getRequest() {
3577 if ( $this->mRequest
) {
3578 return $this->mRequest
;
3586 * Check the watched status of an article.
3587 * @since 1.22 $checkRights parameter added
3588 * @param Title $title Title of the article to look at
3589 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3590 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3593 public function isWatched( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3594 if ( $title->isWatchable() && ( !$checkRights ||
$this->isAllowed( 'viewmywatchlist' ) ) ) {
3595 return MediaWikiServices
::getInstance()->getWatchedItemStore()->isWatched( $this, $title );
3602 * @since 1.22 $checkRights parameter added
3603 * @param Title $title Title of the article to look at
3604 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3605 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3607 public function addWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3608 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3609 MediaWikiServices
::getInstance()->getWatchedItemStore()->addWatchBatchForUser(
3611 [ $title->getSubjectPage(), $title->getTalkPage() ]
3614 $this->invalidateCache();
3618 * Stop watching an article.
3619 * @since 1.22 $checkRights parameter added
3620 * @param Title $title Title of the article to look at
3621 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3622 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3624 public function removeWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3625 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3626 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
3627 $store->removeWatch( $this, $title->getSubjectPage() );
3628 $store->removeWatch( $this, $title->getTalkPage() );
3630 $this->invalidateCache();
3634 * Clear the user's notification timestamp for the given title.
3635 * If e-notif e-mails are on, they will receive notification mails on
3636 * the next change of the page if it's watched etc.
3637 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3638 * @param Title $title Title of the article to look at
3639 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3641 public function clearNotification( &$title, $oldid = 0 ) {
3642 global $wgUseEnotif, $wgShowUpdatedMarker;
3644 // Do nothing if the database is locked to writes
3645 if ( wfReadOnly() ) {
3649 // Do nothing if not allowed to edit the watchlist
3650 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3654 // If we're working on user's talk page, we should update the talk page message indicator
3655 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3656 // Avoid PHP 7.1 warning of passing $this by reference
3658 if ( !Hooks
::run( 'UserClearNewTalkNotification', [ &$user, $oldid ] ) ) {
3662 // Try to update the DB post-send and only if needed...
3663 DeferredUpdates
::addCallableUpdate( function() use ( $title, $oldid ) {
3664 if ( !$this->getNewtalk() ) {
3665 return; // no notifications to clear
3668 // Delete the last notifications (they stack up)
3669 $this->setNewtalk( false );
3671 // If there is a new, unseen, revision, use its timestamp
3673 ?
$title->getNextRevisionID( $oldid, Title
::GAID_FOR_UPDATE
)
3676 $this->setNewtalk( true, Revision
::newFromId( $nextid ) );
3681 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3685 if ( $this->isAnon() ) {
3686 // Nothing else to do...
3690 // Only update the timestamp if the page is being watched.
3691 // The query to find out if it is watched is cached both in memcached and per-invocation,
3692 // and when it does have to be executed, it can be on a replica DB
3693 // If this is the user's newtalk page, we always update the timestamp
3695 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3699 MediaWikiServices
::getInstance()->getWatchedItemStore()
3700 ->resetNotificationTimestamp( $this, $title, $force, $oldid );
3704 * Resets all of the given user's page-change notification timestamps.
3705 * If e-notif e-mails are on, they will receive notification mails on
3706 * the next change of any watched page.
3707 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3709 public function clearAllNotifications() {
3710 global $wgUseEnotif, $wgShowUpdatedMarker;
3711 // Do nothing if not allowed to edit the watchlist
3712 if ( wfReadOnly() ||
!$this->isAllowed( 'editmywatchlist' ) ) {
3716 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3717 $this->setNewtalk( false );
3721 $id = $this->getId();
3726 $dbw = wfGetDB( DB_MASTER
);
3727 $asOfTimes = array_unique( $dbw->selectFieldValues(
3729 'wl_notificationtimestamp',
3730 [ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ],
3732 [ 'ORDER BY' => 'wl_notificationtimestamp DESC', 'LIMIT' => 500 ]
3734 if ( !$asOfTimes ) {
3737 // Immediately update the most recent touched rows, which hopefully covers what
3738 // the user sees on the watchlist page before pressing "mark all pages visited"....
3741 [ 'wl_notificationtimestamp' => null ],
3742 [ 'wl_user' => $id, 'wl_notificationtimestamp' => $asOfTimes ],
3745 // ...and finish the older ones in a post-send update with lag checks...
3746 DeferredUpdates
::addUpdate( new AutoCommitUpdate(
3749 function () use ( $dbw, $id ) {
3750 global $wgUpdateRowsPerQuery;
3752 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
3753 $ticket = $lbFactory->getEmptyTransactionTicket( __METHOD__
);
3754 $asOfTimes = array_unique( $dbw->selectFieldValues(
3756 'wl_notificationtimestamp',
3757 [ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ],
3760 foreach ( array_chunk( $asOfTimes, $wgUpdateRowsPerQuery ) as $asOfTimeBatch ) {
3763 [ 'wl_notificationtimestamp' => null ],
3764 [ 'wl_user' => $id, 'wl_notificationtimestamp' => $asOfTimeBatch ],
3767 $lbFactory->commitAndWaitForReplication( __METHOD__
, $ticket );
3771 // We also need to clear here the "you have new message" notification for the own
3772 // user_talk page; it's cleared one page view later in WikiPage::doViewUpdates().
3776 * Compute experienced level based on edit count and registration date.
3778 * @return string 'newcomer', 'learner', or 'experienced'
3780 public function getExperienceLevel() {
3781 global $wgLearnerEdits,
3782 $wgExperiencedUserEdits,
3783 $wgLearnerMemberSince,
3784 $wgExperiencedUserMemberSince;
3786 if ( $this->isAnon() ) {
3790 $editCount = $this->getEditCount();
3791 $registration = $this->getRegistration();
3793 $learnerRegistration = wfTimestamp( TS_MW
, $now - $wgLearnerMemberSince * 86400 );
3794 $experiencedRegistration = wfTimestamp( TS_MW
, $now - $wgExperiencedUserMemberSince * 86400 );
3797 $editCount < $wgLearnerEdits ||
3798 $registration > $learnerRegistration
3802 $editCount > $wgExperiencedUserEdits &&
3803 $registration <= $experiencedRegistration
3805 return 'experienced';
3812 * Set a cookie on the user's client. Wrapper for
3813 * WebResponse::setCookie
3814 * @deprecated since 1.27
3815 * @param string $name Name of the cookie to set
3816 * @param string $value Value to set
3817 * @param int $exp Expiration time, as a UNIX time value;
3818 * if 0 or not specified, use the default $wgCookieExpiration
3819 * @param bool $secure
3820 * true: Force setting the secure attribute when setting the cookie
3821 * false: Force NOT setting the secure attribute when setting the cookie
3822 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3823 * @param array $params Array of options sent passed to WebResponse::setcookie()
3824 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3827 protected function setCookie(
3828 $name, $value, $exp = 0, $secure = null, $params = [], $request = null
3830 wfDeprecated( __METHOD__
, '1.27' );
3831 if ( $request === null ) {
3832 $request = $this->getRequest();
3834 $params['secure'] = $secure;
3835 $request->response()->setCookie( $name, $value, $exp, $params );
3839 * Clear a cookie on the user's client
3840 * @deprecated since 1.27
3841 * @param string $name Name of the cookie to clear
3842 * @param bool $secure
3843 * true: Force setting the secure attribute when setting the cookie
3844 * false: Force NOT setting the secure attribute when setting the cookie
3845 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3846 * @param array $params Array of options sent passed to WebResponse::setcookie()
3848 protected function clearCookie( $name, $secure = null, $params = [] ) {
3849 wfDeprecated( __METHOD__
, '1.27' );
3850 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3854 * Set an extended login cookie on the user's client. The expiry of the cookie
3855 * is controlled by the $wgExtendedLoginCookieExpiration configuration
3858 * @see User::setCookie
3860 * @deprecated since 1.27
3861 * @param string $name Name of the cookie to set
3862 * @param string $value Value to set
3863 * @param bool $secure
3864 * true: Force setting the secure attribute when setting the cookie
3865 * false: Force NOT setting the secure attribute when setting the cookie
3866 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3868 protected function setExtendedLoginCookie( $name, $value, $secure ) {
3869 global $wgExtendedLoginCookieExpiration, $wgCookieExpiration;
3871 wfDeprecated( __METHOD__
, '1.27' );
3874 $exp +
= $wgExtendedLoginCookieExpiration !== null
3875 ?
$wgExtendedLoginCookieExpiration
3876 : $wgCookieExpiration;
3878 $this->setCookie( $name, $value, $exp, $secure );
3882 * Persist this user's session (e.g. set cookies)
3884 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3886 * @param bool $secure Whether to force secure/insecure cookies or use default
3887 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3889 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3891 if ( 0 == $this->mId
) {
3895 $session = $this->getRequest()->getSession();
3896 if ( $request && $session->getRequest() !== $request ) {
3897 $session = $session->sessionWithRequest( $request );
3899 $delay = $session->delaySave();
3901 if ( !$session->getUser()->equals( $this ) ) {
3902 if ( !$session->canSetUser() ) {
3903 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3904 ->warning( __METHOD__
.
3905 ": Cannot save user \"$this\" to a user \"{$session->getUser()}\"'s immutable session"
3909 $session->setUser( $this );
3912 $session->setRememberUser( $rememberMe );
3913 if ( $secure !== null ) {
3914 $session->setForceHTTPS( $secure );
3917 $session->persist();
3919 ScopedCallback
::consume( $delay );
3923 * Log this user out.
3925 public function logout() {
3926 // Avoid PHP 7.1 warning of passing $this by reference
3928 if ( Hooks
::run( 'UserLogout', [ &$user ] ) ) {
3934 * Clear the user's session, and reset the instance cache.
3937 public function doLogout() {
3938 $session = $this->getRequest()->getSession();
3939 if ( !$session->canSetUser() ) {
3940 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3941 ->warning( __METHOD__
. ": Cannot log out of an immutable session" );
3942 $error = 'immutable';
3943 } elseif ( !$session->getUser()->equals( $this ) ) {
3944 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3945 ->warning( __METHOD__
.
3946 ": Cannot log user \"$this\" out of a user \"{$session->getUser()}\"'s session"
3948 // But we still may as well make this user object anon
3949 $this->clearInstanceCache( 'defaults' );
3950 $error = 'wronguser';
3952 $this->clearInstanceCache( 'defaults' );
3953 $delay = $session->delaySave();
3954 $session->unpersist(); // Clear cookies (T127436)
3955 $session->setLoggedOutTimestamp( time() );
3956 $session->setUser( new User
);
3957 $session->set( 'wsUserID', 0 ); // Other code expects this
3958 $session->resetAllTokens();
3959 ScopedCallback
::consume( $delay );
3962 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authevents' )->info( 'Logout', [
3963 'event' => 'logout',
3964 'successful' => $error === false,
3965 'status' => $error ?
: 'success',
3970 * Save this user's settings into the database.
3971 * @todo Only rarely do all these fields need to be set!
3973 public function saveSettings() {
3974 if ( wfReadOnly() ) {
3975 // @TODO: caller should deal with this instead!
3976 // This should really just be an exception.
3977 MWExceptionHandler
::logException( new DBExpectedError(
3979 "Could not update user with ID '{$this->mId}'; DB is read-only."
3985 if ( 0 == $this->mId
) {
3989 // Get a new user_touched that is higher than the old one.
3990 // This will be used for a CAS check as a last-resort safety
3991 // check against race conditions and replica DB lag.
3992 $newTouched = $this->newTouchedTimestamp();
3994 $dbw = wfGetDB( DB_MASTER
);
3995 $dbw->update( 'user',
3997 'user_name' => $this->mName
,
3998 'user_real_name' => $this->mRealName
,
3999 'user_email' => $this->mEmail
,
4000 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
4001 'user_touched' => $dbw->timestamp( $newTouched ),
4002 'user_token' => strval( $this->mToken
),
4003 'user_email_token' => $this->mEmailToken
,
4004 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
4005 ], $this->makeUpdateConditions( $dbw, [ /* WHERE */
4006 'user_id' => $this->mId
,
4010 if ( !$dbw->affectedRows() ) {
4011 // Maybe the problem was a missed cache update; clear it to be safe
4012 $this->clearSharedCache( 'refresh' );
4013 // User was changed in the meantime or loaded with stale data
4014 $from = ( $this->queryFlagsUsed
& self
::READ_LATEST
) ?
'master' : 'replica';
4015 throw new MWException(
4016 "CAS update failed on user_touched for user ID '{$this->mId}' (read from $from);" .
4017 " the version of the user to be saved is older than the current version."
4021 $this->mTouched
= $newTouched;
4022 $this->saveOptions();
4024 Hooks
::run( 'UserSaveSettings', [ $this ] );
4025 $this->clearSharedCache();
4026 $this->getUserPage()->invalidateCache();
4030 * If only this user's username is known, and it exists, return the user ID.
4032 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
4035 public function idForName( $flags = 0 ) {
4036 $s = trim( $this->getName() );
4041 $db = ( ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
)
4042 ?
wfGetDB( DB_MASTER
)
4043 : wfGetDB( DB_REPLICA
);
4045 $options = ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
)
4046 ?
[ 'LOCK IN SHARE MODE' ]
4049 $id = $db->selectField( 'user',
4050 'user_id', [ 'user_name' => $s ], __METHOD__
, $options );
4056 * Add a user to the database, return the user object
4058 * @param string $name Username to add
4059 * @param array $params Array of Strings Non-default parameters to save to
4060 * the database as user_* fields:
4061 * - email: The user's email address.
4062 * - email_authenticated: The email authentication timestamp.
4063 * - real_name: The user's real name.
4064 * - options: An associative array of non-default options.
4065 * - token: Random authentication token. Do not set.
4066 * - registration: Registration timestamp. Do not set.
4068 * @return User|null User object, or null if the username already exists.
4070 public static function createNew( $name, $params = [] ) {
4071 foreach ( [ 'password', 'newpassword', 'newpass_time', 'password_expires' ] as $field ) {
4072 if ( isset( $params[$field] ) ) {
4073 wfDeprecated( __METHOD__
. " with param '$field'", '1.27' );
4074 unset( $params[$field] );
4080 $user->setToken(); // init token
4081 if ( isset( $params['options'] ) ) {
4082 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
4083 unset( $params['options'] );
4085 $dbw = wfGetDB( DB_MASTER
);
4086 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
4088 $noPass = PasswordFactory
::newInvalidPassword()->toString();
4091 'user_id' => $seqVal,
4092 'user_name' => $name,
4093 'user_password' => $noPass,
4094 'user_newpassword' => $noPass,
4095 'user_email' => $user->mEmail
,
4096 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
4097 'user_real_name' => $user->mRealName
,
4098 'user_token' => strval( $user->mToken
),
4099 'user_registration' => $dbw->timestamp( $user->mRegistration
),
4100 'user_editcount' => 0,
4101 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
4103 foreach ( $params as $name => $value ) {
4104 $fields["user_$name"] = $value;
4106 $dbw->insert( 'user', $fields, __METHOD__
, [ 'IGNORE' ] );
4107 if ( $dbw->affectedRows() ) {
4108 $newUser = User
::newFromId( $dbw->insertId() );
4116 * Add this existing user object to the database. If the user already
4117 * exists, a fatal status object is returned, and the user object is
4118 * initialised with the data from the database.
4120 * Previously, this function generated a DB error due to a key conflict
4121 * if the user already existed. Many extension callers use this function
4122 * in code along the lines of:
4124 * $user = User::newFromName( $name );
4125 * if ( !$user->isLoggedIn() ) {
4126 * $user->addToDatabase();
4128 * // do something with $user...
4130 * However, this was vulnerable to a race condition (T18020). By
4131 * initialising the user object if the user exists, we aim to support this
4132 * calling sequence as far as possible.
4134 * Note that if the user exists, this function will acquire a write lock,
4135 * so it is still advisable to make the call conditional on isLoggedIn(),
4136 * and to commit the transaction after calling.
4138 * @throws MWException
4141 public function addToDatabase() {
4143 if ( !$this->mToken
) {
4144 $this->setToken(); // init token
4147 $this->mTouched
= $this->newTouchedTimestamp();
4149 $noPass = PasswordFactory
::newInvalidPassword()->toString();
4151 $dbw = wfGetDB( DB_MASTER
);
4152 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
4153 $dbw->insert( 'user',
4155 'user_id' => $seqVal,
4156 'user_name' => $this->mName
,
4157 'user_password' => $noPass,
4158 'user_newpassword' => $noPass,
4159 'user_email' => $this->mEmail
,
4160 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
4161 'user_real_name' => $this->mRealName
,
4162 'user_token' => strval( $this->mToken
),
4163 'user_registration' => $dbw->timestamp( $this->mRegistration
),
4164 'user_editcount' => 0,
4165 'user_touched' => $dbw->timestamp( $this->mTouched
),
4169 if ( !$dbw->affectedRows() ) {
4170 // Use locking reads to bypass any REPEATABLE-READ snapshot.
4171 $this->mId
= $dbw->selectField(
4174 [ 'user_name' => $this->mName
],
4176 [ 'LOCK IN SHARE MODE' ]
4180 if ( $this->loadFromDatabase( self
::READ_LOCKING
) ) {
4185 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
4186 "to insert user '{$this->mName}' row, but it was not present in select!" );
4188 return Status
::newFatal( 'userexists' );
4190 $this->mId
= $dbw->insertId();
4191 self
::$idCacheByName[$this->mName
] = $this->mId
;
4193 // Clear instance cache other than user table data, which is already accurate
4194 $this->clearInstanceCache();
4196 $this->saveOptions();
4197 return Status
::newGood();
4201 * If this user is logged-in and blocked,
4202 * block any IP address they've successfully logged in from.
4203 * @return bool A block was spread
4205 public function spreadAnyEditBlock() {
4206 if ( $this->isLoggedIn() && $this->isBlocked() ) {
4207 return $this->spreadBlock();
4214 * If this (non-anonymous) user is blocked,
4215 * block the IP address they've successfully logged in from.
4216 * @return bool A block was spread
4218 protected function spreadBlock() {
4219 wfDebug( __METHOD__
. "()\n" );
4221 if ( $this->mId
== 0 ) {
4225 $userblock = Block
::newFromTarget( $this->getName() );
4226 if ( !$userblock ) {
4230 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
4234 * Get whether the user is explicitly blocked from account creation.
4235 * @return bool|Block
4237 public function isBlockedFromCreateAccount() {
4238 $this->getBlockedStatus();
4239 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
4240 return $this->mBlock
;
4243 # T15611: if the IP address the user is trying to create an account from is
4244 # blocked with createaccount disabled, prevent new account creation there even
4245 # when the user is logged in
4246 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
4247 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
4249 return $this->mBlockedFromCreateAccount
instanceof Block
4250 && $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
4251 ?
$this->mBlockedFromCreateAccount
4256 * Get whether the user is blocked from using Special:Emailuser.
4259 public function isBlockedFromEmailuser() {
4260 $this->getBlockedStatus();
4261 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
4265 * Get whether the user is allowed to create an account.
4268 public function isAllowedToCreateAccount() {
4269 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
4273 * Get this user's personal page title.
4275 * @return Title User's personal page title
4277 public function getUserPage() {
4278 return Title
::makeTitle( NS_USER
, $this->getName() );
4282 * Get this user's talk page title.
4284 * @return Title User's talk page title
4286 public function getTalkPage() {
4287 $title = $this->getUserPage();
4288 return $title->getTalkPage();
4292 * Determine whether the user is a newbie. Newbies are either
4293 * anonymous IPs, or the most recently created accounts.
4296 public function isNewbie() {
4297 return !$this->isAllowed( 'autoconfirmed' );
4301 * Check to see if the given clear-text password is one of the accepted passwords
4302 * @deprecated since 1.27, use AuthManager instead
4303 * @param string $password User password
4304 * @return bool True if the given password is correct, otherwise False
4306 public function checkPassword( $password ) {
4307 $manager = AuthManager
::singleton();
4308 $reqs = AuthenticationRequest
::loadRequestsFromSubmission(
4309 $manager->getAuthenticationRequests( AuthManager
::ACTION_LOGIN
),
4311 'username' => $this->getName(),
4312 'password' => $password,
4315 $res = AuthManager
::singleton()->beginAuthentication( $reqs, 'null:' );
4316 switch ( $res->status
) {
4317 case AuthenticationResponse
::PASS
:
4319 case AuthenticationResponse
::FAIL
:
4320 // Hope it's not a PreAuthenticationProvider that failed...
4321 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
4322 ->info( __METHOD__
. ': Authentication failed: ' . $res->message
->plain() );
4325 throw new BadMethodCallException(
4326 'AuthManager returned a response unsupported by ' . __METHOD__
4332 * Check if the given clear-text password matches the temporary password
4333 * sent by e-mail for password reset operations.
4335 * @deprecated since 1.27, use AuthManager instead
4336 * @param string $plaintext
4337 * @return bool True if matches, false otherwise
4339 public function checkTemporaryPassword( $plaintext ) {
4340 // Can't check the temporary password individually.
4341 return $this->checkPassword( $plaintext );
4345 * Initialize (if necessary) and return a session token value
4346 * which can be used in edit forms to show that the user's
4347 * login credentials aren't being hijacked with a foreign form
4351 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4352 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4353 * @return MediaWiki\Session\Token The new edit token
4355 public function getEditTokenObject( $salt = '', $request = null ) {
4356 if ( $this->isAnon() ) {
4357 return new LoggedOutEditToken();
4361 $request = $this->getRequest();
4363 return $request->getSession()->getToken( $salt );
4367 * Initialize (if necessary) and return a session token value
4368 * which can be used in edit forms to show that the user's
4369 * login credentials aren't being hijacked with a foreign form
4372 * The $salt for 'edit' and 'csrf' tokens is the default (empty string).
4375 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4376 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4377 * @return string The new edit token
4379 public function getEditToken( $salt = '', $request = null ) {
4380 return $this->getEditTokenObject( $salt, $request )->toString();
4384 * Get the embedded timestamp from a token.
4385 * @deprecated since 1.27, use \MediaWiki\Session\Token::getTimestamp instead.
4386 * @param string $val Input token
4389 public static function getEditTokenTimestamp( $val ) {
4390 wfDeprecated( __METHOD__
, '1.27' );
4391 return MediaWiki\Session\Token
::getTimestamp( $val );
4395 * Check given value against the token value stored in the session.
4396 * A match should confirm that the form was submitted from the
4397 * user's own login session, not a form submission from a third-party
4400 * @param string $val Input value to compare
4401 * @param string $salt Optional function-specific data for hashing
4402 * @param WebRequest|null $request Object to use or null to use $wgRequest
4403 * @param int $maxage Fail tokens older than this, in seconds
4404 * @return bool Whether the token matches
4406 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4407 return $this->getEditTokenObject( $salt, $request )->match( $val, $maxage );
4411 * Check given value against the token value stored in the session,
4412 * ignoring the suffix.
4414 * @param string $val Input value to compare
4415 * @param string $salt Optional function-specific data for hashing
4416 * @param WebRequest|null $request Object to use or null to use $wgRequest
4417 * @param int $maxage Fail tokens older than this, in seconds
4418 * @return bool Whether the token matches
4420 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4421 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . Token
::SUFFIX
;
4422 return $this->matchEditToken( $val, $salt, $request, $maxage );
4426 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4427 * mail to the user's given address.
4429 * @param string $type Message to send, either "created", "changed" or "set"
4432 public function sendConfirmationMail( $type = 'created' ) {
4434 $expiration = null; // gets passed-by-ref and defined in next line.
4435 $token = $this->confirmationToken( $expiration );
4436 $url = $this->confirmationTokenUrl( $token );
4437 $invalidateURL = $this->invalidationTokenUrl( $token );
4438 $this->saveSettings();
4440 if ( $type == 'created' ||
$type === false ) {
4441 $message = 'confirmemail_body';
4442 } elseif ( $type === true ) {
4443 $message = 'confirmemail_body_changed';
4445 // Messages: confirmemail_body_changed, confirmemail_body_set
4446 $message = 'confirmemail_body_' . $type;
4449 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4450 wfMessage( $message,
4451 $this->getRequest()->getIP(),
4454 $wgLang->userTimeAndDate( $expiration, $this ),
4456 $wgLang->userDate( $expiration, $this ),
4457 $wgLang->userTime( $expiration, $this ) )->text() );
4461 * Send an e-mail to this user's account. Does not check for
4462 * confirmed status or validity.
4464 * @param string $subject Message subject
4465 * @param string $body Message body
4466 * @param User|null $from Optional sending user; if unspecified, default
4467 * $wgPasswordSender will be used.
4468 * @param string $replyto Reply-To address
4471 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4472 global $wgPasswordSender;
4474 if ( $from instanceof User
) {
4475 $sender = MailAddress
::newFromUser( $from );
4477 $sender = new MailAddress( $wgPasswordSender,
4478 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4480 $to = MailAddress
::newFromUser( $this );
4482 return UserMailer
::send( $to, $sender, $subject, $body, [
4483 'replyTo' => $replyto,
4488 * Generate, store, and return a new e-mail confirmation code.
4489 * A hash (unsalted, since it's used as a key) is stored.
4491 * @note Call saveSettings() after calling this function to commit
4492 * this change to the database.
4494 * @param string &$expiration Accepts the expiration time
4495 * @return string New token
4497 protected function confirmationToken( &$expiration ) {
4498 global $wgUserEmailConfirmationTokenExpiry;
4500 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4501 $expiration = wfTimestamp( TS_MW
, $expires );
4503 $token = MWCryptRand
::generateHex( 32 );
4504 $hash = md5( $token );
4505 $this->mEmailToken
= $hash;
4506 $this->mEmailTokenExpires
= $expiration;
4511 * Return a URL the user can use to confirm their email address.
4512 * @param string $token Accepts the email confirmation token
4513 * @return string New token URL
4515 protected function confirmationTokenUrl( $token ) {
4516 return $this->getTokenUrl( 'ConfirmEmail', $token );
4520 * Return a URL the user can use to invalidate their email address.
4521 * @param string $token Accepts the email confirmation token
4522 * @return string New token URL
4524 protected function invalidationTokenUrl( $token ) {
4525 return $this->getTokenUrl( 'InvalidateEmail', $token );
4529 * Internal function to format the e-mail validation/invalidation URLs.
4530 * This uses a quickie hack to use the
4531 * hardcoded English names of the Special: pages, for ASCII safety.
4533 * @note Since these URLs get dropped directly into emails, using the
4534 * short English names avoids insanely long URL-encoded links, which
4535 * also sometimes can get corrupted in some browsers/mailers
4536 * (T8957 with Gmail and Internet Explorer).
4538 * @param string $page Special page
4539 * @param string $token Token
4540 * @return string Formatted URL
4542 protected function getTokenUrl( $page, $token ) {
4543 // Hack to bypass localization of 'Special:'
4544 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4545 return $title->getCanonicalURL();
4549 * Mark the e-mail address confirmed.
4551 * @note Call saveSettings() after calling this function to commit the change.
4555 public function confirmEmail() {
4556 // Check if it's already confirmed, so we don't touch the database
4557 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4558 if ( !$this->isEmailConfirmed() ) {
4559 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4560 Hooks
::run( 'ConfirmEmailComplete', [ $this ] );
4566 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4567 * address if it was already confirmed.
4569 * @note Call saveSettings() after calling this function to commit the change.
4570 * @return bool Returns true
4572 public function invalidateEmail() {
4574 $this->mEmailToken
= null;
4575 $this->mEmailTokenExpires
= null;
4576 $this->setEmailAuthenticationTimestamp( null );
4578 Hooks
::run( 'InvalidateEmailComplete', [ $this ] );
4583 * Set the e-mail authentication timestamp.
4584 * @param string $timestamp TS_MW timestamp
4586 public function setEmailAuthenticationTimestamp( $timestamp ) {
4588 $this->mEmailAuthenticated
= $timestamp;
4589 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
4593 * Is this user allowed to send e-mails within limits of current
4594 * site configuration?
4597 public function canSendEmail() {
4598 global $wgEnableEmail, $wgEnableUserEmail;
4599 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4602 $canSend = $this->isEmailConfirmed();
4603 // Avoid PHP 7.1 warning of passing $this by reference
4605 Hooks
::run( 'UserCanSendEmail', [ &$user, &$canSend ] );
4610 * Is this user allowed to receive e-mails within limits of current
4611 * site configuration?
4614 public function canReceiveEmail() {
4615 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4619 * Is this user's e-mail address valid-looking and confirmed within
4620 * limits of the current site configuration?
4622 * @note If $wgEmailAuthentication is on, this may require the user to have
4623 * confirmed their address by returning a code or using a password
4624 * sent to the address from the wiki.
4628 public function isEmailConfirmed() {
4629 global $wgEmailAuthentication;
4631 // Avoid PHP 7.1 warning of passing $this by reference
4634 if ( Hooks
::run( 'EmailConfirmed', [ &$user, &$confirmed ] ) ) {
4635 if ( $this->isAnon() ) {
4638 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4641 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4651 * Check whether there is an outstanding request for e-mail confirmation.
4654 public function isEmailConfirmationPending() {
4655 global $wgEmailAuthentication;
4656 return $wgEmailAuthentication &&
4657 !$this->isEmailConfirmed() &&
4658 $this->mEmailToken
&&
4659 $this->mEmailTokenExpires
> wfTimestamp();
4663 * Get the timestamp of account creation.
4665 * @return string|bool|null Timestamp of account creation, false for
4666 * non-existent/anonymous user accounts, or null if existing account
4667 * but information is not in database.
4669 public function getRegistration() {
4670 if ( $this->isAnon() ) {
4674 return $this->mRegistration
;
4678 * Get the timestamp of the first edit
4680 * @return string|bool Timestamp of first edit, or false for
4681 * non-existent/anonymous user accounts.
4683 public function getFirstEditTimestamp() {
4684 if ( $this->getId() == 0 ) {
4685 return false; // anons
4687 $dbr = wfGetDB( DB_REPLICA
);
4688 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4689 [ 'rev_user' => $this->getId() ],
4691 [ 'ORDER BY' => 'rev_timestamp ASC' ]
4694 return false; // no edits
4696 return wfTimestamp( TS_MW
, $time );
4700 * Get the permissions associated with a given list of groups
4702 * @param array $groups Array of Strings List of internal group names
4703 * @return array Array of Strings List of permission key names for given groups combined
4705 public static function getGroupPermissions( $groups ) {
4706 global $wgGroupPermissions, $wgRevokePermissions;
4708 // grant every granted permission first
4709 foreach ( $groups as $group ) {
4710 if ( isset( $wgGroupPermissions[$group] ) ) {
4711 $rights = array_merge( $rights,
4712 // array_filter removes empty items
4713 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4716 // now revoke the revoked permissions
4717 foreach ( $groups as $group ) {
4718 if ( isset( $wgRevokePermissions[$group] ) ) {
4719 $rights = array_diff( $rights,
4720 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4723 return array_unique( $rights );
4727 * Get all the groups who have a given permission
4729 * @param string $role Role to check
4730 * @return array Array of Strings List of internal group names with the given permission
4732 public static function getGroupsWithPermission( $role ) {
4733 global $wgGroupPermissions;
4734 $allowedGroups = [];
4735 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4736 if ( self
::groupHasPermission( $group, $role ) ) {
4737 $allowedGroups[] = $group;
4740 return $allowedGroups;
4744 * Check, if the given group has the given permission
4746 * If you're wanting to check whether all users have a permission, use
4747 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4751 * @param string $group Group to check
4752 * @param string $role Role to check
4755 public static function groupHasPermission( $group, $role ) {
4756 global $wgGroupPermissions, $wgRevokePermissions;
4757 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4758 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4762 * Check if all users may be assumed to have the given permission
4764 * We generally assume so if the right is granted to '*' and isn't revoked
4765 * on any group. It doesn't attempt to take grants or other extension
4766 * limitations on rights into account in the general case, though, as that
4767 * would require it to always return false and defeat the purpose.
4768 * Specifically, session-based rights restrictions (such as OAuth or bot
4769 * passwords) are applied based on the current session.
4772 * @param string $right Right to check
4775 public static function isEveryoneAllowed( $right ) {
4776 global $wgGroupPermissions, $wgRevokePermissions;
4779 // Use the cached results, except in unit tests which rely on
4780 // being able change the permission mid-request
4781 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4782 return $cache[$right];
4785 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4786 $cache[$right] = false;
4790 // If it's revoked anywhere, then everyone doesn't have it
4791 foreach ( $wgRevokePermissions as $rights ) {
4792 if ( isset( $rights[$right] ) && $rights[$right] ) {
4793 $cache[$right] = false;
4798 // Remove any rights that aren't allowed to the global-session user,
4799 // unless there are no sessions for this endpoint.
4800 if ( !defined( 'MW_NO_SESSION' ) ) {
4801 $allowedRights = SessionManager
::getGlobalSession()->getAllowedUserRights();
4802 if ( $allowedRights !== null && !in_array( $right, $allowedRights, true ) ) {
4803 $cache[$right] = false;
4808 // Allow extensions to say false
4809 if ( !Hooks
::run( 'UserIsEveryoneAllowed', [ $right ] ) ) {
4810 $cache[$right] = false;
4814 $cache[$right] = true;
4819 * Get the localized descriptive name for a group, if it exists
4820 * @deprecated since 1.29 Use UserGroupMembership::getGroupName instead
4822 * @param string $group Internal group name
4823 * @return string Localized descriptive group name
4825 public static function getGroupName( $group ) {
4826 wfDeprecated( __METHOD__
, '1.29' );
4827 return UserGroupMembership
::getGroupName( $group );
4831 * Get the localized descriptive name for a member of a group, if it exists
4832 * @deprecated since 1.29 Use UserGroupMembership::getGroupMemberName instead
4834 * @param string $group Internal group name
4835 * @param string $username Username for gender (since 1.19)
4836 * @return string Localized name for group member
4838 public static function getGroupMember( $group, $username = '#' ) {
4839 wfDeprecated( __METHOD__
, '1.29' );
4840 return UserGroupMembership
::getGroupMemberName( $group, $username );
4844 * Return the set of defined explicit groups.
4845 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4846 * are not included, as they are defined automatically, not in the database.
4847 * @return array Array of internal group names
4849 public static function getAllGroups() {
4850 global $wgGroupPermissions, $wgRevokePermissions;
4852 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4853 self
::getImplicitGroups()
4858 * Get a list of all available permissions.
4859 * @return string[] Array of permission names
4861 public static function getAllRights() {
4862 if ( self
::$mAllRights === false ) {
4863 global $wgAvailableRights;
4864 if ( count( $wgAvailableRights ) ) {
4865 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
4867 self
::$mAllRights = self
::$mCoreRights;
4869 Hooks
::run( 'UserGetAllRights', [ &self
::$mAllRights ] );
4871 return self
::$mAllRights;
4875 * Get a list of implicit groups
4876 * @return array Array of Strings Array of internal group names
4878 public static function getImplicitGroups() {
4879 global $wgImplicitGroups;
4881 $groups = $wgImplicitGroups;
4882 # Deprecated, use $wgImplicitGroups instead
4883 Hooks
::run( 'UserGetImplicitGroups', [ &$groups ], '1.25' );
4889 * Get the title of a page describing a particular group
4890 * @deprecated since 1.29 Use UserGroupMembership::getGroupPage instead
4892 * @param string $group Internal group name
4893 * @return Title|bool Title of the page if it exists, false otherwise
4895 public static function getGroupPage( $group ) {
4896 wfDeprecated( __METHOD__
, '1.29' );
4897 return UserGroupMembership
::getGroupPage( $group );
4901 * Create a link to the group in HTML, if available;
4902 * else return the group name.
4903 * @deprecated since 1.29 Use UserGroupMembership::getLink instead, or
4904 * make the link yourself if you need custom text
4906 * @param string $group Internal name of the group
4907 * @param string $text The text of the link
4908 * @return string HTML link to the group
4910 public static function makeGroupLinkHTML( $group, $text = '' ) {
4911 wfDeprecated( __METHOD__
, '1.29' );
4913 if ( $text == '' ) {
4914 $text = UserGroupMembership
::getGroupName( $group );
4916 $title = UserGroupMembership
::getGroupPage( $group );
4918 return Linker
::link( $title, htmlspecialchars( $text ) );
4920 return htmlspecialchars( $text );
4925 * Create a link to the group in Wikitext, if available;
4926 * else return the group name.
4927 * @deprecated since 1.29 Use UserGroupMembership::getLink instead, or
4928 * make the link yourself if you need custom text
4930 * @param string $group Internal name of the group
4931 * @param string $text The text of the link
4932 * @return string Wikilink to the group
4934 public static function makeGroupLinkWiki( $group, $text = '' ) {
4935 wfDeprecated( __METHOD__
, '1.29' );
4937 if ( $text == '' ) {
4938 $text = UserGroupMembership
::getGroupName( $group );
4940 $title = UserGroupMembership
::getGroupPage( $group );
4942 $page = $title->getFullText();
4943 return "[[$page|$text]]";
4950 * Returns an array of the groups that a particular group can add/remove.
4952 * @param string $group The group to check for whether it can add/remove
4953 * @return array Array( 'add' => array( addablegroups ),
4954 * 'remove' => array( removablegroups ),
4955 * 'add-self' => array( addablegroups to self),
4956 * 'remove-self' => array( removable groups from self) )
4958 public static function changeableByGroup( $group ) {
4959 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4968 if ( empty( $wgAddGroups[$group] ) ) {
4969 // Don't add anything to $groups
4970 } elseif ( $wgAddGroups[$group] === true ) {
4971 // You get everything
4972 $groups['add'] = self
::getAllGroups();
4973 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4974 $groups['add'] = $wgAddGroups[$group];
4977 // Same thing for remove
4978 if ( empty( $wgRemoveGroups[$group] ) ) {
4980 } elseif ( $wgRemoveGroups[$group] === true ) {
4981 $groups['remove'] = self
::getAllGroups();
4982 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4983 $groups['remove'] = $wgRemoveGroups[$group];
4986 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4987 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4988 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4989 if ( is_int( $key ) ) {
4990 $wgGroupsAddToSelf['user'][] = $value;
4995 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
4996 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4997 if ( is_int( $key ) ) {
4998 $wgGroupsRemoveFromSelf['user'][] = $value;
5003 // Now figure out what groups the user can add to him/herself
5004 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
5006 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
5007 // No idea WHY this would be used, but it's there
5008 $groups['add-self'] = User
::getAllGroups();
5009 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
5010 $groups['add-self'] = $wgGroupsAddToSelf[$group];
5013 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
5015 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
5016 $groups['remove-self'] = User
::getAllGroups();
5017 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
5018 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
5025 * Returns an array of groups that this user can add and remove
5026 * @return array Array( 'add' => array( addablegroups ),
5027 * 'remove' => array( removablegroups ),
5028 * 'add-self' => array( addablegroups to self),
5029 * 'remove-self' => array( removable groups from self) )
5031 public function changeableGroups() {
5032 if ( $this->isAllowed( 'userrights' ) ) {
5033 // This group gives the right to modify everything (reverse-
5034 // compatibility with old "userrights lets you change
5036 // Using array_merge to make the groups reindexed
5037 $all = array_merge( User
::getAllGroups() );
5046 // Okay, it's not so simple, we will have to go through the arrays
5053 $addergroups = $this->getEffectiveGroups();
5055 foreach ( $addergroups as $addergroup ) {
5056 $groups = array_merge_recursive(
5057 $groups, $this->changeableByGroup( $addergroup )
5059 $groups['add'] = array_unique( $groups['add'] );
5060 $groups['remove'] = array_unique( $groups['remove'] );
5061 $groups['add-self'] = array_unique( $groups['add-self'] );
5062 $groups['remove-self'] = array_unique( $groups['remove-self'] );
5068 * Deferred version of incEditCountImmediate()
5070 public function incEditCount() {
5071 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle(
5073 $this->incEditCountImmediate();
5080 * Increment the user's edit-count field.
5081 * Will have no effect for anonymous users.
5084 public function incEditCountImmediate() {
5085 if ( $this->isAnon() ) {
5089 $dbw = wfGetDB( DB_MASTER
);
5090 // No rows will be "affected" if user_editcount is NULL
5093 [ 'user_editcount=user_editcount+1' ],
5094 [ 'user_id' => $this->getId(), 'user_editcount IS NOT NULL' ],
5097 // Lazy initialization check...
5098 if ( $dbw->affectedRows() == 0 ) {
5099 // Now here's a goddamn hack...
5100 $dbr = wfGetDB( DB_REPLICA
);
5101 if ( $dbr !== $dbw ) {
5102 // If we actually have a replica DB server, the count is
5103 // at least one behind because the current transaction
5104 // has not been committed and replicated.
5105 $this->mEditCount
= $this->initEditCount( 1 );
5107 // But if DB_REPLICA is selecting the master, then the
5108 // count we just read includes the revision that was
5109 // just added in the working transaction.
5110 $this->mEditCount
= $this->initEditCount();
5113 if ( $this->mEditCount
=== null ) {
5114 $this->getEditCount();
5115 $dbr = wfGetDB( DB_REPLICA
);
5116 $this->mEditCount +
= ( $dbr !== $dbw ) ?
1 : 0;
5118 $this->mEditCount++
;
5121 // Edit count in user cache too
5122 $this->invalidateCache();
5126 * Initialize user_editcount from data out of the revision table
5128 * @param int $add Edits to add to the count from the revision table
5129 * @return int Number of edits
5131 protected function initEditCount( $add = 0 ) {
5132 // Pull from a replica DB to be less cruel to servers
5133 // Accuracy isn't the point anyway here
5134 $dbr = wfGetDB( DB_REPLICA
);
5135 $count = (int)$dbr->selectField(
5138 [ 'rev_user' => $this->getId() ],
5141 $count = $count +
$add;
5143 $dbw = wfGetDB( DB_MASTER
);
5146 [ 'user_editcount' => $count ],
5147 [ 'user_id' => $this->getId() ],
5155 * Get the description of a given right
5158 * @param string $right Right to query
5159 * @return string Localized description of the right
5161 public static function getRightDescription( $right ) {
5162 $key = "right-$right";
5163 $msg = wfMessage( $key );
5164 return $msg->isDisabled() ?
$right : $msg->text();
5168 * Get the name of a given grant
5171 * @param string $grant Grant to query
5172 * @return string Localized name of the grant
5174 public static function getGrantName( $grant ) {
5175 $key = "grant-$grant";
5176 $msg = wfMessage( $key );
5177 return $msg->isDisabled() ?
$grant : $msg->text();
5181 * Add a newuser log entry for this user.
5182 * Before 1.19 the return value was always true.
5184 * @deprecated since 1.27, AuthManager handles logging
5185 * @param string|bool $action Account creation type.
5186 * - String, one of the following values:
5187 * - 'create' for an anonymous user creating an account for himself.
5188 * This will force the action's performer to be the created user itself,
5189 * no matter the value of $wgUser
5190 * - 'create2' for a logged in user creating an account for someone else
5191 * - 'byemail' when the created user will receive its password by e-mail
5192 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
5193 * - Boolean means whether the account was created by e-mail (deprecated):
5194 * - true will be converted to 'byemail'
5195 * - false will be converted to 'create' if this object is the same as
5196 * $wgUser and to 'create2' otherwise
5197 * @param string $reason User supplied reason
5200 public function addNewUserLogEntry( $action = false, $reason = '' ) {
5201 return true; // disabled
5205 * Add an autocreate newuser log entry for this user
5206 * Used by things like CentralAuth and perhaps other authplugins.
5207 * Consider calling addNewUserLogEntry() directly instead.
5209 * @deprecated since 1.27, AuthManager handles logging
5212 public function addNewUserLogEntryAutoCreate() {
5213 $this->addNewUserLogEntry( 'autocreate' );
5219 * Load the user options either from cache, the database or an array
5221 * @param array $data Rows for the current user out of the user_properties table
5223 protected function loadOptions( $data = null ) {
5228 if ( $this->mOptionsLoaded
) {
5232 $this->mOptions
= self
::getDefaultOptions();
5234 if ( !$this->getId() ) {
5235 // For unlogged-in users, load language/variant options from request.
5236 // There's no need to do it for logged-in users: they can set preferences,
5237 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5238 // so don't override user's choice (especially when the user chooses site default).
5239 $variant = $wgContLang->getDefaultVariant();
5240 $this->mOptions
['variant'] = $variant;
5241 $this->mOptions
['language'] = $variant;
5242 $this->mOptionsLoaded
= true;
5246 // Maybe load from the object
5247 if ( !is_null( $this->mOptionOverrides
) ) {
5248 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5249 foreach ( $this->mOptionOverrides
as $key => $value ) {
5250 $this->mOptions
[$key] = $value;
5253 if ( !is_array( $data ) ) {
5254 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5255 // Load from database
5256 $dbr = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
5257 ?
wfGetDB( DB_MASTER
)
5258 : wfGetDB( DB_REPLICA
);
5260 $res = $dbr->select(
5262 [ 'up_property', 'up_value' ],
5263 [ 'up_user' => $this->getId() ],
5267 $this->mOptionOverrides
= [];
5269 foreach ( $res as $row ) {
5270 // Convert '0' to 0. PHP's boolean conversion considers them both
5271 // false, but e.g. JavaScript considers the former as true.
5272 // @todo: T54542 Somehow determine the desired type (string/int/bool)
5273 // and convert all values here.
5274 if ( $row->up_value
=== '0' ) {
5277 $data[$row->up_property
] = $row->up_value
;
5280 foreach ( $data as $property => $value ) {
5281 $this->mOptionOverrides
[$property] = $value;
5282 $this->mOptions
[$property] = $value;
5286 $this->mOptionsLoaded
= true;
5288 Hooks
::run( 'UserLoadOptions', [ $this, &$this->mOptions
] );
5292 * Saves the non-default options for this user, as previously set e.g. via
5293 * setOption(), in the database's "user_properties" (preferences) table.
5294 * Usually used via saveSettings().
5296 protected function saveOptions() {
5297 $this->loadOptions();
5299 // Not using getOptions(), to keep hidden preferences in database
5300 $saveOptions = $this->mOptions
;
5302 // Allow hooks to abort, for instance to save to a global profile.
5303 // Reset options to default state before saving.
5304 if ( !Hooks
::run( 'UserSaveOptions', [ $this, &$saveOptions ] ) ) {
5308 $userId = $this->getId();
5310 $insert_rows = []; // all the new preference rows
5311 foreach ( $saveOptions as $key => $value ) {
5312 // Don't bother storing default values
5313 $defaultOption = self
::getDefaultOption( $key );
5314 if ( ( $defaultOption === null && $value !== false && $value !== null )
5315 ||
$value != $defaultOption
5318 'up_user' => $userId,
5319 'up_property' => $key,
5320 'up_value' => $value,
5325 $dbw = wfGetDB( DB_MASTER
);
5327 $res = $dbw->select( 'user_properties',
5328 [ 'up_property', 'up_value' ], [ 'up_user' => $userId ], __METHOD__
);
5330 // Find prior rows that need to be removed or updated. These rows will
5331 // all be deleted (the latter so that INSERT IGNORE applies the new values).
5333 foreach ( $res as $row ) {
5334 if ( !isset( $saveOptions[$row->up_property
] )
5335 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
5337 $keysDelete[] = $row->up_property
;
5341 if ( count( $keysDelete ) ) {
5342 // Do the DELETE by PRIMARY KEY for prior rows.
5343 // In the past a very large portion of calls to this function are for setting
5344 // 'rememberpassword' for new accounts (a preference that has since been removed).
5345 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5346 // caused gap locks on [max user ID,+infinity) which caused high contention since
5347 // updates would pile up on each other as they are for higher (newer) user IDs.
5348 // It might not be necessary these days, but it shouldn't hurt either.
5349 $dbw->delete( 'user_properties',
5350 [ 'up_user' => $userId, 'up_property' => $keysDelete ], __METHOD__
);
5352 // Insert the new preference rows
5353 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, [ 'IGNORE' ] );
5357 * Lazily instantiate and return a factory object for making passwords
5359 * @deprecated since 1.27, create a PasswordFactory directly instead
5360 * @return PasswordFactory
5362 public static function getPasswordFactory() {
5363 wfDeprecated( __METHOD__
, '1.27' );
5364 $ret = new PasswordFactory();
5365 $ret->init( RequestContext
::getMain()->getConfig() );
5370 * Provide an array of HTML5 attributes to put on an input element
5371 * intended for the user to enter a new password. This may include
5372 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
5374 * Do *not* use this when asking the user to enter his current password!
5375 * Regardless of configuration, users may have invalid passwords for whatever
5376 * reason (e.g., they were set before requirements were tightened up).
5377 * Only use it when asking for a new password, like on account creation or
5380 * Obviously, you still need to do server-side checking.
5382 * NOTE: A combination of bugs in various browsers means that this function
5383 * actually just returns array() unconditionally at the moment. May as
5384 * well keep it around for when the browser bugs get fixed, though.
5386 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
5388 * @deprecated since 1.27
5389 * @return array Array of HTML attributes suitable for feeding to
5390 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
5391 * That will get confused by the boolean attribute syntax used.)
5393 public static function passwordChangeInputAttribs() {
5394 global $wgMinimalPasswordLength;
5396 if ( $wgMinimalPasswordLength == 0 ) {
5400 # Note that the pattern requirement will always be satisfied if the
5401 # input is empty, so we need required in all cases.
5403 # @todo FIXME: T25769: This needs to not claim the password is required
5404 # if e-mail confirmation is being used. Since HTML5 input validation
5405 # is b0rked anyway in some browsers, just return nothing. When it's
5406 # re-enabled, fix this code to not output required for e-mail
5408 # $ret = array( 'required' );
5411 # We can't actually do this right now, because Opera 9.6 will print out
5412 # the entered password visibly in its error message! When other
5413 # browsers add support for this attribute, or Opera fixes its support,
5414 # we can add support with a version check to avoid doing this on Opera
5415 # versions where it will be a problem. Reported to Opera as
5416 # DSK-262266, but they don't have a public bug tracker for us to follow.
5418 if ( $wgMinimalPasswordLength > 1 ) {
5419 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
5420 $ret['title'] = wfMessage( 'passwordtooshort' )
5421 ->numParams( $wgMinimalPasswordLength )->text();
5429 * Return the list of user fields that should be selected to create
5430 * a new user object.
5433 public static function selectFields() {
5441 'user_email_authenticated',
5443 'user_email_token_expires',
5444 'user_registration',
5450 * Factory function for fatal permission-denied errors
5453 * @param string $permission User right required
5456 static function newFatalPermissionDeniedStatus( $permission ) {
5460 foreach ( User
::getGroupsWithPermission( $permission ) as $group ) {
5461 $groups[] = UserGroupMembership
::getLink( $group, RequestContext
::getMain(), 'wiki' );
5465 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5467 return Status
::newFatal( 'badaccess-group0' );
5472 * Get a new instance of this user that was loaded from the master via a locking read
5474 * Use this instead of the main context User when updating that user. This avoids races
5475 * where that user was loaded from a replica DB or even the master but without proper locks.
5477 * @return User|null Returns null if the user was not found in the DB
5480 public function getInstanceForUpdate() {
5481 if ( !$this->getId() ) {
5482 return null; // anon
5485 $user = self
::newFromId( $this->getId() );
5486 if ( !$user->loadFromId( self
::READ_EXCLUSIVE
) ) {
5494 * Checks if two user objects point to the same user.
5500 public function equals( User
$user ) {
5501 return $this->getName() === $user->getName();