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 );
512 // if a user group membership is about to expire, the cache needs to
513 // expire at that time (T163691)
514 foreach ( $this->mGroupMemberships
as $ugm ) {
515 if ( $ugm->getExpiry() ) {
516 $secondsUntilExpiry = wfTimestamp( TS_UNIX
, $ugm->getExpiry() ) - time();
517 if ( $secondsUntilExpiry > 0 && $secondsUntilExpiry < $ttl ) {
518 $ttl = $secondsUntilExpiry;
526 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'version' => self
::VERSION
]
529 // Restore from cache
530 foreach ( self
::$mCacheVars as $name ) {
531 $this->$name = $data[$name];
537 /** @name newFrom*() static factory methods */
541 * Static factory method for creation from username.
543 * This is slightly less efficient than newFromId(), so use newFromId() if
544 * you have both an ID and a name handy.
546 * @param string $name Username, validated by Title::newFromText()
547 * @param string|bool $validate Validate username. Takes the same parameters as
548 * User::getCanonicalName(), except that true is accepted as an alias
549 * for 'valid', for BC.
551 * @return User|bool User object, or false if the username is invalid
552 * (e.g. if it contains illegal characters or is an IP address). If the
553 * username is not present in the database, the result will be a user object
554 * with a name, zero user ID and default settings.
556 public static function newFromName( $name, $validate = 'valid' ) {
557 if ( $validate === true ) {
560 $name = self
::getCanonicalName( $name, $validate );
561 if ( $name === false ) {
564 // Create unloaded user object
568 $u->setItemLoaded( 'name' );
574 * Static factory method for creation from a given user ID.
576 * @param int $id Valid user ID
577 * @return User The corresponding User object
579 public static function newFromId( $id ) {
583 $u->setItemLoaded( 'id' );
588 * Factory method to fetch whichever user has a given email confirmation code.
589 * This code is generated when an account is created or its e-mail address
592 * If the code is invalid or has expired, returns NULL.
594 * @param string $code Confirmation code
595 * @param int $flags User::READ_* bitfield
598 public static function newFromConfirmationCode( $code, $flags = 0 ) {
599 $db = ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
600 ?
wfGetDB( DB_MASTER
)
601 : wfGetDB( DB_REPLICA
);
603 $id = $db->selectField(
607 'user_email_token' => md5( $code ),
608 'user_email_token_expires > ' . $db->addQuotes( $db->timestamp() ),
612 return $id ? User
::newFromId( $id ) : null;
616 * Create a new user object using data from session. If the login
617 * credentials are invalid, the result is an anonymous user.
619 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
622 public static function newFromSession( WebRequest
$request = null ) {
624 $user->mFrom
= 'session';
625 $user->mRequest
= $request;
630 * Create a new user object from a user row.
631 * The row should have the following fields from the user table in it:
632 * - either user_name or user_id to load further data if needed (or both)
634 * - all other fields (email, etc.)
635 * It is useless to provide the remaining fields if either user_id,
636 * user_name and user_real_name are not provided because the whole row
637 * will be loaded once more from the database when accessing them.
639 * @param stdClass $row A row from the user table
640 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
643 public static function newFromRow( $row, $data = null ) {
645 $user->loadFromRow( $row, $data );
650 * Static factory method for creation of a "system" user from username.
652 * A "system" user is an account that's used to attribute logged actions
653 * taken by MediaWiki itself, as opposed to a bot or human user. Examples
654 * might include the 'Maintenance script' or 'Conversion script' accounts
655 * used by various scripts in the maintenance/ directory or accounts such
656 * as 'MediaWiki message delivery' used by the MassMessage extension.
658 * This can optionally create the user if it doesn't exist, and "steal" the
659 * account if it does exist.
661 * "Stealing" an existing user is intended to make it impossible for normal
662 * authentication processes to use the account, effectively disabling the
663 * account for normal use:
664 * - Email is invalidated, to prevent account recovery by emailing a
665 * temporary password and to disassociate the account from the existing
667 * - The token is set to a magic invalid value, to kill existing sessions
668 * and to prevent $this->setToken() calls from resetting the token to a
670 * - SessionManager is instructed to prevent new sessions for the user, to
671 * do things like deauthorizing OAuth consumers.
672 * - AuthManager is instructed to revoke access, to invalidate or remove
673 * passwords and other credentials.
675 * @param string $name Username
676 * @param array $options Options are:
677 * - validate: As for User::getCanonicalName(), default 'valid'
678 * - create: Whether to create the user if it doesn't already exist, default true
679 * - steal: Whether to "disable" the account for normal use if it already
680 * exists, default false
684 public static function newSystemUser( $name, $options = [] ) {
686 'validate' => 'valid',
691 $name = self
::getCanonicalName( $name, $options['validate'] );
692 if ( $name === false ) {
696 $fields = self
::selectFields();
698 $dbw = wfGetDB( DB_MASTER
);
699 $row = $dbw->selectRow(
702 [ 'user_name' => $name ],
706 // No user. Create it?
707 return $options['create'] ? self
::createNew( $name, [ 'token' => self
::INVALID_TOKEN
] ) : null;
709 $user = self
::newFromRow( $row );
711 // A user is considered to exist as a non-system user if it can
712 // authenticate, or has an email set, or has a non-invalid token.
713 if ( $user->mEmail ||
$user->mToken
!== self
::INVALID_TOKEN ||
714 AuthManager
::singleton()->userCanAuthenticate( $name )
716 // User exists. Steal it?
717 if ( !$options['steal'] ) {
721 AuthManager
::singleton()->revokeAccessForUser( $name );
723 $user->invalidateEmail();
724 $user->mToken
= self
::INVALID_TOKEN
;
725 $user->saveSettings();
726 SessionManager
::singleton()->preventSessionsForUser( $user->getName() );
735 * Get the username corresponding to a given user ID
736 * @param int $id User ID
737 * @return string|bool The corresponding username
739 public static function whoIs( $id ) {
740 return UserCache
::singleton()->getProp( $id, 'name' );
744 * Get the real name of a user given their user ID
746 * @param int $id User ID
747 * @return string|bool The corresponding user's real name
749 public static function whoIsReal( $id ) {
750 return UserCache
::singleton()->getProp( $id, 'real_name' );
754 * Get database id given a user name
755 * @param string $name Username
756 * @param integer $flags User::READ_* constant bitfield
757 * @return int|null The corresponding user's ID, or null if user is nonexistent
759 public static function idFromName( $name, $flags = self
::READ_NORMAL
) {
760 $nt = Title
::makeTitleSafe( NS_USER
, $name );
761 if ( is_null( $nt ) ) {
766 if ( !( $flags & self
::READ_LATEST
) && isset( self
::$idCacheByName[$name] ) ) {
767 return self
::$idCacheByName[$name];
770 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
771 $db = wfGetDB( $index );
776 [ 'user_name' => $nt->getText() ],
781 if ( $s === false ) {
784 $result = $s->user_id
;
787 self
::$idCacheByName[$name] = $result;
789 if ( count( self
::$idCacheByName ) > 1000 ) {
790 self
::$idCacheByName = [];
797 * Reset the cache used in idFromName(). For use in tests.
799 public static function resetIdByNameCache() {
800 self
::$idCacheByName = [];
804 * Does the string match an anonymous IP address?
806 * This function exists for username validation, in order to reject
807 * usernames which are similar in form to IP addresses. Strings such
808 * as 300.300.300.300 will return true because it looks like an IP
809 * address, despite not being strictly valid.
811 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
812 * address because the usemod software would "cloak" anonymous IP
813 * addresses like this, if we allowed accounts like this to be created
814 * new users could get the old edits of these anonymous users.
816 * @param string $name Name to match
819 public static function isIP( $name ) {
820 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
821 || IP
::isIPv6( $name );
825 * Is the input a valid username?
827 * Checks if the input is a valid username, we don't want an empty string,
828 * an IP address, anything that contains slashes (would mess up subpages),
829 * is longer than the maximum allowed username size or doesn't begin with
832 * @param string $name Name to match
835 public static function isValidUserName( $name ) {
836 global $wgContLang, $wgMaxNameChars;
839 || User
::isIP( $name )
840 ||
strpos( $name, '/' ) !== false
841 ||
strlen( $name ) > $wgMaxNameChars
842 ||
$name != $wgContLang->ucfirst( $name )
847 // Ensure that the name can't be misresolved as a different title,
848 // such as with extra namespace keys at the start.
849 $parsed = Title
::newFromText( $name );
850 if ( is_null( $parsed )
851 ||
$parsed->getNamespace()
852 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
856 // Check an additional blacklist of troublemaker characters.
857 // Should these be merged into the title char list?
858 $unicodeBlacklist = '/[' .
859 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
860 '\x{00a0}' . # non-breaking space
861 '\x{2000}-\x{200f}' . # various whitespace
862 '\x{2028}-\x{202f}' . # breaks and control chars
863 '\x{3000}' . # ideographic space
864 '\x{e000}-\x{f8ff}' . # private use
866 if ( preg_match( $unicodeBlacklist, $name ) ) {
874 * Usernames which fail to pass this function will be blocked
875 * from user login and new account registrations, but may be used
876 * internally by batch processes.
878 * If an account already exists in this form, login will be blocked
879 * by a failure to pass this function.
881 * @param string $name Name to match
884 public static function isUsableName( $name ) {
885 global $wgReservedUsernames;
886 // Must be a valid username, obviously ;)
887 if ( !self
::isValidUserName( $name ) ) {
891 static $reservedUsernames = false;
892 if ( !$reservedUsernames ) {
893 $reservedUsernames = $wgReservedUsernames;
894 Hooks
::run( 'UserGetReservedNames', [ &$reservedUsernames ] );
897 // Certain names may be reserved for batch processes.
898 foreach ( $reservedUsernames as $reserved ) {
899 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
900 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
902 if ( $reserved == $name ) {
910 * Return the users who are members of the given group(s). In case of multiple groups,
911 * users who are members of at least one of them are returned.
913 * @param string|array $groups A single group name or an array of group names
914 * @param int $limit Max number of users to return. The actual limit will never exceed 5000
915 * records; larger values are ignored.
916 * @param int $after ID the user to start after
917 * @return UserArrayFromResult
919 public static function findUsersByGroup( $groups, $limit = 5000, $after = null ) {
920 if ( $groups === [] ) {
921 return UserArrayFromResult
::newFromIDs( [] );
924 $groups = array_unique( (array)$groups );
925 $limit = min( 5000, $limit );
927 $conds = [ 'ug_group' => $groups ];
928 if ( $after !== null ) {
929 $conds[] = 'ug_user > ' . (int)$after;
932 $dbr = wfGetDB( DB_REPLICA
);
933 $ids = $dbr->selectFieldValues(
940 'ORDER BY' => 'ug_user',
944 return UserArray
::newFromIDs( $ids );
948 * Usernames which fail to pass this function will be blocked
949 * from new account registrations, but may be used internally
950 * either by batch processes or by user accounts which have
951 * already been created.
953 * Additional blacklisting may be added here rather than in
954 * isValidUserName() to avoid disrupting existing accounts.
956 * @param string $name String to match
959 public static function isCreatableName( $name ) {
960 global $wgInvalidUsernameCharacters;
962 // Ensure that the username isn't longer than 235 bytes, so that
963 // (at least for the builtin skins) user javascript and css files
964 // will work. (T25080)
965 if ( strlen( $name ) > 235 ) {
966 wfDebugLog( 'username', __METHOD__
.
967 ": '$name' invalid due to length" );
971 // Preg yells if you try to give it an empty string
972 if ( $wgInvalidUsernameCharacters !== '' ) {
973 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
974 wfDebugLog( 'username', __METHOD__
.
975 ": '$name' invalid due to wgInvalidUsernameCharacters" );
980 return self
::isUsableName( $name );
984 * Is the input a valid password for this user?
986 * @param string $password Desired password
989 public function isValidPassword( $password ) {
990 // simple boolean wrapper for getPasswordValidity
991 return $this->getPasswordValidity( $password ) === true;
995 * Given unvalidated password input, return error message on failure.
997 * @param string $password Desired password
998 * @return bool|string|array True on success, string or array of error message on failure
1000 public function getPasswordValidity( $password ) {
1001 $result = $this->checkPasswordValidity( $password );
1002 if ( $result->isGood() ) {
1006 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
1007 $messages[] = $error['message'];
1009 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
1010 $messages[] = $warning['message'];
1012 if ( count( $messages ) === 1 ) {
1013 return $messages[0];
1020 * Check if this is a valid password for this user
1022 * Create a Status object based on the password's validity.
1023 * The Status should be set to fatal if the user should not
1024 * be allowed to log in, and should have any errors that
1025 * would block changing the password.
1027 * If the return value of this is not OK, the password
1028 * should not be checked. If the return value is not Good,
1029 * the password can be checked, but the user should not be
1030 * able to set their password to this.
1032 * @param string $password Desired password
1036 public function checkPasswordValidity( $password ) {
1037 global $wgPasswordPolicy;
1039 $upp = new UserPasswordPolicy(
1040 $wgPasswordPolicy['policies'],
1041 $wgPasswordPolicy['checks']
1044 $status = Status
::newGood();
1045 $result = false; // init $result to false for the internal checks
1047 if ( !Hooks
::run( 'isValidPassword', [ $password, &$result, $this ] ) ) {
1048 $status->error( $result );
1052 if ( $result === false ) {
1053 $status->merge( $upp->checkUserPassword( $this, $password ) );
1055 } elseif ( $result === true ) {
1058 $status->error( $result );
1059 return $status; // the isValidPassword hook set a string $result and returned true
1064 * Given unvalidated user input, return a canonical username, or false if
1065 * the username is invalid.
1066 * @param string $name User input
1067 * @param string|bool $validate Type of validation to use:
1068 * - false No validation
1069 * - 'valid' Valid for batch processes
1070 * - 'usable' Valid for batch processes and login
1071 * - 'creatable' Valid for batch processes, login and account creation
1073 * @throws InvalidArgumentException
1074 * @return bool|string
1076 public static function getCanonicalName( $name, $validate = 'valid' ) {
1077 // Force usernames to capital
1079 $name = $wgContLang->ucfirst( $name );
1081 # Reject names containing '#'; these will be cleaned up
1082 # with title normalisation, but then it's too late to
1084 if ( strpos( $name, '#' ) !== false ) {
1088 // Clean up name according to title rules,
1089 // but only when validation is requested (T14654)
1090 $t = ( $validate !== false ) ?
1091 Title
::newFromText( $name, NS_USER
) : Title
::makeTitle( NS_USER
, $name );
1092 // Check for invalid titles
1093 if ( is_null( $t ) ||
$t->getNamespace() !== NS_USER ||
$t->isExternal() ) {
1097 // Reject various classes of invalid names
1098 $name = AuthManager
::callLegacyAuthPlugin(
1099 'getCanonicalName', [ $t->getText() ], $t->getText()
1102 switch ( $validate ) {
1106 if ( !User
::isValidUserName( $name ) ) {
1111 if ( !User
::isUsableName( $name ) ) {
1116 if ( !User
::isCreatableName( $name ) ) {
1121 throw new InvalidArgumentException(
1122 'Invalid parameter value for $validate in ' . __METHOD__
);
1128 * Return a random password.
1130 * @deprecated since 1.27, use PasswordFactory::generateRandomPasswordString()
1131 * @return string New random password
1133 public static function randomPassword() {
1134 global $wgMinimalPasswordLength;
1135 return PasswordFactory
::generateRandomPasswordString( $wgMinimalPasswordLength );
1139 * Set cached properties to default.
1141 * @note This no longer clears uncached lazy-initialised properties;
1142 * the constructor does that instead.
1144 * @param string|bool $name
1146 public function loadDefaults( $name = false ) {
1148 $this->mName
= $name;
1149 $this->mRealName
= '';
1151 $this->mOptionOverrides
= null;
1152 $this->mOptionsLoaded
= false;
1154 $loggedOut = $this->mRequest
&& !defined( 'MW_NO_SESSION' )
1155 ?
$this->mRequest
->getSession()->getLoggedOutTimestamp() : 0;
1156 if ( $loggedOut !== 0 ) {
1157 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1159 $this->mTouched
= '1'; # Allow any pages to be cached
1162 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1163 $this->mEmailAuthenticated
= null;
1164 $this->mEmailToken
= '';
1165 $this->mEmailTokenExpires
= null;
1166 $this->mRegistration
= wfTimestamp( TS_MW
);
1167 $this->mGroupMemberships
= [];
1169 Hooks
::run( 'UserLoadDefaults', [ $this, $name ] );
1173 * Return whether an item has been loaded.
1175 * @param string $item Item to check. Current possibilities:
1179 * @param string $all 'all' to check if the whole object has been loaded
1180 * or any other string to check if only the item is available (e.g.
1184 public function isItemLoaded( $item, $all = 'all' ) {
1185 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1186 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1190 * Set that an item has been loaded
1192 * @param string $item
1194 protected function setItemLoaded( $item ) {
1195 if ( is_array( $this->mLoadedItems
) ) {
1196 $this->mLoadedItems
[$item] = true;
1201 * Load user data from the session.
1203 * @return bool True if the user is logged in, false otherwise.
1205 private function loadFromSession() {
1208 Hooks
::run( 'UserLoadFromSession', [ $this, &$result ], '1.27' );
1209 if ( $result !== null ) {
1213 // MediaWiki\Session\Session already did the necessary authentication of the user
1214 // returned here, so just use it if applicable.
1215 $session = $this->getRequest()->getSession();
1216 $user = $session->getUser();
1217 if ( $user->isLoggedIn() ) {
1218 $this->loadFromUserObject( $user );
1220 // If this user is autoblocked, set a cookie to track the Block. This has to be done on
1221 // every session load, because an autoblocked editor might not edit again from the same
1222 // IP address after being blocked.
1223 $config = RequestContext
::getMain()->getConfig();
1224 if ( $config->get( 'CookieSetOnAutoblock' ) === true ) {
1225 $block = $this->getBlock();
1226 $shouldSetCookie = $this->getRequest()->getCookie( 'BlockID' ) === null
1228 && $block->getType() === Block
::TYPE_USER
1229 && $block->isAutoblocking();
1230 if ( $shouldSetCookie ) {
1231 wfDebug( __METHOD__
. ': User is autoblocked, setting cookie to track' );
1232 $block->setCookie( $this->getRequest()->response() );
1236 // Other code expects these to be set in the session, so set them.
1237 $session->set( 'wsUserID', $this->getId() );
1238 $session->set( 'wsUserName', $this->getName() );
1239 $session->set( 'wsToken', $this->getToken() );
1246 * Load user and user_group data from the database.
1247 * $this->mId must be set, this is how the user is identified.
1249 * @param integer $flags User::READ_* constant bitfield
1250 * @return bool True if the user exists, false if the user is anonymous
1252 public function loadFromDatabase( $flags = self
::READ_LATEST
) {
1254 $this->mId
= intval( $this->mId
);
1256 if ( !$this->mId
) {
1257 // Anonymous users are not in the database
1258 $this->loadDefaults();
1262 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
1263 $db = wfGetDB( $index );
1265 $s = $db->selectRow(
1267 self
::selectFields(),
1268 [ 'user_id' => $this->mId
],
1273 $this->queryFlagsUsed
= $flags;
1274 Hooks
::run( 'UserLoadFromDatabase', [ $this, &$s ] );
1276 if ( $s !== false ) {
1277 // Initialise user table data
1278 $this->loadFromRow( $s );
1279 $this->mGroupMemberships
= null; // deferred
1280 $this->getEditCount(); // revalidation for nulls
1285 $this->loadDefaults();
1291 * Initialize this object from a row from the user table.
1293 * @param stdClass $row Row from the user table to load.
1294 * @param array $data Further user data to load into the object
1296 * user_groups Array of arrays or stdClass result rows out of the user_groups
1297 * table. Previously you were supposed to pass an array of strings
1298 * here, but we also need expiry info nowadays, so an array of
1299 * strings is ignored.
1300 * user_properties Array with properties out of the user_properties table
1302 protected function loadFromRow( $row, $data = null ) {
1305 $this->mGroupMemberships
= null; // deferred
1307 if ( isset( $row->user_name
) ) {
1308 $this->mName
= $row->user_name
;
1309 $this->mFrom
= 'name';
1310 $this->setItemLoaded( 'name' );
1315 if ( isset( $row->user_real_name
) ) {
1316 $this->mRealName
= $row->user_real_name
;
1317 $this->setItemLoaded( 'realname' );
1322 if ( isset( $row->user_id
) ) {
1323 $this->mId
= intval( $row->user_id
);
1324 $this->mFrom
= 'id';
1325 $this->setItemLoaded( 'id' );
1330 if ( isset( $row->user_id
) && isset( $row->user_name
) ) {
1331 self
::$idCacheByName[$row->user_name
] = $row->user_id
;
1334 if ( isset( $row->user_editcount
) ) {
1335 $this->mEditCount
= $row->user_editcount
;
1340 if ( isset( $row->user_touched
) ) {
1341 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1346 if ( isset( $row->user_token
) ) {
1347 // The definition for the column is binary(32), so trim the NULs
1348 // that appends. The previous definition was char(32), so trim
1350 $this->mToken
= rtrim( $row->user_token
, " \0" );
1351 if ( $this->mToken
=== '' ) {
1352 $this->mToken
= null;
1358 if ( isset( $row->user_email
) ) {
1359 $this->mEmail
= $row->user_email
;
1360 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1361 $this->mEmailToken
= $row->user_email_token
;
1362 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1363 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1369 $this->mLoadedItems
= true;
1372 if ( is_array( $data ) ) {
1373 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1374 if ( !count( $data['user_groups'] ) ) {
1375 $this->mGroupMemberships
= [];
1377 $firstGroup = reset( $data['user_groups'] );
1378 if ( is_array( $firstGroup ) ||
is_object( $firstGroup ) ) {
1379 $this->mGroupMemberships
= [];
1380 foreach ( $data['user_groups'] as $row ) {
1381 $ugm = UserGroupMembership
::newFromRow( (object)$row );
1382 $this->mGroupMemberships
[$ugm->getGroup()] = $ugm;
1387 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1388 $this->loadOptions( $data['user_properties'] );
1394 * Load the data for this user object from another user object.
1398 protected function loadFromUserObject( $user ) {
1400 foreach ( self
::$mCacheVars as $var ) {
1401 $this->$var = $user->$var;
1406 * Load the groups from the database if they aren't already loaded.
1408 private function loadGroups() {
1409 if ( is_null( $this->mGroupMemberships
) ) {
1410 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
1411 ?
wfGetDB( DB_MASTER
)
1412 : wfGetDB( DB_REPLICA
);
1413 $this->mGroupMemberships
= UserGroupMembership
::getMembershipsForUser(
1419 * Add the user to the group if he/she meets given criteria.
1421 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1422 * possible to remove manually via Special:UserRights. In such case it
1423 * will not be re-added automatically. The user will also not lose the
1424 * group if they no longer meet the criteria.
1426 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1428 * @return array Array of groups the user has been promoted to.
1430 * @see $wgAutopromoteOnce
1432 public function addAutopromoteOnceGroups( $event ) {
1433 global $wgAutopromoteOnceLogInRC;
1435 if ( wfReadOnly() ||
!$this->getId() ) {
1439 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1440 if ( !count( $toPromote ) ) {
1444 if ( !$this->checkAndSetTouched() ) {
1445 return []; // raced out (bug T48834)
1448 $oldGroups = $this->getGroups(); // previous groups
1449 foreach ( $toPromote as $group ) {
1450 $this->addGroup( $group );
1452 // update groups in external authentication database
1453 Hooks
::run( 'UserGroupsChanged', [ $this, $toPromote, [], false, false ] );
1454 AuthManager
::callLegacyAuthPlugin( 'updateExternalDBGroups', [ $this, $toPromote ] );
1456 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1458 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1459 $logEntry->setPerformer( $this );
1460 $logEntry->setTarget( $this->getUserPage() );
1461 $logEntry->setParameters( [
1462 '4::oldgroups' => $oldGroups,
1463 '5::newgroups' => $newGroups,
1465 $logid = $logEntry->insert();
1466 if ( $wgAutopromoteOnceLogInRC ) {
1467 $logEntry->publish( $logid );
1474 * Builds update conditions. Additional conditions may be added to $conditions to
1475 * protected against race conditions using a compare-and-set (CAS) mechanism
1476 * based on comparing $this->mTouched with the user_touched field.
1478 * @param Database $db
1479 * @param array $conditions WHERE conditions for use with Database::update
1480 * @return array WHERE conditions for use with Database::update
1482 protected function makeUpdateConditions( Database
$db, array $conditions ) {
1483 if ( $this->mTouched
) {
1484 // CAS check: only update if the row wasn't changed sicne it was loaded.
1485 $conditions['user_touched'] = $db->timestamp( $this->mTouched
);
1492 * Bump user_touched if it didn't change since this object was loaded
1494 * On success, the mTouched field is updated.
1495 * The user serialization cache is always cleared.
1497 * @return bool Whether user_touched was actually updated
1500 protected function checkAndSetTouched() {
1503 if ( !$this->mId
) {
1504 return false; // anon
1507 // Get a new user_touched that is higher than the old one
1508 $newTouched = $this->newTouchedTimestamp();
1510 $dbw = wfGetDB( DB_MASTER
);
1511 $dbw->update( 'user',
1512 [ 'user_touched' => $dbw->timestamp( $newTouched ) ],
1513 $this->makeUpdateConditions( $dbw, [
1514 'user_id' => $this->mId
,
1518 $success = ( $dbw->affectedRows() > 0 );
1521 $this->mTouched
= $newTouched;
1522 $this->clearSharedCache();
1524 // Clears on failure too since that is desired if the cache is stale
1525 $this->clearSharedCache( 'refresh' );
1532 * Clear various cached data stored in this object. The cache of the user table
1533 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1535 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1536 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1538 public function clearInstanceCache( $reloadFrom = false ) {
1539 $this->mNewtalk
= -1;
1540 $this->mDatePreference
= null;
1541 $this->mBlockedby
= -1; # Unset
1542 $this->mHash
= false;
1543 $this->mRights
= null;
1544 $this->mEffectiveGroups
= null;
1545 $this->mImplicitGroups
= null;
1546 $this->mGroupMemberships
= null;
1547 $this->mOptions
= null;
1548 $this->mOptionsLoaded
= false;
1549 $this->mEditCount
= null;
1551 if ( $reloadFrom ) {
1552 $this->mLoadedItems
= [];
1553 $this->mFrom
= $reloadFrom;
1558 * Combine the language default options with any site-specific options
1559 * and add the default language variants.
1561 * @return array Array of String options
1563 public static function getDefaultOptions() {
1564 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1566 static $defOpt = null;
1567 static $defOptLang = null;
1569 if ( $defOpt !== null && $defOptLang === $wgContLang->getCode() ) {
1570 // $wgContLang does not change (and should not change) mid-request,
1571 // but the unit tests change it anyway, and expect this method to
1572 // return values relevant to the current $wgContLang.
1576 $defOpt = $wgDefaultUserOptions;
1577 // Default language setting
1578 $defOptLang = $wgContLang->getCode();
1579 $defOpt['language'] = $defOptLang;
1580 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1581 $defOpt[$langCode == $wgContLang->getCode() ?
'variant' : "variant-$langCode"] = $langCode;
1584 // NOTE: don't use SearchEngineConfig::getSearchableNamespaces here,
1585 // since extensions may change the set of searchable namespaces depending
1586 // on user groups/permissions.
1587 foreach ( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
1588 $defOpt['searchNs' . $nsnum] = (boolean
)$val;
1590 $defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1592 Hooks
::run( 'UserGetDefaultOptions', [ &$defOpt ] );
1598 * Get a given default option value.
1600 * @param string $opt Name of option to retrieve
1601 * @return string Default option value
1603 public static function getDefaultOption( $opt ) {
1604 $defOpts = self
::getDefaultOptions();
1605 if ( isset( $defOpts[$opt] ) ) {
1606 return $defOpts[$opt];
1613 * Get blocking information
1614 * @param bool $bFromSlave Whether to check the replica DB first.
1615 * To improve performance, non-critical checks are done against replica DBs.
1616 * Check when actually saving should be done against master.
1618 private function getBlockedStatus( $bFromSlave = true ) {
1619 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff, $wgSoftBlockRanges;
1621 if ( -1 != $this->mBlockedby
) {
1625 wfDebug( __METHOD__
. ": checking...\n" );
1627 // Initialize data...
1628 // Otherwise something ends up stomping on $this->mBlockedby when
1629 // things get lazy-loaded later, causing false positive block hits
1630 // due to -1 !== 0. Probably session-related... Nothing should be
1631 // overwriting mBlockedby, surely?
1634 # We only need to worry about passing the IP address to the Block generator if the
1635 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1636 # know which IP address they're actually coming from
1638 if ( !$this->isAllowed( 'ipblock-exempt' ) ) {
1639 // $wgUser->getName() only works after the end of Setup.php. Until
1640 // then, assume it's a logged-out user.
1641 $globalUserName = $wgUser->isSafeToLoad()
1642 ?
$wgUser->getName()
1643 : IP
::sanitizeIP( $wgUser->getRequest()->getIP() );
1644 if ( $this->getName() === $globalUserName ) {
1645 $ip = $this->getRequest()->getIP();
1650 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1653 if ( !$block instanceof Block
) {
1654 $block = $this->getBlockFromCookieValue( $this->getRequest()->getCookie( 'BlockID' ) );
1658 if ( !$block instanceof Block
&& $ip !== null && !in_array( $ip, $wgProxyWhitelist ) ) {
1660 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1661 $block = new Block( [
1662 'byText' => wfMessage( 'proxyblocker' )->text(),
1663 'reason' => wfMessage( 'proxyblockreason' )->text(),
1665 'systemBlock' => 'proxy',
1667 $this->blockTrigger
= 'proxy-block';
1668 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1669 $block = new Block( [
1670 'byText' => wfMessage( 'sorbs' )->text(),
1671 'reason' => wfMessage( 'sorbsreason' )->text(),
1673 'systemBlock' => 'dnsbl',
1675 $this->blockTrigger
= 'openproxy-block';
1679 // (T25343) Apply IP blocks to the contents of XFF headers, if enabled
1680 if ( !$block instanceof Block
1681 && $wgApplyIpBlocksToXff
1683 && !in_array( $ip, $wgProxyWhitelist )
1685 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1686 $xff = array_map( 'trim', explode( ',', $xff ) );
1687 $xff = array_diff( $xff, [ $ip ] );
1688 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1689 $block = Block
::chooseBlock( $xffblocks, $xff );
1690 if ( $block instanceof Block
) {
1691 # Mangle the reason to alert the user that the block
1692 # originated from matching the X-Forwarded-For header.
1693 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->text();
1694 $this->blockTrigger
= 'xff-block';
1698 if ( !$block instanceof Block
1701 && IP
::isInRanges( $ip, $wgSoftBlockRanges )
1703 $block = new Block( [
1705 'byText' => 'MediaWiki default',
1706 'reason' => wfMessage( 'softblockrangesreason', $ip )->text(),
1708 'systemBlock' => 'wgSoftBlockRanges',
1710 $this->blockTrigger
= 'config-block';
1713 if ( $block instanceof Block
) {
1714 wfDebug( __METHOD__
. ": Found block.\n" );
1715 $this->mBlock
= $block;
1716 $this->mBlockedby
= $block->getByName();
1717 $this->mBlockreason
= $block->mReason
;
1718 $this->mHideName
= $block->mHideName
;
1719 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1721 $this->mBlockedby
= '';
1722 $this->mHideName
= 0;
1723 $this->mAllowUsertalk
= false;
1724 $this->blockTrigger
= false;
1727 // Avoid PHP 7.1 warning of passing $this by reference
1730 Hooks
::run( 'GetBlockedStatus', [ &$user ] );
1734 * Try to load a Block from an ID given in a cookie value.
1735 * @param string|null $blockCookieVal The cookie value to check.
1736 * @return Block|bool The Block object, or false if none could be loaded.
1738 protected function getBlockFromCookieValue( $blockCookieVal ) {
1739 // Make sure there's something to check. The cookie value must start with a number.
1740 if ( strlen( $blockCookieVal ) < 1 ||
!is_numeric( substr( $blockCookieVal, 0, 1 ) ) ) {
1743 // Load the Block from the ID in the cookie.
1744 $blockCookieId = Block
::getIdFromCookieValue( $blockCookieVal );
1745 if ( $blockCookieId !== null ) {
1746 // An ID was found in the cookie.
1747 $tmpBlock = Block
::newFromID( $blockCookieId );
1748 if ( $tmpBlock instanceof Block
) {
1749 // Check the validity of the block.
1750 $blockIsValid = $tmpBlock->getType() == Block
::TYPE_USER
1751 && !$tmpBlock->isExpired()
1752 && $tmpBlock->isAutoblocking();
1753 $config = RequestContext
::getMain()->getConfig();
1754 $useBlockCookie = ( $config->get( 'CookieSetOnAutoblock' ) === true );
1755 if ( $blockIsValid && $useBlockCookie ) {
1757 $this->blockTrigger
= 'cookie-block';
1760 // If the block is not valid, remove the cookie.
1761 Block
::clearCookie( $this->getRequest()->response() );
1764 // If the block doesn't exist, remove the cookie.
1765 Block
::clearCookie( $this->getRequest()->response() );
1772 * Whether the given IP is in a DNS blacklist.
1774 * @param string $ip IP to check
1775 * @param bool $checkWhitelist Whether to check the whitelist first
1776 * @return bool True if blacklisted.
1778 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1779 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1781 if ( !$wgEnableDnsBlacklist ) {
1785 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1789 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1793 * Whether the given IP is in a given DNS blacklist.
1795 * @param string $ip IP to check
1796 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1797 * @return bool True if blacklisted.
1799 public function inDnsBlacklist( $ip, $bases ) {
1801 // @todo FIXME: IPv6 ??? (https://bugs.php.net/bug.php?id=33170)
1802 if ( IP
::isIPv4( $ip ) ) {
1803 // Reverse IP, T23255
1804 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1806 foreach ( (array)$bases as $base ) {
1808 // If we have an access key, use that too (ProjectHoneypot, etc.)
1810 if ( is_array( $base ) ) {
1811 if ( count( $base ) >= 2 ) {
1812 // Access key is 1, base URL is 0
1813 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1815 $host = "$ipReversed.{$base[0]}";
1817 $basename = $base[0];
1819 $host = "$ipReversed.$base";
1823 $ipList = gethostbynamel( $host );
1826 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
1830 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
1839 * Check if an IP address is in the local proxy list
1845 public static function isLocallyBlockedProxy( $ip ) {
1846 global $wgProxyList;
1848 if ( !$wgProxyList ) {
1852 if ( !is_array( $wgProxyList ) ) {
1853 // Load values from the specified file
1854 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1857 if ( is_array( $wgProxyList ) ) {
1859 // Look for IP as value
1860 array_search( $ip, $wgProxyList ) !== false ||
1861 // Look for IP as key (for backwards-compatility)
1862 array_key_exists( $ip, $wgProxyList )
1872 * Is this user subject to rate limiting?
1874 * @return bool True if rate limited
1876 public function isPingLimitable() {
1877 global $wgRateLimitsExcludedIPs;
1878 if ( IP
::isInRanges( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1879 // No other good way currently to disable rate limits
1880 // for specific IPs. :P
1881 // But this is a crappy hack and should die.
1884 return !$this->isAllowed( 'noratelimit' );
1888 * Primitive rate limits: enforce maximum actions per time period
1889 * to put a brake on flooding.
1891 * The method generates both a generic profiling point and a per action one
1892 * (suffix being "-$action".
1894 * @note When using a shared cache like memcached, IP-address
1895 * last-hit counters will be shared across wikis.
1897 * @param string $action Action to enforce; 'edit' if unspecified
1898 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1899 * @return bool True if a rate limiter was tripped
1901 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1902 // Avoid PHP 7.1 warning of passing $this by reference
1904 // Call the 'PingLimiter' hook
1906 if ( !Hooks
::run( 'PingLimiter', [ &$user, $action, &$result, $incrBy ] ) ) {
1910 global $wgRateLimits;
1911 if ( !isset( $wgRateLimits[$action] ) ) {
1915 $limits = array_merge(
1916 [ '&can-bypass' => true ],
1917 $wgRateLimits[$action]
1920 // Some groups shouldn't trigger the ping limiter, ever
1921 if ( $limits['&can-bypass'] && !$this->isPingLimitable() ) {
1926 $id = $this->getId();
1928 $isNewbie = $this->isNewbie();
1932 if ( isset( $limits['anon'] ) ) {
1933 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1936 // limits for logged-in users
1937 if ( isset( $limits['user'] ) ) {
1938 $userLimit = $limits['user'];
1940 // limits for newbie logged-in users
1941 if ( $isNewbie && isset( $limits['newbie'] ) ) {
1942 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1946 // limits for anons and for newbie logged-in users
1949 if ( isset( $limits['ip'] ) ) {
1950 $ip = $this->getRequest()->getIP();
1951 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1953 // subnet-based limits
1954 if ( isset( $limits['subnet'] ) ) {
1955 $ip = $this->getRequest()->getIP();
1956 $subnet = IP
::getSubnet( $ip );
1957 if ( $subnet !== false ) {
1958 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1963 // Check for group-specific permissions
1964 // If more than one group applies, use the group with the highest limit ratio (max/period)
1965 foreach ( $this->getGroups() as $group ) {
1966 if ( isset( $limits[$group] ) ) {
1967 if ( $userLimit === false
1968 ||
$limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1970 $userLimit = $limits[$group];
1975 // Set the user limit key
1976 if ( $userLimit !== false ) {
1977 list( $max, $period ) = $userLimit;
1978 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
1979 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1982 // ip-based limits for all ping-limitable users
1983 if ( isset( $limits['ip-all'] ) ) {
1984 $ip = $this->getRequest()->getIP();
1985 // ignore if user limit is more permissive
1986 if ( $isNewbie ||
$userLimit === false
1987 ||
$limits['ip-all'][0] / $limits['ip-all'][1] > $userLimit[0] / $userLimit[1] ) {
1988 $keys["mediawiki:limiter:$action:ip-all:$ip"] = $limits['ip-all'];
1992 // subnet-based limits for all ping-limitable users
1993 if ( isset( $limits['subnet-all'] ) ) {
1994 $ip = $this->getRequest()->getIP();
1995 $subnet = IP
::getSubnet( $ip );
1996 if ( $subnet !== false ) {
1997 // ignore if user limit is more permissive
1998 if ( $isNewbie ||
$userLimit === false
1999 ||
$limits['ip-all'][0] / $limits['ip-all'][1]
2000 > $userLimit[0] / $userLimit[1] ) {
2001 $keys["mediawiki:limiter:$action:subnet-all:$subnet"] = $limits['subnet-all'];
2006 $cache = ObjectCache
::getLocalClusterInstance();
2009 foreach ( $keys as $key => $limit ) {
2010 list( $max, $period ) = $limit;
2011 $summary = "(limit $max in {$period}s)";
2012 $count = $cache->get( $key );
2015 if ( $count >= $max ) {
2016 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
2017 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
2020 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
2023 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
2024 if ( $incrBy > 0 ) {
2025 $cache->add( $key, 0, intval( $period ) ); // first ping
2028 if ( $incrBy > 0 ) {
2029 $cache->incr( $key, $incrBy );
2037 * Check if user is blocked
2039 * @param bool $bFromSlave Whether to check the replica DB instead of
2040 * the master. Hacked from false due to horrible probs on site.
2041 * @return bool True if blocked, false otherwise
2043 public function isBlocked( $bFromSlave = true ) {
2044 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
2048 * Get the block affecting the user, or null if the user is not blocked
2050 * @param bool $bFromSlave Whether to check the replica DB instead of the master
2051 * @return Block|null
2053 public function getBlock( $bFromSlave = true ) {
2054 $this->getBlockedStatus( $bFromSlave );
2055 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
2059 * Check if user is blocked from editing a particular article
2061 * @param Title $title Title to check
2062 * @param bool $bFromSlave Whether to check the replica DB instead of the master
2065 public function isBlockedFrom( $title, $bFromSlave = false ) {
2066 global $wgBlockAllowsUTEdit;
2068 $blocked = $this->isBlocked( $bFromSlave );
2069 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
2070 // If a user's name is suppressed, they cannot make edits anywhere
2071 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName()
2072 && $title->getNamespace() == NS_USER_TALK
) {
2074 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
2077 Hooks
::run( 'UserIsBlockedFrom', [ $this, $title, &$blocked, &$allowUsertalk ] );
2083 * If user is blocked, return the name of the user who placed the block
2084 * @return string Name of blocker
2086 public function blockedBy() {
2087 $this->getBlockedStatus();
2088 return $this->mBlockedby
;
2092 * If user is blocked, return the specified reason for the block
2093 * @return string Blocking reason
2095 public function blockedFor() {
2096 $this->getBlockedStatus();
2097 return $this->mBlockreason
;
2101 * If user is blocked, return the ID for the block
2102 * @return int Block ID
2104 public function getBlockId() {
2105 $this->getBlockedStatus();
2106 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
2110 * Check if user is blocked on all wikis.
2111 * Do not use for actual edit permission checks!
2112 * This is intended for quick UI checks.
2114 * @param string $ip IP address, uses current client if none given
2115 * @return bool True if blocked, false otherwise
2117 public function isBlockedGlobally( $ip = '' ) {
2118 return $this->getGlobalBlock( $ip ) instanceof Block
;
2122 * Check if user is blocked on all wikis.
2123 * Do not use for actual edit permission checks!
2124 * This is intended for quick UI checks.
2126 * @param string $ip IP address, uses current client if none given
2127 * @return Block|null Block object if blocked, null otherwise
2128 * @throws FatalError
2129 * @throws MWException
2131 public function getGlobalBlock( $ip = '' ) {
2132 if ( $this->mGlobalBlock
!== null ) {
2133 return $this->mGlobalBlock ?
: null;
2135 // User is already an IP?
2136 if ( IP
::isIPAddress( $this->getName() ) ) {
2137 $ip = $this->getName();
2139 $ip = $this->getRequest()->getIP();
2141 // Avoid PHP 7.1 warning of passing $this by reference
2145 Hooks
::run( 'UserIsBlockedGlobally', [ &$user, $ip, &$blocked, &$block ] );
2147 if ( $blocked && $block === null ) {
2148 // back-compat: UserIsBlockedGlobally didn't have $block param first
2149 $block = new Block( [
2151 'systemBlock' => 'global-block'
2155 $this->mGlobalBlock
= $blocked ?
$block : false;
2156 return $this->mGlobalBlock ?
: null;
2160 * Check if user account is locked
2162 * @return bool True if locked, false otherwise
2164 public function isLocked() {
2165 if ( $this->mLocked
!== null ) {
2166 return $this->mLocked
;
2168 // Avoid PHP 7.1 warning of passing $this by reference
2170 $authUser = AuthManager
::callLegacyAuthPlugin( 'getUserInstance', [ &$user ], null );
2171 $this->mLocked
= $authUser && $authUser->isLocked();
2172 Hooks
::run( 'UserIsLocked', [ $this, &$this->mLocked
] );
2173 return $this->mLocked
;
2177 * Check if user account is hidden
2179 * @return bool True if hidden, false otherwise
2181 public function isHidden() {
2182 if ( $this->mHideName
!== null ) {
2183 return $this->mHideName
;
2185 $this->getBlockedStatus();
2186 if ( !$this->mHideName
) {
2187 // Avoid PHP 7.1 warning of passing $this by reference
2189 $authUser = AuthManager
::callLegacyAuthPlugin( 'getUserInstance', [ &$user ], null );
2190 $this->mHideName
= $authUser && $authUser->isHidden();
2191 Hooks
::run( 'UserIsHidden', [ $this, &$this->mHideName
] );
2193 return $this->mHideName
;
2197 * Get the user's ID.
2198 * @return int The user's ID; 0 if the user is anonymous or nonexistent
2200 public function getId() {
2201 if ( $this->mId
=== null && $this->mName
!== null && User
::isIP( $this->mName
) ) {
2202 // Special case, we know the user is anonymous
2204 } elseif ( !$this->isItemLoaded( 'id' ) ) {
2205 // Don't load if this was initialized from an ID
2209 return (int)$this->mId
;
2213 * Set the user and reload all fields according to a given ID
2214 * @param int $v User ID to reload
2216 public function setId( $v ) {
2218 $this->clearInstanceCache( 'id' );
2222 * Get the user name, or the IP of an anonymous user
2223 * @return string User's name or IP address
2225 public function getName() {
2226 if ( $this->isItemLoaded( 'name', 'only' ) ) {
2227 // Special case optimisation
2228 return $this->mName
;
2231 if ( $this->mName
=== false ) {
2233 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
2235 return $this->mName
;
2240 * Set the user name.
2242 * This does not reload fields from the database according to the given
2243 * name. Rather, it is used to create a temporary "nonexistent user" for
2244 * later addition to the database. It can also be used to set the IP
2245 * address for an anonymous user to something other than the current
2248 * @note User::newFromName() has roughly the same function, when the named user
2250 * @param string $str New user name to set
2252 public function setName( $str ) {
2254 $this->mName
= $str;
2258 * Get the user's name escaped by underscores.
2259 * @return string Username escaped by underscores.
2261 public function getTitleKey() {
2262 return str_replace( ' ', '_', $this->getName() );
2266 * Check if the user has new messages.
2267 * @return bool True if the user has new messages
2269 public function getNewtalk() {
2272 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2273 if ( $this->mNewtalk
=== -1 ) {
2274 $this->mNewtalk
= false; # reset talk page status
2276 // Check memcached separately for anons, who have no
2277 // entire User object stored in there.
2278 if ( !$this->mId
) {
2279 global $wgDisableAnonTalk;
2280 if ( $wgDisableAnonTalk ) {
2281 // Anon newtalk disabled by configuration.
2282 $this->mNewtalk
= false;
2284 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
2287 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2291 return (bool)$this->mNewtalk
;
2295 * Return the data needed to construct links for new talk page message
2296 * alerts. If there are new messages, this will return an associative array
2297 * with the following data:
2298 * wiki: The database name of the wiki
2299 * link: Root-relative link to the user's talk page
2300 * rev: The last talk page revision that the user has seen or null. This
2301 * is useful for building diff links.
2302 * If there are no new messages, it returns an empty array.
2303 * @note This function was designed to accomodate multiple talk pages, but
2304 * currently only returns a single link and revision.
2307 public function getNewMessageLinks() {
2308 // Avoid PHP 7.1 warning of passing $this by reference
2311 if ( !Hooks
::run( 'UserRetrieveNewTalks', [ &$user, &$talks ] ) ) {
2313 } elseif ( !$this->getNewtalk() ) {
2316 $utp = $this->getTalkPage();
2317 $dbr = wfGetDB( DB_REPLICA
);
2318 // Get the "last viewed rev" timestamp from the oldest message notification
2319 $timestamp = $dbr->selectField( 'user_newtalk',
2320 'MIN(user_last_timestamp)',
2321 $this->isAnon() ?
[ 'user_ip' => $this->getName() ] : [ 'user_id' => $this->getId() ],
2323 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2324 return [ [ 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ] ];
2328 * Get the revision ID for the last talk page revision viewed by the talk
2330 * @return int|null Revision ID or null
2332 public function getNewMessageRevisionId() {
2333 $newMessageRevisionId = null;
2334 $newMessageLinks = $this->getNewMessageLinks();
2335 if ( $newMessageLinks ) {
2336 // Note: getNewMessageLinks() never returns more than a single link
2337 // and it is always for the same wiki, but we double-check here in
2338 // case that changes some time in the future.
2339 if ( count( $newMessageLinks ) === 1
2340 && $newMessageLinks[0]['wiki'] === wfWikiID()
2341 && $newMessageLinks[0]['rev']
2343 /** @var Revision $newMessageRevision */
2344 $newMessageRevision = $newMessageLinks[0]['rev'];
2345 $newMessageRevisionId = $newMessageRevision->getId();
2348 return $newMessageRevisionId;
2352 * Internal uncached check for new messages
2355 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2356 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2357 * @return bool True if the user has new messages
2359 protected function checkNewtalk( $field, $id ) {
2360 $dbr = wfGetDB( DB_REPLICA
);
2362 $ok = $dbr->selectField( 'user_newtalk', $field, [ $field => $id ], __METHOD__
);
2364 return $ok !== false;
2368 * Add or update the new messages flag
2369 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2370 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2371 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2372 * @return bool True if successful, false otherwise
2374 protected function updateNewtalk( $field, $id, $curRev = null ) {
2375 // Get timestamp of the talk page revision prior to the current one
2376 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2377 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2378 // Mark the user as having new messages since this revision
2379 $dbw = wfGetDB( DB_MASTER
);
2380 $dbw->insert( 'user_newtalk',
2381 [ $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ],
2384 if ( $dbw->affectedRows() ) {
2385 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2388 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2394 * Clear the new messages flag for the given user
2395 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2396 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2397 * @return bool True if successful, false otherwise
2399 protected function deleteNewtalk( $field, $id ) {
2400 $dbw = wfGetDB( DB_MASTER
);
2401 $dbw->delete( 'user_newtalk',
2404 if ( $dbw->affectedRows() ) {
2405 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2408 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2414 * Update the 'You have new messages!' status.
2415 * @param bool $val Whether the user has new messages
2416 * @param Revision $curRev New, as yet unseen revision of the user talk
2417 * page. Ignored if null or !$val.
2419 public function setNewtalk( $val, $curRev = null ) {
2420 if ( wfReadOnly() ) {
2425 $this->mNewtalk
= $val;
2427 if ( $this->isAnon() ) {
2429 $id = $this->getName();
2432 $id = $this->getId();
2436 $changed = $this->updateNewtalk( $field, $id, $curRev );
2438 $changed = $this->deleteNewtalk( $field, $id );
2442 $this->invalidateCache();
2447 * Generate a current or new-future timestamp to be stored in the
2448 * user_touched field when we update things.
2449 * @return string Timestamp in TS_MW format
2451 private function newTouchedTimestamp() {
2452 global $wgClockSkewFudge;
2454 $time = wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2455 if ( $this->mTouched
&& $time <= $this->mTouched
) {
2456 $time = wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $this->mTouched
) +
1 );
2463 * Clear user data from memcached
2465 * Use after applying updates to the database; caller's
2466 * responsibility to update user_touched if appropriate.
2468 * Called implicitly from invalidateCache() and saveSettings().
2470 * @param string $mode Use 'refresh' to clear now; otherwise before DB commit
2472 public function clearSharedCache( $mode = 'changed' ) {
2473 if ( !$this->getId() ) {
2477 $cache = ObjectCache
::getMainWANInstance();
2478 $key = $this->getCacheKey( $cache );
2479 if ( $mode === 'refresh' ) {
2480 $cache->delete( $key, 1 );
2482 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle(
2483 function() use ( $cache, $key ) {
2484 $cache->delete( $key );
2492 * Immediately touch the user data cache for this account
2494 * Calls touch() and removes account data from memcached
2496 public function invalidateCache() {
2498 $this->clearSharedCache();
2502 * Update the "touched" timestamp for the user
2504 * This is useful on various login/logout events when making sure that
2505 * a browser or proxy that has multiple tenants does not suffer cache
2506 * pollution where the new user sees the old users content. The value
2507 * of getTouched() is checked when determining 304 vs 200 responses.
2508 * Unlike invalidateCache(), this preserves the User object cache and
2509 * avoids database writes.
2513 public function touch() {
2514 $id = $this->getId();
2516 $key = wfMemcKey( 'user-quicktouched', 'id', $id );
2517 ObjectCache
::getMainWANInstance()->touchCheckKey( $key );
2518 $this->mQuickTouched
= null;
2523 * Validate the cache for this account.
2524 * @param string $timestamp A timestamp in TS_MW format
2527 public function validateCache( $timestamp ) {
2528 return ( $timestamp >= $this->getTouched() );
2532 * Get the user touched timestamp
2534 * Use this value only to validate caches via inequalities
2535 * such as in the case of HTTP If-Modified-Since response logic
2537 * @return string TS_MW Timestamp
2539 public function getTouched() {
2543 if ( $this->mQuickTouched
=== null ) {
2544 $key = wfMemcKey( 'user-quicktouched', 'id', $this->mId
);
2545 $cache = ObjectCache
::getMainWANInstance();
2547 $this->mQuickTouched
= wfTimestamp( TS_MW
, $cache->getCheckKeyTime( $key ) );
2550 return max( $this->mTouched
, $this->mQuickTouched
);
2553 return $this->mTouched
;
2557 * Get the user_touched timestamp field (time of last DB updates)
2558 * @return string TS_MW Timestamp
2561 public function getDBTouched() {
2564 return $this->mTouched
;
2568 * Set the password and reset the random token.
2569 * Calls through to authentication plugin if necessary;
2570 * will have no effect if the auth plugin refuses to
2571 * pass the change through or if the legal password
2574 * As a special case, setting the password to null
2575 * wipes it, so the account cannot be logged in until
2576 * a new password is set, for instance via e-mail.
2578 * @deprecated since 1.27, use AuthManager instead
2579 * @param string $str New password to set
2580 * @throws PasswordError On failure
2583 public function setPassword( $str ) {
2584 return $this->setPasswordInternal( $str );
2588 * Set the password and reset the random token unconditionally.
2590 * @deprecated since 1.27, use AuthManager instead
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.
2595 public function setInternalPassword( $str ) {
2596 $this->setPasswordInternal( $str );
2600 * Actually set the password and such
2601 * @since 1.27 cannot set a password for a user not in the database
2602 * @param string|null $str New password to set or null to set an invalid
2603 * password hash meaning that the user will not be able to log in
2604 * through the web interface.
2605 * @return bool Success
2607 private function setPasswordInternal( $str ) {
2608 $manager = AuthManager
::singleton();
2610 // If the user doesn't exist yet, fail
2611 if ( !$manager->userExists( $this->getName() ) ) {
2612 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2615 $status = $this->changeAuthenticationData( [
2616 'username' => $this->getName(),
2620 if ( !$status->isGood() ) {
2621 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
2622 ->info( __METHOD__
. ': Password change rejected: '
2623 . $status->getWikiText( null, null, 'en' ) );
2627 $this->setOption( 'watchlisttoken', false );
2628 SessionManager
::singleton()->invalidateSessionsForUser( $this );
2634 * Changes credentials of the user.
2636 * This is a convenience wrapper around AuthManager::changeAuthenticationData.
2637 * Note that this can return a status that isOK() but not isGood() on certain types of failures,
2638 * e.g. when no provider handled the change.
2640 * @param array $data A set of authentication data in fieldname => value format. This is the
2641 * same data you would pass the changeauthenticationdata API - 'username', 'password' etc.
2645 public function changeAuthenticationData( array $data ) {
2646 $manager = AuthManager
::singleton();
2647 $reqs = $manager->getAuthenticationRequests( AuthManager
::ACTION_CHANGE
, $this );
2648 $reqs = AuthenticationRequest
::loadRequestsFromSubmission( $reqs, $data );
2650 $status = Status
::newGood( 'ignored' );
2651 foreach ( $reqs as $req ) {
2652 $status->merge( $manager->allowsAuthenticationDataChange( $req ), true );
2654 if ( $status->getValue() === 'ignored' ) {
2655 $status->warning( 'authenticationdatachange-ignored' );
2658 if ( $status->isGood() ) {
2659 foreach ( $reqs as $req ) {
2660 $manager->changeAuthenticationData( $req );
2667 * Get the user's current token.
2668 * @param bool $forceCreation Force the generation of a new token if the
2669 * user doesn't have one (default=true for backwards compatibility).
2670 * @return string|null Token
2672 public function getToken( $forceCreation = true ) {
2673 global $wgAuthenticationTokenVersion;
2676 if ( !$this->mToken
&& $forceCreation ) {
2680 if ( !$this->mToken
) {
2681 // The user doesn't have a token, return null to indicate that.
2683 } elseif ( $this->mToken
=== self
::INVALID_TOKEN
) {
2684 // We return a random value here so existing token checks are very
2686 return MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2687 } elseif ( $wgAuthenticationTokenVersion === null ) {
2688 // $wgAuthenticationTokenVersion not in use, so return the raw secret
2689 return $this->mToken
;
2691 // $wgAuthenticationTokenVersion in use, so hmac it.
2692 $ret = MWCryptHash
::hmac( $wgAuthenticationTokenVersion, $this->mToken
, false );
2694 // The raw hash can be overly long. Shorten it up.
2695 $len = max( 32, self
::TOKEN_LENGTH
);
2696 if ( strlen( $ret ) < $len ) {
2697 // Should never happen, even md5 is 128 bits
2698 throw new \
UnexpectedValueException( 'Hmac returned less than 128 bits' );
2700 return substr( $ret, -$len );
2705 * Set the random token (used for persistent authentication)
2706 * Called from loadDefaults() among other places.
2708 * @param string|bool $token If specified, set the token to this value
2710 public function setToken( $token = false ) {
2712 if ( $this->mToken
=== self
::INVALID_TOKEN
) {
2713 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
2714 ->debug( __METHOD__
. ": Ignoring attempt to set token for system user \"$this\"" );
2715 } elseif ( !$token ) {
2716 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2718 $this->mToken
= $token;
2723 * Set the password for a password reminder or new account email
2725 * @deprecated Removed in 1.27. Use PasswordReset instead.
2726 * @param string $str New password to set or null to set an invalid
2727 * password hash meaning that the user will not be able to use it
2728 * @param bool $throttle If true, reset the throttle timestamp to the present
2730 public function setNewpassword( $str, $throttle = true ) {
2731 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2735 * Get the user's e-mail address
2736 * @return string User's email address
2738 public function getEmail() {
2740 Hooks
::run( 'UserGetEmail', [ $this, &$this->mEmail
] );
2741 return $this->mEmail
;
2745 * Get the timestamp of the user's e-mail authentication
2746 * @return string TS_MW timestamp
2748 public function getEmailAuthenticationTimestamp() {
2750 Hooks
::run( 'UserGetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
2751 return $this->mEmailAuthenticated
;
2755 * Set the user's e-mail address
2756 * @param string $str New e-mail address
2758 public function setEmail( $str ) {
2760 if ( $str == $this->mEmail
) {
2763 $this->invalidateEmail();
2764 $this->mEmail
= $str;
2765 Hooks
::run( 'UserSetEmail', [ $this, &$this->mEmail
] );
2769 * Set the user's e-mail address and a confirmation mail if needed.
2772 * @param string $str New e-mail address
2775 public function setEmailWithConfirmation( $str ) {
2776 global $wgEnableEmail, $wgEmailAuthentication;
2778 if ( !$wgEnableEmail ) {
2779 return Status
::newFatal( 'emaildisabled' );
2782 $oldaddr = $this->getEmail();
2783 if ( $str === $oldaddr ) {
2784 return Status
::newGood( true );
2787 $type = $oldaddr != '' ?
'changed' : 'set';
2788 $notificationResult = null;
2790 if ( $wgEmailAuthentication ) {
2791 // Send the user an email notifying the user of the change in registered
2792 // email address on their previous email address
2793 if ( $type == 'changed' ) {
2794 $change = $str != '' ?
'changed' : 'removed';
2795 $notificationResult = $this->sendMail(
2796 wfMessage( 'notificationemail_subject_' . $change )->text(),
2797 wfMessage( 'notificationemail_body_' . $change,
2798 $this->getRequest()->getIP(),
2805 $this->setEmail( $str );
2807 if ( $str !== '' && $wgEmailAuthentication ) {
2808 // Send a confirmation request to the new address if needed
2809 $result = $this->sendConfirmationMail( $type );
2811 if ( $notificationResult !== null ) {
2812 $result->merge( $notificationResult );
2815 if ( $result->isGood() ) {
2816 // Say to the caller that a confirmation and notification mail has been sent
2817 $result->value
= 'eauth';
2820 $result = Status
::newGood( true );
2827 * Get the user's real name
2828 * @return string User's real name
2830 public function getRealName() {
2831 if ( !$this->isItemLoaded( 'realname' ) ) {
2835 return $this->mRealName
;
2839 * Set the user's real name
2840 * @param string $str New real name
2842 public function setRealName( $str ) {
2844 $this->mRealName
= $str;
2848 * Get the user's current setting for a given option.
2850 * @param string $oname The option to check
2851 * @param string $defaultOverride A default value returned if the option does not exist
2852 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2853 * @return string|null User's current value for the option
2854 * @see getBoolOption()
2855 * @see getIntOption()
2857 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2858 global $wgHiddenPrefs;
2859 $this->loadOptions();
2861 # We want 'disabled' preferences to always behave as the default value for
2862 # users, even if they have set the option explicitly in their settings (ie they
2863 # set it, and then it was disabled removing their ability to change it). But
2864 # we don't want to erase the preferences in the database in case the preference
2865 # is re-enabled again. So don't touch $mOptions, just override the returned value
2866 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2867 return self
::getDefaultOption( $oname );
2870 if ( array_key_exists( $oname, $this->mOptions
) ) {
2871 return $this->mOptions
[$oname];
2873 return $defaultOverride;
2878 * Get all user's options
2880 * @param int $flags Bitwise combination of:
2881 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2882 * to the default value. (Since 1.25)
2885 public function getOptions( $flags = 0 ) {
2886 global $wgHiddenPrefs;
2887 $this->loadOptions();
2888 $options = $this->mOptions
;
2890 # We want 'disabled' preferences to always behave as the default value for
2891 # users, even if they have set the option explicitly in their settings (ie they
2892 # set it, and then it was disabled removing their ability to change it). But
2893 # we don't want to erase the preferences in the database in case the preference
2894 # is re-enabled again. So don't touch $mOptions, just override the returned value
2895 foreach ( $wgHiddenPrefs as $pref ) {
2896 $default = self
::getDefaultOption( $pref );
2897 if ( $default !== null ) {
2898 $options[$pref] = $default;
2902 if ( $flags & self
::GETOPTIONS_EXCLUDE_DEFAULTS
) {
2903 $options = array_diff_assoc( $options, self
::getDefaultOptions() );
2910 * Get the user's current setting for a given option, as a boolean value.
2912 * @param string $oname The option to check
2913 * @return bool User's current value for the option
2916 public function getBoolOption( $oname ) {
2917 return (bool)$this->getOption( $oname );
2921 * Get the user's current setting for a given option, as an integer value.
2923 * @param string $oname The option to check
2924 * @param int $defaultOverride A default value returned if the option does not exist
2925 * @return int User's current value for the option
2928 public function getIntOption( $oname, $defaultOverride = 0 ) {
2929 $val = $this->getOption( $oname );
2931 $val = $defaultOverride;
2933 return intval( $val );
2937 * Set the given option for a user.
2939 * You need to call saveSettings() to actually write to the database.
2941 * @param string $oname The option to set
2942 * @param mixed $val New value to set
2944 public function setOption( $oname, $val ) {
2945 $this->loadOptions();
2947 // Explicitly NULL values should refer to defaults
2948 if ( is_null( $val ) ) {
2949 $val = self
::getDefaultOption( $oname );
2952 $this->mOptions
[$oname] = $val;
2956 * Get a token stored in the preferences (like the watchlist one),
2957 * resetting it if it's empty (and saving changes).
2959 * @param string $oname The option name to retrieve the token from
2960 * @return string|bool User's current value for the option, or false if this option is disabled.
2961 * @see resetTokenFromOption()
2963 * @deprecated since 1.26 Applications should use the OAuth extension
2965 public function getTokenFromOption( $oname ) {
2966 global $wgHiddenPrefs;
2968 $id = $this->getId();
2969 if ( !$id ||
in_array( $oname, $wgHiddenPrefs ) ) {
2973 $token = $this->getOption( $oname );
2975 // Default to a value based on the user token to avoid space
2976 // wasted on storing tokens for all users. When this option
2977 // is set manually by the user, only then is it stored.
2978 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
2985 * Reset a token stored in the preferences (like the watchlist one).
2986 * *Does not* save user's preferences (similarly to setOption()).
2988 * @param string $oname The option name to reset the token in
2989 * @return string|bool New token value, or false if this option is disabled.
2990 * @see getTokenFromOption()
2993 public function resetTokenFromOption( $oname ) {
2994 global $wgHiddenPrefs;
2995 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2999 $token = MWCryptRand
::generateHex( 40 );
3000 $this->setOption( $oname, $token );
3005 * Return a list of the types of user options currently returned by
3006 * User::getOptionKinds().
3008 * Currently, the option kinds are:
3009 * - 'registered' - preferences which are registered in core MediaWiki or
3010 * by extensions using the UserGetDefaultOptions hook.
3011 * - 'registered-multiselect' - as above, using the 'multiselect' type.
3012 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
3013 * - 'userjs' - preferences with names starting with 'userjs-', intended to
3014 * be used by user scripts.
3015 * - 'special' - "preferences" that are not accessible via User::getOptions
3016 * or User::setOptions.
3017 * - 'unused' - preferences about which MediaWiki doesn't know anything.
3018 * These are usually legacy options, removed in newer versions.
3020 * The API (and possibly others) use this function to determine the possible
3021 * option types for validation purposes, so make sure to update this when a
3022 * new option kind is added.
3024 * @see User::getOptionKinds
3025 * @return array Option kinds
3027 public static function listOptionKinds() {
3030 'registered-multiselect',
3031 'registered-checkmatrix',
3039 * Return an associative array mapping preferences keys to the kind of a preference they're
3040 * used for. Different kinds are handled differently when setting or reading preferences.
3042 * See User::listOptionKinds for the list of valid option types that can be provided.
3044 * @see User::listOptionKinds
3045 * @param IContextSource $context
3046 * @param array $options Assoc. array with options keys to check as keys.
3047 * Defaults to $this->mOptions.
3048 * @return array The key => kind mapping data
3050 public function getOptionKinds( IContextSource
$context, $options = null ) {
3051 $this->loadOptions();
3052 if ( $options === null ) {
3053 $options = $this->mOptions
;
3056 $prefs = Preferences
::getPreferences( $this, $context );
3059 // Pull out the "special" options, so they don't get converted as
3060 // multiselect or checkmatrix.
3061 $specialOptions = array_fill_keys( Preferences
::getSaveBlacklist(), true );
3062 foreach ( $specialOptions as $name => $value ) {
3063 unset( $prefs[$name] );
3066 // Multiselect and checkmatrix options are stored in the database with
3067 // one key per option, each having a boolean value. Extract those keys.
3068 $multiselectOptions = [];
3069 foreach ( $prefs as $name => $info ) {
3070 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
3071 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
3072 $opts = HTMLFormField
::flattenOptions( $info['options'] );
3073 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
3075 foreach ( $opts as $value ) {
3076 $multiselectOptions["$prefix$value"] = true;
3079 unset( $prefs[$name] );
3082 $checkmatrixOptions = [];
3083 foreach ( $prefs as $name => $info ) {
3084 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
3085 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
3086 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
3087 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
3088 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
3090 foreach ( $columns as $column ) {
3091 foreach ( $rows as $row ) {
3092 $checkmatrixOptions["$prefix$column-$row"] = true;
3096 unset( $prefs[$name] );
3100 // $value is ignored
3101 foreach ( $options as $key => $value ) {
3102 if ( isset( $prefs[$key] ) ) {
3103 $mapping[$key] = 'registered';
3104 } elseif ( isset( $multiselectOptions[$key] ) ) {
3105 $mapping[$key] = 'registered-multiselect';
3106 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
3107 $mapping[$key] = 'registered-checkmatrix';
3108 } elseif ( isset( $specialOptions[$key] ) ) {
3109 $mapping[$key] = 'special';
3110 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
3111 $mapping[$key] = 'userjs';
3113 $mapping[$key] = 'unused';
3121 * Reset certain (or all) options to the site defaults
3123 * The optional parameter determines which kinds of preferences will be reset.
3124 * Supported values are everything that can be reported by getOptionKinds()
3125 * and 'all', which forces a reset of *all* preferences and overrides everything else.
3127 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
3128 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
3129 * for backwards-compatibility.
3130 * @param IContextSource|null $context Context source used when $resetKinds
3131 * does not contain 'all', passed to getOptionKinds().
3132 * Defaults to RequestContext::getMain() when null.
3134 public function resetOptions(
3135 $resetKinds = [ 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ],
3136 IContextSource
$context = null
3139 $defaultOptions = self
::getDefaultOptions();
3141 if ( !is_array( $resetKinds ) ) {
3142 $resetKinds = [ $resetKinds ];
3145 if ( in_array( 'all', $resetKinds ) ) {
3146 $newOptions = $defaultOptions;
3148 if ( $context === null ) {
3149 $context = RequestContext
::getMain();
3152 $optionKinds = $this->getOptionKinds( $context );
3153 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
3156 // Use default values for the options that should be deleted, and
3157 // copy old values for the ones that shouldn't.
3158 foreach ( $this->mOptions
as $key => $value ) {
3159 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
3160 if ( array_key_exists( $key, $defaultOptions ) ) {
3161 $newOptions[$key] = $defaultOptions[$key];
3164 $newOptions[$key] = $value;
3169 Hooks
::run( 'UserResetAllOptions', [ $this, &$newOptions, $this->mOptions
, $resetKinds ] );
3171 $this->mOptions
= $newOptions;
3172 $this->mOptionsLoaded
= true;
3176 * Get the user's preferred date format.
3177 * @return string User's preferred date format
3179 public function getDatePreference() {
3180 // Important migration for old data rows
3181 if ( is_null( $this->mDatePreference
) ) {
3183 $value = $this->getOption( 'date' );
3184 $map = $wgLang->getDatePreferenceMigrationMap();
3185 if ( isset( $map[$value] ) ) {
3186 $value = $map[$value];
3188 $this->mDatePreference
= $value;
3190 return $this->mDatePreference
;
3194 * Determine based on the wiki configuration and the user's options,
3195 * whether this user must be over HTTPS no matter what.
3199 public function requiresHTTPS() {
3200 global $wgSecureLogin;
3201 if ( !$wgSecureLogin ) {
3204 $https = $this->getBoolOption( 'prefershttps' );
3205 Hooks
::run( 'UserRequiresHTTPS', [ $this, &$https ] );
3207 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
3214 * Get the user preferred stub threshold
3218 public function getStubThreshold() {
3219 global $wgMaxArticleSize; # Maximum article size, in Kb
3220 $threshold = $this->getIntOption( 'stubthreshold' );
3221 if ( $threshold > $wgMaxArticleSize * 1024 ) {
3222 // If they have set an impossible value, disable the preference
3223 // so we can use the parser cache again.
3230 * Get the permissions this user has.
3231 * @return string[] permission names
3233 public function getRights() {
3234 if ( is_null( $this->mRights
) ) {
3235 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
3236 Hooks
::run( 'UserGetRights', [ $this, &$this->mRights
] );
3238 // Deny any rights denied by the user's session, unless this
3239 // endpoint has no sessions.
3240 if ( !defined( 'MW_NO_SESSION' ) ) {
3241 $allowedRights = $this->getRequest()->getSession()->getAllowedUserRights();
3242 if ( $allowedRights !== null ) {
3243 $this->mRights
= array_intersect( $this->mRights
, $allowedRights );
3247 // Force reindexation of rights when a hook has unset one of them
3248 $this->mRights
= array_values( array_unique( $this->mRights
) );
3250 // If block disables login, we should also remove any
3251 // extra rights blocked users might have, in case the
3252 // blocked user has a pre-existing session (T129738).
3253 // This is checked here for cases where people only call
3254 // $user->isAllowed(). It is also checked in Title::checkUserBlock()
3255 // to give a better error message in the common case.
3256 $config = RequestContext
::getMain()->getConfig();
3258 $this->isLoggedIn() &&
3259 $config->get( 'BlockDisablesLogin' ) &&
3263 $this->mRights
= array_intersect( $this->mRights
, $anon->getRights() );
3266 return $this->mRights
;
3270 * Get the list of explicit group memberships this user has.
3271 * The implicit * and user groups are not included.
3272 * @return array Array of String internal group names
3274 public function getGroups() {
3276 $this->loadGroups();
3277 return array_keys( $this->mGroupMemberships
);
3281 * Get the list of explicit group memberships this user has, stored as
3282 * UserGroupMembership objects. Implicit groups are not included.
3284 * @return array Associative array of (group name as string => UserGroupMembership object)
3287 public function getGroupMemberships() {
3289 $this->loadGroups();
3290 return $this->mGroupMemberships
;
3294 * Get the list of implicit group memberships this user has.
3295 * This includes all explicit groups, plus 'user' if logged in,
3296 * '*' for all accounts, and autopromoted groups
3297 * @param bool $recache Whether to avoid the cache
3298 * @return array Array of String internal group names
3300 public function getEffectiveGroups( $recache = false ) {
3301 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
3302 $this->mEffectiveGroups
= array_unique( array_merge(
3303 $this->getGroups(), // explicit groups
3304 $this->getAutomaticGroups( $recache ) // implicit groups
3306 // Avoid PHP 7.1 warning of passing $this by reference
3308 // Hook for additional groups
3309 Hooks
::run( 'UserEffectiveGroups', [ &$user, &$this->mEffectiveGroups
] );
3310 // Force reindexation of groups when a hook has unset one of them
3311 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
3313 return $this->mEffectiveGroups
;
3317 * Get the list of implicit group memberships this user has.
3318 * This includes 'user' if logged in, '*' for all accounts,
3319 * and autopromoted groups
3320 * @param bool $recache Whether to avoid the cache
3321 * @return array Array of String internal group names
3323 public function getAutomaticGroups( $recache = false ) {
3324 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
3325 $this->mImplicitGroups
= [ '*' ];
3326 if ( $this->getId() ) {
3327 $this->mImplicitGroups
[] = 'user';
3329 $this->mImplicitGroups
= array_unique( array_merge(
3330 $this->mImplicitGroups
,
3331 Autopromote
::getAutopromoteGroups( $this )
3335 // Assure data consistency with rights/groups,
3336 // as getEffectiveGroups() depends on this function
3337 $this->mEffectiveGroups
= null;
3340 return $this->mImplicitGroups
;
3344 * Returns the groups the user has belonged to.
3346 * The user may still belong to the returned groups. Compare with getGroups().
3348 * The function will not return groups the user had belonged to before MW 1.17
3350 * @return array Names of the groups the user has belonged to.
3352 public function getFormerGroups() {
3355 if ( is_null( $this->mFormerGroups
) ) {
3356 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3357 ?
wfGetDB( DB_MASTER
)
3358 : wfGetDB( DB_REPLICA
);
3359 $res = $db->select( 'user_former_groups',
3361 [ 'ufg_user' => $this->mId
],
3363 $this->mFormerGroups
= [];
3364 foreach ( $res as $row ) {
3365 $this->mFormerGroups
[] = $row->ufg_group
;
3369 return $this->mFormerGroups
;
3373 * Get the user's edit count.
3374 * @return int|null Null for anonymous users
3376 public function getEditCount() {
3377 if ( !$this->getId() ) {
3381 if ( $this->mEditCount
=== null ) {
3382 /* Populate the count, if it has not been populated yet */
3383 $dbr = wfGetDB( DB_REPLICA
);
3384 // check if the user_editcount field has been initialized
3385 $count = $dbr->selectField(
3386 'user', 'user_editcount',
3387 [ 'user_id' => $this->mId
],
3391 if ( $count === null ) {
3392 // it has not been initialized. do so.
3393 $count = $this->initEditCount();
3395 $this->mEditCount
= $count;
3397 return (int)$this->mEditCount
;
3401 * Add the user to the given group. This takes immediate effect.
3402 * If the user is already in the group, the expiry time will be updated to the new
3403 * expiry time. (If $expiry is omitted or null, the membership will be altered to
3406 * @param string $group Name of the group to add
3407 * @param string $expiry Optional expiry timestamp in any format acceptable to
3408 * wfTimestamp(), or null if the group assignment should not expire
3411 public function addGroup( $group, $expiry = null ) {
3413 $this->loadGroups();
3416 $expiry = wfTimestamp( TS_MW
, $expiry );
3419 if ( !Hooks
::run( 'UserAddGroup', [ $this, &$group, &$expiry ] ) ) {
3423 // create the new UserGroupMembership and put it in the DB
3424 $ugm = new UserGroupMembership( $this->mId
, $group, $expiry );
3425 if ( !$ugm->insert( true ) ) {
3429 $this->mGroupMemberships
[$group] = $ugm;
3431 // Refresh the groups caches, and clear the rights cache so it will be
3432 // refreshed on the next call to $this->getRights().
3433 $this->getEffectiveGroups( true );
3434 $this->mRights
= null;
3436 $this->invalidateCache();
3442 * Remove the user from the given group.
3443 * This takes immediate effect.
3444 * @param string $group Name of the group to remove
3447 public function removeGroup( $group ) {
3450 if ( !Hooks
::run( 'UserRemoveGroup', [ $this, &$group ] ) ) {
3454 $ugm = UserGroupMembership
::getMembership( $this->mId
, $group );
3455 // delete the membership entry
3456 if ( !$ugm ||
!$ugm->delete() ) {
3460 $this->loadGroups();
3461 unset( $this->mGroupMemberships
[$group] );
3463 // Refresh the groups caches, and clear the rights cache so it will be
3464 // refreshed on the next call to $this->getRights().
3465 $this->getEffectiveGroups( true );
3466 $this->mRights
= null;
3468 $this->invalidateCache();
3474 * Get whether the user is logged in
3477 public function isLoggedIn() {
3478 return $this->getId() != 0;
3482 * Get whether the user is anonymous
3485 public function isAnon() {
3486 return !$this->isLoggedIn();
3490 * @return bool Whether this user is flagged as being a bot role account
3493 public function isBot() {
3494 if ( in_array( 'bot', $this->getGroups() ) && $this->isAllowed( 'bot' ) ) {
3499 Hooks
::run( "UserIsBot", [ $this, &$isBot ] );
3505 * Check if user is allowed to access a feature / make an action
3507 * @param string ... Permissions to test
3508 * @return bool True if user is allowed to perform *any* of the given actions
3510 public function isAllowedAny() {
3511 $permissions = func_get_args();
3512 foreach ( $permissions as $permission ) {
3513 if ( $this->isAllowed( $permission ) ) {
3522 * @param string ... Permissions to test
3523 * @return bool True if the user is allowed to perform *all* of the given actions
3525 public function isAllowedAll() {
3526 $permissions = func_get_args();
3527 foreach ( $permissions as $permission ) {
3528 if ( !$this->isAllowed( $permission ) ) {
3536 * Internal mechanics of testing a permission
3537 * @param string $action
3540 public function isAllowed( $action = '' ) {
3541 if ( $action === '' ) {
3542 return true; // In the spirit of DWIM
3544 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3545 // by misconfiguration: 0 == 'foo'
3546 return in_array( $action, $this->getRights(), true );
3550 * Check whether to enable recent changes patrol features for this user
3551 * @return bool True or false
3553 public function useRCPatrol() {
3554 global $wgUseRCPatrol;
3555 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3559 * Check whether to enable new pages patrol features for this user
3560 * @return bool True or false
3562 public function useNPPatrol() {
3563 global $wgUseRCPatrol, $wgUseNPPatrol;
3565 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3566 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3571 * Check whether to enable new files patrol features for this user
3572 * @return bool True or false
3574 public function useFilePatrol() {
3575 global $wgUseRCPatrol, $wgUseFilePatrol;
3577 ( $wgUseRCPatrol ||
$wgUseFilePatrol )
3578 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3583 * Get the WebRequest object to use with this object
3585 * @return WebRequest
3587 public function getRequest() {
3588 if ( $this->mRequest
) {
3589 return $this->mRequest
;
3597 * Check the watched status of an article.
3598 * @since 1.22 $checkRights parameter added
3599 * @param Title $title Title of the article to look at
3600 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3601 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3604 public function isWatched( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3605 if ( $title->isWatchable() && ( !$checkRights ||
$this->isAllowed( 'viewmywatchlist' ) ) ) {
3606 return MediaWikiServices
::getInstance()->getWatchedItemStore()->isWatched( $this, $title );
3613 * @since 1.22 $checkRights parameter added
3614 * @param Title $title Title of the article to look at
3615 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3616 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3618 public function addWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3619 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3620 MediaWikiServices
::getInstance()->getWatchedItemStore()->addWatchBatchForUser(
3622 [ $title->getSubjectPage(), $title->getTalkPage() ]
3625 $this->invalidateCache();
3629 * Stop watching an article.
3630 * @since 1.22 $checkRights parameter added
3631 * @param Title $title Title of the article to look at
3632 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3633 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3635 public function removeWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3636 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3637 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
3638 $store->removeWatch( $this, $title->getSubjectPage() );
3639 $store->removeWatch( $this, $title->getTalkPage() );
3641 $this->invalidateCache();
3645 * Clear the user's notification timestamp for the given title.
3646 * If e-notif e-mails are on, they will receive notification mails on
3647 * the next change of the page if it's watched etc.
3648 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3649 * @param Title $title Title of the article to look at
3650 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3652 public function clearNotification( &$title, $oldid = 0 ) {
3653 global $wgUseEnotif, $wgShowUpdatedMarker;
3655 // Do nothing if the database is locked to writes
3656 if ( wfReadOnly() ) {
3660 // Do nothing if not allowed to edit the watchlist
3661 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3665 // If we're working on user's talk page, we should update the talk page message indicator
3666 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3667 // Avoid PHP 7.1 warning of passing $this by reference
3669 if ( !Hooks
::run( 'UserClearNewTalkNotification', [ &$user, $oldid ] ) ) {
3673 // Try to update the DB post-send and only if needed...
3674 DeferredUpdates
::addCallableUpdate( function() use ( $title, $oldid ) {
3675 if ( !$this->getNewtalk() ) {
3676 return; // no notifications to clear
3679 // Delete the last notifications (they stack up)
3680 $this->setNewtalk( false );
3682 // If there is a new, unseen, revision, use its timestamp
3684 ?
$title->getNextRevisionID( $oldid, Title
::GAID_FOR_UPDATE
)
3687 $this->setNewtalk( true, Revision
::newFromId( $nextid ) );
3692 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3696 if ( $this->isAnon() ) {
3697 // Nothing else to do...
3701 // Only update the timestamp if the page is being watched.
3702 // The query to find out if it is watched is cached both in memcached and per-invocation,
3703 // and when it does have to be executed, it can be on a replica DB
3704 // If this is the user's newtalk page, we always update the timestamp
3706 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3710 MediaWikiServices
::getInstance()->getWatchedItemStore()
3711 ->resetNotificationTimestamp( $this, $title, $force, $oldid );
3715 * Resets all of the given user's page-change notification timestamps.
3716 * If e-notif e-mails are on, they will receive notification mails on
3717 * the next change of any watched page.
3718 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3720 public function clearAllNotifications() {
3721 global $wgUseEnotif, $wgShowUpdatedMarker;
3722 // Do nothing if not allowed to edit the watchlist
3723 if ( wfReadOnly() ||
!$this->isAllowed( 'editmywatchlist' ) ) {
3727 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3728 $this->setNewtalk( false );
3732 $id = $this->getId();
3737 $dbw = wfGetDB( DB_MASTER
);
3738 $asOfTimes = array_unique( $dbw->selectFieldValues(
3740 'wl_notificationtimestamp',
3741 [ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ],
3743 [ 'ORDER BY' => 'wl_notificationtimestamp DESC', 'LIMIT' => 500 ]
3745 if ( !$asOfTimes ) {
3748 // Immediately update the most recent touched rows, which hopefully covers what
3749 // the user sees on the watchlist page before pressing "mark all pages visited"....
3752 [ 'wl_notificationtimestamp' => null ],
3753 [ 'wl_user' => $id, 'wl_notificationtimestamp' => $asOfTimes ],
3756 // ...and finish the older ones in a post-send update with lag checks...
3757 DeferredUpdates
::addUpdate( new AutoCommitUpdate(
3760 function () use ( $dbw, $id ) {
3761 global $wgUpdateRowsPerQuery;
3763 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
3764 $ticket = $lbFactory->getEmptyTransactionTicket( __METHOD__
);
3765 $asOfTimes = array_unique( $dbw->selectFieldValues(
3767 'wl_notificationtimestamp',
3768 [ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ],
3771 foreach ( array_chunk( $asOfTimes, $wgUpdateRowsPerQuery ) as $asOfTimeBatch ) {
3774 [ 'wl_notificationtimestamp' => null ],
3775 [ 'wl_user' => $id, 'wl_notificationtimestamp' => $asOfTimeBatch ],
3778 $lbFactory->commitAndWaitForReplication( __METHOD__
, $ticket );
3782 // We also need to clear here the "you have new message" notification for the own
3783 // user_talk page; it's cleared one page view later in WikiPage::doViewUpdates().
3787 * Compute experienced level based on edit count and registration date.
3789 * @return string 'newcomer', 'learner', or 'experienced'
3791 public function getExperienceLevel() {
3792 global $wgLearnerEdits,
3793 $wgExperiencedUserEdits,
3794 $wgLearnerMemberSince,
3795 $wgExperiencedUserMemberSince;
3797 if ( $this->isAnon() ) {
3801 $editCount = $this->getEditCount();
3802 $registration = $this->getRegistration();
3804 $learnerRegistration = wfTimestamp( TS_MW
, $now - $wgLearnerMemberSince * 86400 );
3805 $experiencedRegistration = wfTimestamp( TS_MW
, $now - $wgExperiencedUserMemberSince * 86400 );
3808 $editCount < $wgLearnerEdits ||
3809 $registration > $learnerRegistration
3813 $editCount > $wgExperiencedUserEdits &&
3814 $registration <= $experiencedRegistration
3816 return 'experienced';
3823 * Set a cookie on the user's client. Wrapper for
3824 * WebResponse::setCookie
3825 * @deprecated since 1.27
3826 * @param string $name Name of the cookie to set
3827 * @param string $value Value to set
3828 * @param int $exp Expiration time, as a UNIX time value;
3829 * if 0 or not specified, use the default $wgCookieExpiration
3830 * @param bool $secure
3831 * true: Force setting the secure attribute when setting the cookie
3832 * false: Force NOT setting the secure attribute when setting the cookie
3833 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3834 * @param array $params Array of options sent passed to WebResponse::setcookie()
3835 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3838 protected function setCookie(
3839 $name, $value, $exp = 0, $secure = null, $params = [], $request = null
3841 wfDeprecated( __METHOD__
, '1.27' );
3842 if ( $request === null ) {
3843 $request = $this->getRequest();
3845 $params['secure'] = $secure;
3846 $request->response()->setCookie( $name, $value, $exp, $params );
3850 * Clear a cookie on the user's client
3851 * @deprecated since 1.27
3852 * @param string $name Name of the cookie to clear
3853 * @param bool $secure
3854 * true: Force setting the secure attribute when setting the cookie
3855 * false: Force NOT setting the secure attribute when setting the cookie
3856 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3857 * @param array $params Array of options sent passed to WebResponse::setcookie()
3859 protected function clearCookie( $name, $secure = null, $params = [] ) {
3860 wfDeprecated( __METHOD__
, '1.27' );
3861 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3865 * Set an extended login cookie on the user's client. The expiry of the cookie
3866 * is controlled by the $wgExtendedLoginCookieExpiration configuration
3869 * @see User::setCookie
3871 * @deprecated since 1.27
3872 * @param string $name Name of the cookie to set
3873 * @param string $value Value to set
3874 * @param bool $secure
3875 * true: Force setting the secure attribute when setting the cookie
3876 * false: Force NOT setting the secure attribute when setting the cookie
3877 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3879 protected function setExtendedLoginCookie( $name, $value, $secure ) {
3880 global $wgExtendedLoginCookieExpiration, $wgCookieExpiration;
3882 wfDeprecated( __METHOD__
, '1.27' );
3885 $exp +
= $wgExtendedLoginCookieExpiration !== null
3886 ?
$wgExtendedLoginCookieExpiration
3887 : $wgCookieExpiration;
3889 $this->setCookie( $name, $value, $exp, $secure );
3893 * Persist this user's session (e.g. set cookies)
3895 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3897 * @param bool $secure Whether to force secure/insecure cookies or use default
3898 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3900 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3902 if ( 0 == $this->mId
) {
3906 $session = $this->getRequest()->getSession();
3907 if ( $request && $session->getRequest() !== $request ) {
3908 $session = $session->sessionWithRequest( $request );
3910 $delay = $session->delaySave();
3912 if ( !$session->getUser()->equals( $this ) ) {
3913 if ( !$session->canSetUser() ) {
3914 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3915 ->warning( __METHOD__
.
3916 ": Cannot save user \"$this\" to a user \"{$session->getUser()}\"'s immutable session"
3920 $session->setUser( $this );
3923 $session->setRememberUser( $rememberMe );
3924 if ( $secure !== null ) {
3925 $session->setForceHTTPS( $secure );
3928 $session->persist();
3930 ScopedCallback
::consume( $delay );
3934 * Log this user out.
3936 public function logout() {
3937 // Avoid PHP 7.1 warning of passing $this by reference
3939 if ( Hooks
::run( 'UserLogout', [ &$user ] ) ) {
3945 * Clear the user's session, and reset the instance cache.
3948 public function doLogout() {
3949 $session = $this->getRequest()->getSession();
3950 if ( !$session->canSetUser() ) {
3951 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3952 ->warning( __METHOD__
. ": Cannot log out of an immutable session" );
3953 $error = 'immutable';
3954 } elseif ( !$session->getUser()->equals( $this ) ) {
3955 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3956 ->warning( __METHOD__
.
3957 ": Cannot log user \"$this\" out of a user \"{$session->getUser()}\"'s session"
3959 // But we still may as well make this user object anon
3960 $this->clearInstanceCache( 'defaults' );
3961 $error = 'wronguser';
3963 $this->clearInstanceCache( 'defaults' );
3964 $delay = $session->delaySave();
3965 $session->unpersist(); // Clear cookies (T127436)
3966 $session->setLoggedOutTimestamp( time() );
3967 $session->setUser( new User
);
3968 $session->set( 'wsUserID', 0 ); // Other code expects this
3969 $session->resetAllTokens();
3970 ScopedCallback
::consume( $delay );
3973 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authevents' )->info( 'Logout', [
3974 'event' => 'logout',
3975 'successful' => $error === false,
3976 'status' => $error ?
: 'success',
3981 * Save this user's settings into the database.
3982 * @todo Only rarely do all these fields need to be set!
3984 public function saveSettings() {
3985 if ( wfReadOnly() ) {
3986 // @TODO: caller should deal with this instead!
3987 // This should really just be an exception.
3988 MWExceptionHandler
::logException( new DBExpectedError(
3990 "Could not update user with ID '{$this->mId}'; DB is read-only."
3996 if ( 0 == $this->mId
) {
4000 // Get a new user_touched that is higher than the old one.
4001 // This will be used for a CAS check as a last-resort safety
4002 // check against race conditions and replica DB lag.
4003 $newTouched = $this->newTouchedTimestamp();
4005 $dbw = wfGetDB( DB_MASTER
);
4006 $dbw->update( 'user',
4008 'user_name' => $this->mName
,
4009 'user_real_name' => $this->mRealName
,
4010 'user_email' => $this->mEmail
,
4011 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
4012 'user_touched' => $dbw->timestamp( $newTouched ),
4013 'user_token' => strval( $this->mToken
),
4014 'user_email_token' => $this->mEmailToken
,
4015 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
4016 ], $this->makeUpdateConditions( $dbw, [ /* WHERE */
4017 'user_id' => $this->mId
,
4021 if ( !$dbw->affectedRows() ) {
4022 // Maybe the problem was a missed cache update; clear it to be safe
4023 $this->clearSharedCache( 'refresh' );
4024 // User was changed in the meantime or loaded with stale data
4025 $from = ( $this->queryFlagsUsed
& self
::READ_LATEST
) ?
'master' : 'replica';
4026 throw new MWException(
4027 "CAS update failed on user_touched for user ID '{$this->mId}' (read from $from);" .
4028 " the version of the user to be saved is older than the current version."
4032 $this->mTouched
= $newTouched;
4033 $this->saveOptions();
4035 Hooks
::run( 'UserSaveSettings', [ $this ] );
4036 $this->clearSharedCache();
4037 $this->getUserPage()->invalidateCache();
4041 * If only this user's username is known, and it exists, return the user ID.
4043 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
4046 public function idForName( $flags = 0 ) {
4047 $s = trim( $this->getName() );
4052 $db = ( ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
)
4053 ?
wfGetDB( DB_MASTER
)
4054 : wfGetDB( DB_REPLICA
);
4056 $options = ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
)
4057 ?
[ 'LOCK IN SHARE MODE' ]
4060 $id = $db->selectField( 'user',
4061 'user_id', [ 'user_name' => $s ], __METHOD__
, $options );
4067 * Add a user to the database, return the user object
4069 * @param string $name Username to add
4070 * @param array $params Array of Strings Non-default parameters to save to
4071 * the database as user_* fields:
4072 * - email: The user's email address.
4073 * - email_authenticated: The email authentication timestamp.
4074 * - real_name: The user's real name.
4075 * - options: An associative array of non-default options.
4076 * - token: Random authentication token. Do not set.
4077 * - registration: Registration timestamp. Do not set.
4079 * @return User|null User object, or null if the username already exists.
4081 public static function createNew( $name, $params = [] ) {
4082 foreach ( [ 'password', 'newpassword', 'newpass_time', 'password_expires' ] as $field ) {
4083 if ( isset( $params[$field] ) ) {
4084 wfDeprecated( __METHOD__
. " with param '$field'", '1.27' );
4085 unset( $params[$field] );
4091 $user->setToken(); // init token
4092 if ( isset( $params['options'] ) ) {
4093 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
4094 unset( $params['options'] );
4096 $dbw = wfGetDB( DB_MASTER
);
4097 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
4099 $noPass = PasswordFactory
::newInvalidPassword()->toString();
4102 'user_id' => $seqVal,
4103 'user_name' => $name,
4104 'user_password' => $noPass,
4105 'user_newpassword' => $noPass,
4106 'user_email' => $user->mEmail
,
4107 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
4108 'user_real_name' => $user->mRealName
,
4109 'user_token' => strval( $user->mToken
),
4110 'user_registration' => $dbw->timestamp( $user->mRegistration
),
4111 'user_editcount' => 0,
4112 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
4114 foreach ( $params as $name => $value ) {
4115 $fields["user_$name"] = $value;
4117 $dbw->insert( 'user', $fields, __METHOD__
, [ 'IGNORE' ] );
4118 if ( $dbw->affectedRows() ) {
4119 $newUser = User
::newFromId( $dbw->insertId() );
4127 * Add this existing user object to the database. If the user already
4128 * exists, a fatal status object is returned, and the user object is
4129 * initialised with the data from the database.
4131 * Previously, this function generated a DB error due to a key conflict
4132 * if the user already existed. Many extension callers use this function
4133 * in code along the lines of:
4135 * $user = User::newFromName( $name );
4136 * if ( !$user->isLoggedIn() ) {
4137 * $user->addToDatabase();
4139 * // do something with $user...
4141 * However, this was vulnerable to a race condition (T18020). By
4142 * initialising the user object if the user exists, we aim to support this
4143 * calling sequence as far as possible.
4145 * Note that if the user exists, this function will acquire a write lock,
4146 * so it is still advisable to make the call conditional on isLoggedIn(),
4147 * and to commit the transaction after calling.
4149 * @throws MWException
4152 public function addToDatabase() {
4154 if ( !$this->mToken
) {
4155 $this->setToken(); // init token
4158 $this->mTouched
= $this->newTouchedTimestamp();
4160 $noPass = PasswordFactory
::newInvalidPassword()->toString();
4162 $dbw = wfGetDB( DB_MASTER
);
4163 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
4164 $dbw->insert( 'user',
4166 'user_id' => $seqVal,
4167 'user_name' => $this->mName
,
4168 'user_password' => $noPass,
4169 'user_newpassword' => $noPass,
4170 'user_email' => $this->mEmail
,
4171 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
4172 'user_real_name' => $this->mRealName
,
4173 'user_token' => strval( $this->mToken
),
4174 'user_registration' => $dbw->timestamp( $this->mRegistration
),
4175 'user_editcount' => 0,
4176 'user_touched' => $dbw->timestamp( $this->mTouched
),
4180 if ( !$dbw->affectedRows() ) {
4181 // Use locking reads to bypass any REPEATABLE-READ snapshot.
4182 $this->mId
= $dbw->selectField(
4185 [ 'user_name' => $this->mName
],
4187 [ 'LOCK IN SHARE MODE' ]
4191 if ( $this->loadFromDatabase( self
::READ_LOCKING
) ) {
4196 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
4197 "to insert user '{$this->mName}' row, but it was not present in select!" );
4199 return Status
::newFatal( 'userexists' );
4201 $this->mId
= $dbw->insertId();
4202 self
::$idCacheByName[$this->mName
] = $this->mId
;
4204 // Clear instance cache other than user table data, which is already accurate
4205 $this->clearInstanceCache();
4207 $this->saveOptions();
4208 return Status
::newGood();
4212 * If this user is logged-in and blocked,
4213 * block any IP address they've successfully logged in from.
4214 * @return bool A block was spread
4216 public function spreadAnyEditBlock() {
4217 if ( $this->isLoggedIn() && $this->isBlocked() ) {
4218 return $this->spreadBlock();
4225 * If this (non-anonymous) user is blocked,
4226 * block the IP address they've successfully logged in from.
4227 * @return bool A block was spread
4229 protected function spreadBlock() {
4230 wfDebug( __METHOD__
. "()\n" );
4232 if ( $this->mId
== 0 ) {
4236 $userblock = Block
::newFromTarget( $this->getName() );
4237 if ( !$userblock ) {
4241 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
4245 * Get whether the user is explicitly blocked from account creation.
4246 * @return bool|Block
4248 public function isBlockedFromCreateAccount() {
4249 $this->getBlockedStatus();
4250 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
4251 return $this->mBlock
;
4254 # T15611: if the IP address the user is trying to create an account from is
4255 # blocked with createaccount disabled, prevent new account creation there even
4256 # when the user is logged in
4257 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
4258 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
4260 return $this->mBlockedFromCreateAccount
instanceof Block
4261 && $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
4262 ?
$this->mBlockedFromCreateAccount
4267 * Get whether the user is blocked from using Special:Emailuser.
4270 public function isBlockedFromEmailuser() {
4271 $this->getBlockedStatus();
4272 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
4276 * Get whether the user is allowed to create an account.
4279 public function isAllowedToCreateAccount() {
4280 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
4284 * Get this user's personal page title.
4286 * @return Title User's personal page title
4288 public function getUserPage() {
4289 return Title
::makeTitle( NS_USER
, $this->getName() );
4293 * Get this user's talk page title.
4295 * @return Title User's talk page title
4297 public function getTalkPage() {
4298 $title = $this->getUserPage();
4299 return $title->getTalkPage();
4303 * Determine whether the user is a newbie. Newbies are either
4304 * anonymous IPs, or the most recently created accounts.
4307 public function isNewbie() {
4308 return !$this->isAllowed( 'autoconfirmed' );
4312 * Check to see if the given clear-text password is one of the accepted passwords
4313 * @deprecated since 1.27, use AuthManager instead
4314 * @param string $password User password
4315 * @return bool True if the given password is correct, otherwise False
4317 public function checkPassword( $password ) {
4318 $manager = AuthManager
::singleton();
4319 $reqs = AuthenticationRequest
::loadRequestsFromSubmission(
4320 $manager->getAuthenticationRequests( AuthManager
::ACTION_LOGIN
),
4322 'username' => $this->getName(),
4323 'password' => $password,
4326 $res = AuthManager
::singleton()->beginAuthentication( $reqs, 'null:' );
4327 switch ( $res->status
) {
4328 case AuthenticationResponse
::PASS
:
4330 case AuthenticationResponse
::FAIL
:
4331 // Hope it's not a PreAuthenticationProvider that failed...
4332 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
4333 ->info( __METHOD__
. ': Authentication failed: ' . $res->message
->plain() );
4336 throw new BadMethodCallException(
4337 'AuthManager returned a response unsupported by ' . __METHOD__
4343 * Check if the given clear-text password matches the temporary password
4344 * sent by e-mail for password reset operations.
4346 * @deprecated since 1.27, use AuthManager instead
4347 * @param string $plaintext
4348 * @return bool True if matches, false otherwise
4350 public function checkTemporaryPassword( $plaintext ) {
4351 // Can't check the temporary password individually.
4352 return $this->checkPassword( $plaintext );
4356 * Initialize (if necessary) and return a session token value
4357 * which can be used in edit forms to show that the user's
4358 * login credentials aren't being hijacked with a foreign form
4362 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4363 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4364 * @return MediaWiki\Session\Token The new edit token
4366 public function getEditTokenObject( $salt = '', $request = null ) {
4367 if ( $this->isAnon() ) {
4368 return new LoggedOutEditToken();
4372 $request = $this->getRequest();
4374 return $request->getSession()->getToken( $salt );
4378 * Initialize (if necessary) and return a session token value
4379 * which can be used in edit forms to show that the user's
4380 * login credentials aren't being hijacked with a foreign form
4383 * The $salt for 'edit' and 'csrf' tokens is the default (empty string).
4386 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4387 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4388 * @return string The new edit token
4390 public function getEditToken( $salt = '', $request = null ) {
4391 return $this->getEditTokenObject( $salt, $request )->toString();
4395 * Get the embedded timestamp from a token.
4396 * @deprecated since 1.27, use \MediaWiki\Session\Token::getTimestamp instead.
4397 * @param string $val Input token
4400 public static function getEditTokenTimestamp( $val ) {
4401 wfDeprecated( __METHOD__
, '1.27' );
4402 return MediaWiki\Session\Token
::getTimestamp( $val );
4406 * Check given value against the token value stored in the session.
4407 * A match should confirm that the form was submitted from the
4408 * user's own login session, not a form submission from a third-party
4411 * @param string $val Input value to compare
4412 * @param string $salt Optional function-specific data for hashing
4413 * @param WebRequest|null $request Object to use or null to use $wgRequest
4414 * @param int $maxage Fail tokens older than this, in seconds
4415 * @return bool Whether the token matches
4417 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4418 return $this->getEditTokenObject( $salt, $request )->match( $val, $maxage );
4422 * Check given value against the token value stored in the session,
4423 * ignoring the suffix.
4425 * @param string $val Input value to compare
4426 * @param string $salt Optional function-specific data for hashing
4427 * @param WebRequest|null $request Object to use or null to use $wgRequest
4428 * @param int $maxage Fail tokens older than this, in seconds
4429 * @return bool Whether the token matches
4431 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4432 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . Token
::SUFFIX
;
4433 return $this->matchEditToken( $val, $salt, $request, $maxage );
4437 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4438 * mail to the user's given address.
4440 * @param string $type Message to send, either "created", "changed" or "set"
4443 public function sendConfirmationMail( $type = 'created' ) {
4445 $expiration = null; // gets passed-by-ref and defined in next line.
4446 $token = $this->confirmationToken( $expiration );
4447 $url = $this->confirmationTokenUrl( $token );
4448 $invalidateURL = $this->invalidationTokenUrl( $token );
4449 $this->saveSettings();
4451 if ( $type == 'created' ||
$type === false ) {
4452 $message = 'confirmemail_body';
4453 } elseif ( $type === true ) {
4454 $message = 'confirmemail_body_changed';
4456 // Messages: confirmemail_body_changed, confirmemail_body_set
4457 $message = 'confirmemail_body_' . $type;
4460 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4461 wfMessage( $message,
4462 $this->getRequest()->getIP(),
4465 $wgLang->userTimeAndDate( $expiration, $this ),
4467 $wgLang->userDate( $expiration, $this ),
4468 $wgLang->userTime( $expiration, $this ) )->text() );
4472 * Send an e-mail to this user's account. Does not check for
4473 * confirmed status or validity.
4475 * @param string $subject Message subject
4476 * @param string $body Message body
4477 * @param User|null $from Optional sending user; if unspecified, default
4478 * $wgPasswordSender will be used.
4479 * @param string $replyto Reply-To address
4482 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4483 global $wgPasswordSender;
4485 if ( $from instanceof User
) {
4486 $sender = MailAddress
::newFromUser( $from );
4488 $sender = new MailAddress( $wgPasswordSender,
4489 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4491 $to = MailAddress
::newFromUser( $this );
4493 return UserMailer
::send( $to, $sender, $subject, $body, [
4494 'replyTo' => $replyto,
4499 * Generate, store, and return a new e-mail confirmation code.
4500 * A hash (unsalted, since it's used as a key) is stored.
4502 * @note Call saveSettings() after calling this function to commit
4503 * this change to the database.
4505 * @param string &$expiration Accepts the expiration time
4506 * @return string New token
4508 protected function confirmationToken( &$expiration ) {
4509 global $wgUserEmailConfirmationTokenExpiry;
4511 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4512 $expiration = wfTimestamp( TS_MW
, $expires );
4514 $token = MWCryptRand
::generateHex( 32 );
4515 $hash = md5( $token );
4516 $this->mEmailToken
= $hash;
4517 $this->mEmailTokenExpires
= $expiration;
4522 * Return a URL the user can use to confirm their email address.
4523 * @param string $token Accepts the email confirmation token
4524 * @return string New token URL
4526 protected function confirmationTokenUrl( $token ) {
4527 return $this->getTokenUrl( 'ConfirmEmail', $token );
4531 * Return a URL the user can use to invalidate their email address.
4532 * @param string $token Accepts the email confirmation token
4533 * @return string New token URL
4535 protected function invalidationTokenUrl( $token ) {
4536 return $this->getTokenUrl( 'InvalidateEmail', $token );
4540 * Internal function to format the e-mail validation/invalidation URLs.
4541 * This uses a quickie hack to use the
4542 * hardcoded English names of the Special: pages, for ASCII safety.
4544 * @note Since these URLs get dropped directly into emails, using the
4545 * short English names avoids insanely long URL-encoded links, which
4546 * also sometimes can get corrupted in some browsers/mailers
4547 * (T8957 with Gmail and Internet Explorer).
4549 * @param string $page Special page
4550 * @param string $token Token
4551 * @return string Formatted URL
4553 protected function getTokenUrl( $page, $token ) {
4554 // Hack to bypass localization of 'Special:'
4555 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4556 return $title->getCanonicalURL();
4560 * Mark the e-mail address confirmed.
4562 * @note Call saveSettings() after calling this function to commit the change.
4566 public function confirmEmail() {
4567 // Check if it's already confirmed, so we don't touch the database
4568 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4569 if ( !$this->isEmailConfirmed() ) {
4570 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4571 Hooks
::run( 'ConfirmEmailComplete', [ $this ] );
4577 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4578 * address if it was already confirmed.
4580 * @note Call saveSettings() after calling this function to commit the change.
4581 * @return bool Returns true
4583 public function invalidateEmail() {
4585 $this->mEmailToken
= null;
4586 $this->mEmailTokenExpires
= null;
4587 $this->setEmailAuthenticationTimestamp( null );
4589 Hooks
::run( 'InvalidateEmailComplete', [ $this ] );
4594 * Set the e-mail authentication timestamp.
4595 * @param string $timestamp TS_MW timestamp
4597 public function setEmailAuthenticationTimestamp( $timestamp ) {
4599 $this->mEmailAuthenticated
= $timestamp;
4600 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
4604 * Is this user allowed to send e-mails within limits of current
4605 * site configuration?
4608 public function canSendEmail() {
4609 global $wgEnableEmail, $wgEnableUserEmail;
4610 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4613 $canSend = $this->isEmailConfirmed();
4614 // Avoid PHP 7.1 warning of passing $this by reference
4616 Hooks
::run( 'UserCanSendEmail', [ &$user, &$canSend ] );
4621 * Is this user allowed to receive e-mails within limits of current
4622 * site configuration?
4625 public function canReceiveEmail() {
4626 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4630 * Is this user's e-mail address valid-looking and confirmed within
4631 * limits of the current site configuration?
4633 * @note If $wgEmailAuthentication is on, this may require the user to have
4634 * confirmed their address by returning a code or using a password
4635 * sent to the address from the wiki.
4639 public function isEmailConfirmed() {
4640 global $wgEmailAuthentication;
4642 // Avoid PHP 7.1 warning of passing $this by reference
4645 if ( Hooks
::run( 'EmailConfirmed', [ &$user, &$confirmed ] ) ) {
4646 if ( $this->isAnon() ) {
4649 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4652 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4662 * Check whether there is an outstanding request for e-mail confirmation.
4665 public function isEmailConfirmationPending() {
4666 global $wgEmailAuthentication;
4667 return $wgEmailAuthentication &&
4668 !$this->isEmailConfirmed() &&
4669 $this->mEmailToken
&&
4670 $this->mEmailTokenExpires
> wfTimestamp();
4674 * Get the timestamp of account creation.
4676 * @return string|bool|null Timestamp of account creation, false for
4677 * non-existent/anonymous user accounts, or null if existing account
4678 * but information is not in database.
4680 public function getRegistration() {
4681 if ( $this->isAnon() ) {
4685 return $this->mRegistration
;
4689 * Get the timestamp of the first edit
4691 * @return string|bool Timestamp of first edit, or false for
4692 * non-existent/anonymous user accounts.
4694 public function getFirstEditTimestamp() {
4695 if ( $this->getId() == 0 ) {
4696 return false; // anons
4698 $dbr = wfGetDB( DB_REPLICA
);
4699 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4700 [ 'rev_user' => $this->getId() ],
4702 [ 'ORDER BY' => 'rev_timestamp ASC' ]
4705 return false; // no edits
4707 return wfTimestamp( TS_MW
, $time );
4711 * Get the permissions associated with a given list of groups
4713 * @param array $groups Array of Strings List of internal group names
4714 * @return array Array of Strings List of permission key names for given groups combined
4716 public static function getGroupPermissions( $groups ) {
4717 global $wgGroupPermissions, $wgRevokePermissions;
4719 // grant every granted permission first
4720 foreach ( $groups as $group ) {
4721 if ( isset( $wgGroupPermissions[$group] ) ) {
4722 $rights = array_merge( $rights,
4723 // array_filter removes empty items
4724 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4727 // now revoke the revoked permissions
4728 foreach ( $groups as $group ) {
4729 if ( isset( $wgRevokePermissions[$group] ) ) {
4730 $rights = array_diff( $rights,
4731 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4734 return array_unique( $rights );
4738 * Get all the groups who have a given permission
4740 * @param string $role Role to check
4741 * @return array Array of Strings List of internal group names with the given permission
4743 public static function getGroupsWithPermission( $role ) {
4744 global $wgGroupPermissions;
4745 $allowedGroups = [];
4746 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4747 if ( self
::groupHasPermission( $group, $role ) ) {
4748 $allowedGroups[] = $group;
4751 return $allowedGroups;
4755 * Check, if the given group has the given permission
4757 * If you're wanting to check whether all users have a permission, use
4758 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4762 * @param string $group Group to check
4763 * @param string $role Role to check
4766 public static function groupHasPermission( $group, $role ) {
4767 global $wgGroupPermissions, $wgRevokePermissions;
4768 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4769 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4773 * Check if all users may be assumed to have the given permission
4775 * We generally assume so if the right is granted to '*' and isn't revoked
4776 * on any group. It doesn't attempt to take grants or other extension
4777 * limitations on rights into account in the general case, though, as that
4778 * would require it to always return false and defeat the purpose.
4779 * Specifically, session-based rights restrictions (such as OAuth or bot
4780 * passwords) are applied based on the current session.
4783 * @param string $right Right to check
4786 public static function isEveryoneAllowed( $right ) {
4787 global $wgGroupPermissions, $wgRevokePermissions;
4790 // Use the cached results, except in unit tests which rely on
4791 // being able change the permission mid-request
4792 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4793 return $cache[$right];
4796 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4797 $cache[$right] = false;
4801 // If it's revoked anywhere, then everyone doesn't have it
4802 foreach ( $wgRevokePermissions as $rights ) {
4803 if ( isset( $rights[$right] ) && $rights[$right] ) {
4804 $cache[$right] = false;
4809 // Remove any rights that aren't allowed to the global-session user,
4810 // unless there are no sessions for this endpoint.
4811 if ( !defined( 'MW_NO_SESSION' ) ) {
4812 $allowedRights = SessionManager
::getGlobalSession()->getAllowedUserRights();
4813 if ( $allowedRights !== null && !in_array( $right, $allowedRights, true ) ) {
4814 $cache[$right] = false;
4819 // Allow extensions to say false
4820 if ( !Hooks
::run( 'UserIsEveryoneAllowed', [ $right ] ) ) {
4821 $cache[$right] = false;
4825 $cache[$right] = true;
4830 * Get the localized descriptive name for a group, if it exists
4831 * @deprecated since 1.29 Use UserGroupMembership::getGroupName instead
4833 * @param string $group Internal group name
4834 * @return string Localized descriptive group name
4836 public static function getGroupName( $group ) {
4837 wfDeprecated( __METHOD__
, '1.29' );
4838 return UserGroupMembership
::getGroupName( $group );
4842 * Get the localized descriptive name for a member of a group, if it exists
4843 * @deprecated since 1.29 Use UserGroupMembership::getGroupMemberName instead
4845 * @param string $group Internal group name
4846 * @param string $username Username for gender (since 1.19)
4847 * @return string Localized name for group member
4849 public static function getGroupMember( $group, $username = '#' ) {
4850 wfDeprecated( __METHOD__
, '1.29' );
4851 return UserGroupMembership
::getGroupMemberName( $group, $username );
4855 * Return the set of defined explicit groups.
4856 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4857 * are not included, as they are defined automatically, not in the database.
4858 * @return array Array of internal group names
4860 public static function getAllGroups() {
4861 global $wgGroupPermissions, $wgRevokePermissions;
4863 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4864 self
::getImplicitGroups()
4869 * Get a list of all available permissions.
4870 * @return string[] Array of permission names
4872 public static function getAllRights() {
4873 if ( self
::$mAllRights === false ) {
4874 global $wgAvailableRights;
4875 if ( count( $wgAvailableRights ) ) {
4876 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
4878 self
::$mAllRights = self
::$mCoreRights;
4880 Hooks
::run( 'UserGetAllRights', [ &self
::$mAllRights ] );
4882 return self
::$mAllRights;
4886 * Get a list of implicit groups
4887 * @return array Array of Strings Array of internal group names
4889 public static function getImplicitGroups() {
4890 global $wgImplicitGroups;
4892 $groups = $wgImplicitGroups;
4893 # Deprecated, use $wgImplicitGroups instead
4894 Hooks
::run( 'UserGetImplicitGroups', [ &$groups ], '1.25' );
4900 * Get the title of a page describing a particular group
4901 * @deprecated since 1.29 Use UserGroupMembership::getGroupPage instead
4903 * @param string $group Internal group name
4904 * @return Title|bool Title of the page if it exists, false otherwise
4906 public static function getGroupPage( $group ) {
4907 wfDeprecated( __METHOD__
, '1.29' );
4908 return UserGroupMembership
::getGroupPage( $group );
4912 * Create a link to the group in HTML, if available;
4913 * else return the group name.
4914 * @deprecated since 1.29 Use UserGroupMembership::getLink instead, or
4915 * make the link yourself if you need custom text
4917 * @param string $group Internal name of the group
4918 * @param string $text The text of the link
4919 * @return string HTML link to the group
4921 public static function makeGroupLinkHTML( $group, $text = '' ) {
4922 wfDeprecated( __METHOD__
, '1.29' );
4924 if ( $text == '' ) {
4925 $text = UserGroupMembership
::getGroupName( $group );
4927 $title = UserGroupMembership
::getGroupPage( $group );
4929 return Linker
::link( $title, htmlspecialchars( $text ) );
4931 return htmlspecialchars( $text );
4936 * Create a link to the group in Wikitext, if available;
4937 * else return the group name.
4938 * @deprecated since 1.29 Use UserGroupMembership::getLink instead, or
4939 * make the link yourself if you need custom text
4941 * @param string $group Internal name of the group
4942 * @param string $text The text of the link
4943 * @return string Wikilink to the group
4945 public static function makeGroupLinkWiki( $group, $text = '' ) {
4946 wfDeprecated( __METHOD__
, '1.29' );
4948 if ( $text == '' ) {
4949 $text = UserGroupMembership
::getGroupName( $group );
4951 $title = UserGroupMembership
::getGroupPage( $group );
4953 $page = $title->getFullText();
4954 return "[[$page|$text]]";
4961 * Returns an array of the groups that a particular group can add/remove.
4963 * @param string $group The group to check for whether it can add/remove
4964 * @return array Array( 'add' => array( addablegroups ),
4965 * 'remove' => array( removablegroups ),
4966 * 'add-self' => array( addablegroups to self),
4967 * 'remove-self' => array( removable groups from self) )
4969 public static function changeableByGroup( $group ) {
4970 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4979 if ( empty( $wgAddGroups[$group] ) ) {
4980 // Don't add anything to $groups
4981 } elseif ( $wgAddGroups[$group] === true ) {
4982 // You get everything
4983 $groups['add'] = self
::getAllGroups();
4984 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4985 $groups['add'] = $wgAddGroups[$group];
4988 // Same thing for remove
4989 if ( empty( $wgRemoveGroups[$group] ) ) {
4991 } elseif ( $wgRemoveGroups[$group] === true ) {
4992 $groups['remove'] = self
::getAllGroups();
4993 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4994 $groups['remove'] = $wgRemoveGroups[$group];
4997 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4998 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4999 foreach ( $wgGroupsAddToSelf as $key => $value ) {
5000 if ( is_int( $key ) ) {
5001 $wgGroupsAddToSelf['user'][] = $value;
5006 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
5007 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
5008 if ( is_int( $key ) ) {
5009 $wgGroupsRemoveFromSelf['user'][] = $value;
5014 // Now figure out what groups the user can add to him/herself
5015 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
5017 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
5018 // No idea WHY this would be used, but it's there
5019 $groups['add-self'] = User
::getAllGroups();
5020 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
5021 $groups['add-self'] = $wgGroupsAddToSelf[$group];
5024 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
5026 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
5027 $groups['remove-self'] = User
::getAllGroups();
5028 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
5029 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
5036 * Returns an array of groups that this user can add and remove
5037 * @return array Array( 'add' => array( addablegroups ),
5038 * 'remove' => array( removablegroups ),
5039 * 'add-self' => array( addablegroups to self),
5040 * 'remove-self' => array( removable groups from self) )
5042 public function changeableGroups() {
5043 if ( $this->isAllowed( 'userrights' ) ) {
5044 // This group gives the right to modify everything (reverse-
5045 // compatibility with old "userrights lets you change
5047 // Using array_merge to make the groups reindexed
5048 $all = array_merge( User
::getAllGroups() );
5057 // Okay, it's not so simple, we will have to go through the arrays
5064 $addergroups = $this->getEffectiveGroups();
5066 foreach ( $addergroups as $addergroup ) {
5067 $groups = array_merge_recursive(
5068 $groups, $this->changeableByGroup( $addergroup )
5070 $groups['add'] = array_unique( $groups['add'] );
5071 $groups['remove'] = array_unique( $groups['remove'] );
5072 $groups['add-self'] = array_unique( $groups['add-self'] );
5073 $groups['remove-self'] = array_unique( $groups['remove-self'] );
5079 * Deferred version of incEditCountImmediate()
5081 public function incEditCount() {
5082 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle(
5084 $this->incEditCountImmediate();
5091 * Increment the user's edit-count field.
5092 * Will have no effect for anonymous users.
5095 public function incEditCountImmediate() {
5096 if ( $this->isAnon() ) {
5100 $dbw = wfGetDB( DB_MASTER
);
5101 // No rows will be "affected" if user_editcount is NULL
5104 [ 'user_editcount=user_editcount+1' ],
5105 [ 'user_id' => $this->getId(), 'user_editcount IS NOT NULL' ],
5108 // Lazy initialization check...
5109 if ( $dbw->affectedRows() == 0 ) {
5110 // Now here's a goddamn hack...
5111 $dbr = wfGetDB( DB_REPLICA
);
5112 if ( $dbr !== $dbw ) {
5113 // If we actually have a replica DB server, the count is
5114 // at least one behind because the current transaction
5115 // has not been committed and replicated.
5116 $this->mEditCount
= $this->initEditCount( 1 );
5118 // But if DB_REPLICA is selecting the master, then the
5119 // count we just read includes the revision that was
5120 // just added in the working transaction.
5121 $this->mEditCount
= $this->initEditCount();
5124 if ( $this->mEditCount
=== null ) {
5125 $this->getEditCount();
5126 $dbr = wfGetDB( DB_REPLICA
);
5127 $this->mEditCount +
= ( $dbr !== $dbw ) ?
1 : 0;
5129 $this->mEditCount++
;
5132 // Edit count in user cache too
5133 $this->invalidateCache();
5137 * Initialize user_editcount from data out of the revision table
5139 * @param int $add Edits to add to the count from the revision table
5140 * @return int Number of edits
5142 protected function initEditCount( $add = 0 ) {
5143 // Pull from a replica DB to be less cruel to servers
5144 // Accuracy isn't the point anyway here
5145 $dbr = wfGetDB( DB_REPLICA
);
5146 $count = (int)$dbr->selectField(
5149 [ 'rev_user' => $this->getId() ],
5152 $count = $count +
$add;
5154 $dbw = wfGetDB( DB_MASTER
);
5157 [ 'user_editcount' => $count ],
5158 [ 'user_id' => $this->getId() ],
5166 * Get the description of a given right
5169 * @param string $right Right to query
5170 * @return string Localized description of the right
5172 public static function getRightDescription( $right ) {
5173 $key = "right-$right";
5174 $msg = wfMessage( $key );
5175 return $msg->isDisabled() ?
$right : $msg->text();
5179 * Get the name of a given grant
5182 * @param string $grant Grant to query
5183 * @return string Localized name of the grant
5185 public static function getGrantName( $grant ) {
5186 $key = "grant-$grant";
5187 $msg = wfMessage( $key );
5188 return $msg->isDisabled() ?
$grant : $msg->text();
5192 * Add a newuser log entry for this user.
5193 * Before 1.19 the return value was always true.
5195 * @deprecated since 1.27, AuthManager handles logging
5196 * @param string|bool $action Account creation type.
5197 * - String, one of the following values:
5198 * - 'create' for an anonymous user creating an account for himself.
5199 * This will force the action's performer to be the created user itself,
5200 * no matter the value of $wgUser
5201 * - 'create2' for a logged in user creating an account for someone else
5202 * - 'byemail' when the created user will receive its password by e-mail
5203 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
5204 * - Boolean means whether the account was created by e-mail (deprecated):
5205 * - true will be converted to 'byemail'
5206 * - false will be converted to 'create' if this object is the same as
5207 * $wgUser and to 'create2' otherwise
5208 * @param string $reason User supplied reason
5211 public function addNewUserLogEntry( $action = false, $reason = '' ) {
5212 return true; // disabled
5216 * Add an autocreate newuser log entry for this user
5217 * Used by things like CentralAuth and perhaps other authplugins.
5218 * Consider calling addNewUserLogEntry() directly instead.
5220 * @deprecated since 1.27, AuthManager handles logging
5223 public function addNewUserLogEntryAutoCreate() {
5224 $this->addNewUserLogEntry( 'autocreate' );
5230 * Load the user options either from cache, the database or an array
5232 * @param array $data Rows for the current user out of the user_properties table
5234 protected function loadOptions( $data = null ) {
5239 if ( $this->mOptionsLoaded
) {
5243 $this->mOptions
= self
::getDefaultOptions();
5245 if ( !$this->getId() ) {
5246 // For unlogged-in users, load language/variant options from request.
5247 // There's no need to do it for logged-in users: they can set preferences,
5248 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5249 // so don't override user's choice (especially when the user chooses site default).
5250 $variant = $wgContLang->getDefaultVariant();
5251 $this->mOptions
['variant'] = $variant;
5252 $this->mOptions
['language'] = $variant;
5253 $this->mOptionsLoaded
= true;
5257 // Maybe load from the object
5258 if ( !is_null( $this->mOptionOverrides
) ) {
5259 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5260 foreach ( $this->mOptionOverrides
as $key => $value ) {
5261 $this->mOptions
[$key] = $value;
5264 if ( !is_array( $data ) ) {
5265 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5266 // Load from database
5267 $dbr = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
5268 ?
wfGetDB( DB_MASTER
)
5269 : wfGetDB( DB_REPLICA
);
5271 $res = $dbr->select(
5273 [ 'up_property', 'up_value' ],
5274 [ 'up_user' => $this->getId() ],
5278 $this->mOptionOverrides
= [];
5280 foreach ( $res as $row ) {
5281 // Convert '0' to 0. PHP's boolean conversion considers them both
5282 // false, but e.g. JavaScript considers the former as true.
5283 // @todo: T54542 Somehow determine the desired type (string/int/bool)
5284 // and convert all values here.
5285 if ( $row->up_value
=== '0' ) {
5288 $data[$row->up_property
] = $row->up_value
;
5291 foreach ( $data as $property => $value ) {
5292 $this->mOptionOverrides
[$property] = $value;
5293 $this->mOptions
[$property] = $value;
5297 $this->mOptionsLoaded
= true;
5299 Hooks
::run( 'UserLoadOptions', [ $this, &$this->mOptions
] );
5303 * Saves the non-default options for this user, as previously set e.g. via
5304 * setOption(), in the database's "user_properties" (preferences) table.
5305 * Usually used via saveSettings().
5307 protected function saveOptions() {
5308 $this->loadOptions();
5310 // Not using getOptions(), to keep hidden preferences in database
5311 $saveOptions = $this->mOptions
;
5313 // Allow hooks to abort, for instance to save to a global profile.
5314 // Reset options to default state before saving.
5315 if ( !Hooks
::run( 'UserSaveOptions', [ $this, &$saveOptions ] ) ) {
5319 $userId = $this->getId();
5321 $insert_rows = []; // all the new preference rows
5322 foreach ( $saveOptions as $key => $value ) {
5323 // Don't bother storing default values
5324 $defaultOption = self
::getDefaultOption( $key );
5325 if ( ( $defaultOption === null && $value !== false && $value !== null )
5326 ||
$value != $defaultOption
5329 'up_user' => $userId,
5330 'up_property' => $key,
5331 'up_value' => $value,
5336 $dbw = wfGetDB( DB_MASTER
);
5338 $res = $dbw->select( 'user_properties',
5339 [ 'up_property', 'up_value' ], [ 'up_user' => $userId ], __METHOD__
);
5341 // Find prior rows that need to be removed or updated. These rows will
5342 // all be deleted (the latter so that INSERT IGNORE applies the new values).
5344 foreach ( $res as $row ) {
5345 if ( !isset( $saveOptions[$row->up_property
] )
5346 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
5348 $keysDelete[] = $row->up_property
;
5352 if ( count( $keysDelete ) ) {
5353 // Do the DELETE by PRIMARY KEY for prior rows.
5354 // In the past a very large portion of calls to this function are for setting
5355 // 'rememberpassword' for new accounts (a preference that has since been removed).
5356 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5357 // caused gap locks on [max user ID,+infinity) which caused high contention since
5358 // updates would pile up on each other as they are for higher (newer) user IDs.
5359 // It might not be necessary these days, but it shouldn't hurt either.
5360 $dbw->delete( 'user_properties',
5361 [ 'up_user' => $userId, 'up_property' => $keysDelete ], __METHOD__
);
5363 // Insert the new preference rows
5364 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, [ 'IGNORE' ] );
5368 * Lazily instantiate and return a factory object for making passwords
5370 * @deprecated since 1.27, create a PasswordFactory directly instead
5371 * @return PasswordFactory
5373 public static function getPasswordFactory() {
5374 wfDeprecated( __METHOD__
, '1.27' );
5375 $ret = new PasswordFactory();
5376 $ret->init( RequestContext
::getMain()->getConfig() );
5381 * Provide an array of HTML5 attributes to put on an input element
5382 * intended for the user to enter a new password. This may include
5383 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
5385 * Do *not* use this when asking the user to enter his current password!
5386 * Regardless of configuration, users may have invalid passwords for whatever
5387 * reason (e.g., they were set before requirements were tightened up).
5388 * Only use it when asking for a new password, like on account creation or
5391 * Obviously, you still need to do server-side checking.
5393 * NOTE: A combination of bugs in various browsers means that this function
5394 * actually just returns array() unconditionally at the moment. May as
5395 * well keep it around for when the browser bugs get fixed, though.
5397 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
5399 * @deprecated since 1.27
5400 * @return array Array of HTML attributes suitable for feeding to
5401 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
5402 * That will get confused by the boolean attribute syntax used.)
5404 public static function passwordChangeInputAttribs() {
5405 global $wgMinimalPasswordLength;
5407 if ( $wgMinimalPasswordLength == 0 ) {
5411 # Note that the pattern requirement will always be satisfied if the
5412 # input is empty, so we need required in all cases.
5414 # @todo FIXME: T25769: This needs to not claim the password is required
5415 # if e-mail confirmation is being used. Since HTML5 input validation
5416 # is b0rked anyway in some browsers, just return nothing. When it's
5417 # re-enabled, fix this code to not output required for e-mail
5419 # $ret = array( 'required' );
5422 # We can't actually do this right now, because Opera 9.6 will print out
5423 # the entered password visibly in its error message! When other
5424 # browsers add support for this attribute, or Opera fixes its support,
5425 # we can add support with a version check to avoid doing this on Opera
5426 # versions where it will be a problem. Reported to Opera as
5427 # DSK-262266, but they don't have a public bug tracker for us to follow.
5429 if ( $wgMinimalPasswordLength > 1 ) {
5430 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
5431 $ret['title'] = wfMessage( 'passwordtooshort' )
5432 ->numParams( $wgMinimalPasswordLength )->text();
5440 * Return the list of user fields that should be selected to create
5441 * a new user object.
5444 public static function selectFields() {
5452 'user_email_authenticated',
5454 'user_email_token_expires',
5455 'user_registration',
5461 * Factory function for fatal permission-denied errors
5464 * @param string $permission User right required
5467 static function newFatalPermissionDeniedStatus( $permission ) {
5471 foreach ( User
::getGroupsWithPermission( $permission ) as $group ) {
5472 $groups[] = UserGroupMembership
::getLink( $group, RequestContext
::getMain(), 'wiki' );
5476 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5478 return Status
::newFatal( 'badaccess-group0' );
5483 * Get a new instance of this user that was loaded from the master via a locking read
5485 * Use this instead of the main context User when updating that user. This avoids races
5486 * where that user was loaded from a replica DB or even the master but without proper locks.
5488 * @return User|null Returns null if the user was not found in the DB
5491 public function getInstanceForUpdate() {
5492 if ( !$this->getId() ) {
5493 return null; // anon
5496 $user = self
::newFromId( $this->getId() );
5497 if ( !$user->loadFromId( self
::READ_EXCLUSIVE
) ) {
5505 * Checks if two user objects point to the same user.
5511 public function equals( User
$user ) {
5512 return $this->getName() === $user->getName();