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
;
28 * String Some punctuation to prevent editing from broken text-mangling proxies.
29 * @deprecated since 1.27, use \MediaWiki\Session\Token::SUFFIX
32 define( 'EDIT_TOKEN_SUFFIX', Token
::SUFFIX
);
35 * The User object encapsulates all of the user-specific settings (user_id,
36 * name, rights, email address, options, last login time). Client
37 * classes use the getXXX() functions to access these fields. These functions
38 * do all the work of determining whether the user is logged in,
39 * whether the requested option can be satisfied from cookies or
40 * whether a database query is needed. Most of the settings needed
41 * for rendering normal pages are set in the cookie to minimize use
44 class User
implements IDBAccessObject
{
46 * @const int Number of characters in user_token field.
48 const TOKEN_LENGTH
= 32;
51 * @const string An invalid value for user_token
53 const INVALID_TOKEN
= '*** INVALID ***';
56 * Global constant made accessible as class constants so that autoloader
58 * @deprecated since 1.27, use \MediaWiki\Session\Token::SUFFIX
60 const EDIT_TOKEN_SUFFIX
= EDIT_TOKEN_SUFFIX
;
63 * @const int Serialized record version.
68 * Exclude user options that are set to their default value.
71 const GETOPTIONS_EXCLUDE_DEFAULTS
= 1;
76 const CHECK_USER_RIGHTS
= true;
81 const IGNORE_USER_RIGHTS
= false;
84 * Array of Strings List of member variables which are saved to the
85 * shared cache (memcached). Any operation which changes the
86 * corresponding database fields must call a cache-clearing function.
89 protected static $mCacheVars = [
97 'mEmailAuthenticated',
104 // user_properties table
109 * Array of Strings Core rights.
110 * Each of these should have a corresponding message of the form
114 protected static $mCoreRights = [
145 'editusercssjs', # deprecated
158 'move-categorypages',
159 'move-rootuserpages',
163 'override-export-depth',
186 'userrights-interwiki',
194 * String Cached results of getAllRights()
196 protected static $mAllRights = false;
199 * An in-process cache for user data lookup
202 protected static $inProcessCache;
204 /** Cache variables */
215 /** @var string TS_MW timestamp from the DB */
217 /** @var string TS_MW timestamp from cache */
218 protected $mQuickTouched;
222 public $mEmailAuthenticated;
224 protected $mEmailToken;
226 protected $mEmailTokenExpires;
228 protected $mRegistration;
230 protected $mEditCount;
234 protected $mOptionOverrides;
238 * Bool Whether the cache variables have been loaded.
241 public $mOptionsLoaded;
244 * Array with already loaded items or true if all items have been loaded.
246 protected $mLoadedItems = [];
250 * String Initialization data source if mLoadedItems!==true. May be one of:
251 * - 'defaults' anonymous user initialised from class defaults
252 * - 'name' initialise from mName
253 * - 'id' initialise from mId
254 * - 'session' log in from session if possible
256 * Use the User::newFrom*() family of functions to set this.
261 * Lazy-initialized variables, invalidated with clearInstanceCache
265 protected $mDatePreference;
273 protected $mBlockreason;
275 protected $mEffectiveGroups;
277 protected $mImplicitGroups;
279 protected $mFormerGroups;
281 protected $mGlobalBlock;
298 protected $mAllowUsertalk;
301 private $mBlockedFromCreateAccount = false;
303 /** @var integer User::READ_* constant bitfield used to load data */
304 protected $queryFlagsUsed = self
::READ_NORMAL
;
306 public static $idCacheByName = [];
309 * Lightweight constructor for an anonymous user.
310 * Use the User::newFrom* factory functions for other kinds of users.
314 * @see newFromConfirmationCode()
315 * @see newFromSession()
318 public function __construct() {
319 $this->clearInstanceCache( 'defaults' );
325 public function __toString() {
326 return $this->getName();
330 * Test if it's safe to load this User object.
332 * You should typically check this before using $wgUser or
333 * RequestContext::getUser in a method that might be called before the
334 * system has been fully initialized. If the object is unsafe, you should
335 * use an anonymous user:
337 * $user = $wgUser->isSafeToLoad() ? $wgUser : new User;
343 public function isSafeToLoad() {
344 global $wgFullyInitialised;
346 // The user is safe to load if:
347 // * MW_NO_SESSION is undefined AND $wgFullyInitialised is true (safe to use session data)
348 // * mLoadedItems === true (already loaded)
349 // * mFrom !== 'session' (sessions not involved at all)
351 return ( !defined( 'MW_NO_SESSION' ) && $wgFullyInitialised ) ||
352 $this->mLoadedItems
=== true ||
$this->mFrom
!== 'session';
356 * Load the user table data for this object from the source given by mFrom.
358 * @param integer $flags User::READ_* constant bitfield
360 public function load( $flags = self
::READ_NORMAL
) {
361 global $wgFullyInitialised;
363 if ( $this->mLoadedItems
=== true ) {
367 // Set it now to avoid infinite recursion in accessors
368 $oldLoadedItems = $this->mLoadedItems
;
369 $this->mLoadedItems
= true;
370 $this->queryFlagsUsed
= $flags;
372 // If this is called too early, things are likely to break.
373 if ( !$wgFullyInitialised && $this->mFrom
=== 'session' ) {
374 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
375 ->warning( 'User::loadFromSession called before the end of Setup.php', [
376 'exception' => new Exception( 'User::loadFromSession called before the end of Setup.php' ),
378 $this->loadDefaults();
379 $this->mLoadedItems
= $oldLoadedItems;
383 switch ( $this->mFrom
) {
385 $this->loadDefaults();
388 // Make sure this thread sees its own changes
389 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
390 $flags |
= self
::READ_LATEST
;
391 $this->queryFlagsUsed
= $flags;
394 $this->mId
= self
::idFromName( $this->mName
, $flags );
396 // Nonexistent user placeholder object
397 $this->loadDefaults( $this->mName
);
399 $this->loadFromId( $flags );
403 $this->loadFromId( $flags );
406 if ( !$this->loadFromSession() ) {
407 // Loading from session failed. Load defaults.
408 $this->loadDefaults();
410 Hooks
::run( 'UserLoadAfterLoadFromSession', [ $this ] );
413 throw new UnexpectedValueException(
414 "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
419 * Load user table data, given mId has already been set.
420 * @param integer $flags User::READ_* constant bitfield
421 * @return bool False if the ID does not exist, true otherwise
423 public function loadFromId( $flags = self
::READ_NORMAL
) {
424 if ( $this->mId
== 0 ) {
425 $this->loadDefaults();
429 // Try cache (unless this needs data from the master DB).
430 // NOTE: if this thread called saveSettings(), the cache was cleared.
431 $latest = DBAccessObjectUtils
::hasFlags( $flags, self
::READ_LATEST
);
432 if ( $latest ||
!$this->loadFromCache() ) {
433 wfDebug( "User: cache miss for user {$this->mId}\n" );
434 // Load from DB (make sure this thread sees its own changes)
435 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
436 $flags |
= self
::READ_LATEST
;
438 if ( !$this->loadFromDatabase( $flags ) ) {
439 // Can't load from ID, user is anonymous
442 $this->saveToCache();
445 $this->mLoadedItems
= true;
446 $this->queryFlagsUsed
= $flags;
453 * @param string $wikiId
454 * @param integer $userId
456 public static function purge( $wikiId, $userId ) {
457 $cache = ObjectCache
::getMainWANInstance();
458 $processCache = self
::getInProcessCache();
459 $key = $cache->makeGlobalKey( 'user', 'id', $wikiId, $userId );
460 $cache->delete( $key );
461 $processCache->delete( $key );
466 * @param WANObjectCache $cache
469 protected function getCacheKey( WANObjectCache
$cache ) {
470 return $cache->makeGlobalKey( 'user', 'id', wfWikiID(), $this->mId
);
475 * @return HashBagOStuff
477 protected static function getInProcessCache() {
478 if ( !self
::$inProcessCache ) {
479 self
::$inProcessCache = new HashBagOStuff( [ 'maxKeys' => 10 ] );
481 return self
::$inProcessCache;
485 * Load user data from shared cache, given mId has already been set.
487 * @return bool false if the ID does not exist or data is invalid, true otherwise
490 protected function loadFromCache() {
491 if ( $this->mId
== 0 ) {
492 $this->loadDefaults();
496 $cache = ObjectCache
::getMainWANInstance();
497 $processCache = self
::getInProcessCache();
498 $key = $this->getCacheKey( $cache );
499 $data = $processCache->get( $key );
500 if ( !is_array( $data ) ) {
501 $data = $cache->get( $key );
502 if ( !is_array( $data ) ||
$data['mVersion'] < self
::VERSION
) {
506 $processCache->set( $key, $data );
508 wfDebug( "User: got user {$this->mId} from cache\n" );
510 // Restore from cache
511 foreach ( self
::$mCacheVars as $name ) {
512 $this->$name = $data[$name];
519 * Save user data to the shared cache
521 * This method should not be called outside the User class
523 public function saveToCache() {
526 $this->loadOptions();
528 if ( $this->isAnon() ) {
529 // Anonymous users are uncached
534 foreach ( self
::$mCacheVars as $name ) {
535 $data[$name] = $this->$name;
537 $data['mVersion'] = self
::VERSION
;
538 $opts = Database
::getCacheSetOptions( wfGetDB( DB_SLAVE
) );
540 $cache = ObjectCache
::getMainWANInstance();
541 $processCache = self
::getInProcessCache();
542 $key = $this->getCacheKey( $cache );
543 $cache->set( $key, $data, $cache::TTL_HOUR
, $opts );
544 $processCache->set( $key, $data );
547 /** @name newFrom*() static factory methods */
551 * Static factory method for creation from username.
553 * This is slightly less efficient than newFromId(), so use newFromId() if
554 * you have both an ID and a name handy.
556 * @param string $name Username, validated by Title::newFromText()
557 * @param string|bool $validate Validate username. Takes the same parameters as
558 * User::getCanonicalName(), except that true is accepted as an alias
559 * for 'valid', for BC.
561 * @return User|bool User object, or false if the username is invalid
562 * (e.g. if it contains illegal characters or is an IP address). If the
563 * username is not present in the database, the result will be a user object
564 * with a name, zero user ID and default settings.
566 public static function newFromName( $name, $validate = 'valid' ) {
567 if ( $validate === true ) {
570 $name = self
::getCanonicalName( $name, $validate );
571 if ( $name === false ) {
574 // Create unloaded user object
578 $u->setItemLoaded( 'name' );
584 * Static factory method for creation from a given user ID.
586 * @param int $id Valid user ID
587 * @return User The corresponding User object
589 public static function newFromId( $id ) {
593 $u->setItemLoaded( 'id' );
598 * Factory method to fetch whichever user has a given email confirmation code.
599 * This code is generated when an account is created or its e-mail address
602 * If the code is invalid or has expired, returns NULL.
604 * @param string $code Confirmation code
605 * @param int $flags User::READ_* bitfield
608 public static function newFromConfirmationCode( $code, $flags = 0 ) {
609 $db = ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
610 ?
wfGetDB( DB_MASTER
)
611 : wfGetDB( DB_SLAVE
);
613 $id = $db->selectField(
617 'user_email_token' => md5( $code ),
618 'user_email_token_expires > ' . $db->addQuotes( $db->timestamp() ),
622 return $id ? User
::newFromId( $id ) : null;
626 * Create a new user object using data from session. If the login
627 * credentials are invalid, the result is an anonymous user.
629 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
632 public static function newFromSession( WebRequest
$request = null ) {
634 $user->mFrom
= 'session';
635 $user->mRequest
= $request;
640 * Create a new user object from a user row.
641 * The row should have the following fields from the user table in it:
642 * - either user_name or user_id to load further data if needed (or both)
644 * - all other fields (email, etc.)
645 * It is useless to provide the remaining fields if either user_id,
646 * user_name and user_real_name are not provided because the whole row
647 * will be loaded once more from the database when accessing them.
649 * @param stdClass $row A row from the user table
650 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
653 public static function newFromRow( $row, $data = null ) {
655 $user->loadFromRow( $row, $data );
660 * Static factory method for creation of a "system" user from username.
662 * A "system" user is an account that's used to attribute logged actions
663 * taken by MediaWiki itself, as opposed to a bot or human user. Examples
664 * might include the 'Maintenance script' or 'Conversion script' accounts
665 * used by various scripts in the maintenance/ directory or accounts such
666 * as 'MediaWiki message delivery' used by the MassMessage extension.
668 * This can optionally create the user if it doesn't exist, and "steal" the
669 * account if it does exist.
671 * @param string $name Username
672 * @param array $options Options are:
673 * - validate: As for User::getCanonicalName(), default 'valid'
674 * - create: Whether to create the user if it doesn't already exist, default true
675 * - steal: Whether to reset the account's password and email if it
676 * already exists, default false
680 public static function newSystemUser( $name, $options = [] ) {
682 'validate' => 'valid',
687 $name = self
::getCanonicalName( $name, $options['validate'] );
688 if ( $name === false ) {
692 $dbw = wfGetDB( DB_MASTER
);
693 $row = $dbw->selectRow(
696 self
::selectFields(),
697 [ 'user_password', 'user_newpassword' ]
699 [ 'user_name' => $name ],
703 // No user. Create it?
704 return $options['create'] ? self
::createNew( $name ) : null;
706 $user = self
::newFromRow( $row );
708 // A user is considered to exist as a non-system user if it has a
709 // password set, or a temporary password set, or an email set, or a
710 // non-invalid token.
711 $passwordFactory = new PasswordFactory();
712 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
714 $password = $passwordFactory->newFromCiphertext( $row->user_password
);
715 } catch ( PasswordError
$e ) {
716 wfDebug( 'Invalid password hash found in database.' );
717 $password = PasswordFactory
::newInvalidPassword();
720 $newpassword = $passwordFactory->newFromCiphertext( $row->user_newpassword
);
721 } catch ( PasswordError
$e ) {
722 wfDebug( 'Invalid password hash found in database.' );
723 $newpassword = PasswordFactory
::newInvalidPassword();
725 if ( !$password instanceof InvalidPassword ||
!$newpassword instanceof InvalidPassword
726 ||
$user->mEmail ||
$user->mToken
!== self
::INVALID_TOKEN
728 // User exists. Steal it?
729 if ( !$options['steal'] ) {
733 $nopass = PasswordFactory
::newInvalidPassword()->toString();
738 'user_password' => $nopass,
739 'user_newpassword' => $nopass,
740 'user_newpass_time' => null,
742 [ 'user_id' => $user->getId() ],
745 $user->invalidateEmail();
746 $user->mToken
= self
::INVALID_TOKEN
;
747 $user->saveSettings();
748 SessionManager
::singleton()->preventSessionsForUser( $user->getName() );
757 * Get the username corresponding to a given user ID
758 * @param int $id User ID
759 * @return string|bool The corresponding username
761 public static function whoIs( $id ) {
762 return UserCache
::singleton()->getProp( $id, 'name' );
766 * Get the real name of a user given their user ID
768 * @param int $id User ID
769 * @return string|bool The corresponding user's real name
771 public static function whoIsReal( $id ) {
772 return UserCache
::singleton()->getProp( $id, 'real_name' );
776 * Get database id given a user name
777 * @param string $name Username
778 * @param integer $flags User::READ_* constant bitfield
779 * @return int|null The corresponding user's ID, or null if user is nonexistent
781 public static function idFromName( $name, $flags = self
::READ_NORMAL
) {
782 $nt = Title
::makeTitleSafe( NS_USER
, $name );
783 if ( is_null( $nt ) ) {
788 if ( !( $flags & self
::READ_LATEST
) && isset( self
::$idCacheByName[$name] ) ) {
789 return self
::$idCacheByName[$name];
792 $db = ( $flags & self
::READ_LATEST
)
793 ?
wfGetDB( DB_MASTER
)
794 : wfGetDB( DB_SLAVE
);
799 [ 'user_name' => $nt->getText() ],
803 if ( $s === false ) {
806 $result = $s->user_id
;
809 self
::$idCacheByName[$name] = $result;
811 if ( count( self
::$idCacheByName ) > 1000 ) {
812 self
::$idCacheByName = [];
819 * Reset the cache used in idFromName(). For use in tests.
821 public static function resetIdByNameCache() {
822 self
::$idCacheByName = [];
826 * Does the string match an anonymous IPv4 address?
828 * This function exists for username validation, in order to reject
829 * usernames which are similar in form to IP addresses. Strings such
830 * as 300.300.300.300 will return true because it looks like an IP
831 * address, despite not being strictly valid.
833 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
834 * address because the usemod software would "cloak" anonymous IP
835 * addresses like this, if we allowed accounts like this to be created
836 * new users could get the old edits of these anonymous users.
838 * @param string $name Name to match
841 public static function isIP( $name ) {
842 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
843 || IP
::isIPv6( $name );
847 * Is the input a valid username?
849 * Checks if the input is a valid username, we don't want an empty string,
850 * an IP address, anything that contains slashes (would mess up subpages),
851 * is longer than the maximum allowed username size or doesn't begin with
854 * @param string $name Name to match
857 public static function isValidUserName( $name ) {
858 global $wgContLang, $wgMaxNameChars;
861 || User
::isIP( $name )
862 ||
strpos( $name, '/' ) !== false
863 ||
strlen( $name ) > $wgMaxNameChars
864 ||
$name != $wgContLang->ucfirst( $name )
869 // Ensure that the name can't be misresolved as a different title,
870 // such as with extra namespace keys at the start.
871 $parsed = Title
::newFromText( $name );
872 if ( is_null( $parsed )
873 ||
$parsed->getNamespace()
874 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
878 // Check an additional blacklist of troublemaker characters.
879 // Should these be merged into the title char list?
880 $unicodeBlacklist = '/[' .
881 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
882 '\x{00a0}' . # non-breaking space
883 '\x{2000}-\x{200f}' . # various whitespace
884 '\x{2028}-\x{202f}' . # breaks and control chars
885 '\x{3000}' . # ideographic space
886 '\x{e000}-\x{f8ff}' . # private use
888 if ( preg_match( $unicodeBlacklist, $name ) ) {
896 * Usernames which fail to pass this function will be blocked
897 * from user login and new account registrations, but may be used
898 * internally by batch processes.
900 * If an account already exists in this form, login will be blocked
901 * by a failure to pass this function.
903 * @param string $name Name to match
906 public static function isUsableName( $name ) {
907 global $wgReservedUsernames;
908 // Must be a valid username, obviously ;)
909 if ( !self
::isValidUserName( $name ) ) {
913 static $reservedUsernames = false;
914 if ( !$reservedUsernames ) {
915 $reservedUsernames = $wgReservedUsernames;
916 Hooks
::run( 'UserGetReservedNames', [ &$reservedUsernames ] );
919 // Certain names may be reserved for batch processes.
920 foreach ( $reservedUsernames as $reserved ) {
921 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
922 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
924 if ( $reserved == $name ) {
932 * Usernames which fail to pass this function will be blocked
933 * from new account registrations, but may be used internally
934 * either by batch processes or by user accounts which have
935 * already been created.
937 * Additional blacklisting may be added here rather than in
938 * isValidUserName() to avoid disrupting existing accounts.
940 * @param string $name String to match
943 public static function isCreatableName( $name ) {
944 global $wgInvalidUsernameCharacters;
946 // Ensure that the username isn't longer than 235 bytes, so that
947 // (at least for the builtin skins) user javascript and css files
948 // will work. (bug 23080)
949 if ( strlen( $name ) > 235 ) {
950 wfDebugLog( 'username', __METHOD__
.
951 ": '$name' invalid due to length" );
955 // Preg yells if you try to give it an empty string
956 if ( $wgInvalidUsernameCharacters !== '' ) {
957 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
958 wfDebugLog( 'username', __METHOD__
.
959 ": '$name' invalid due to wgInvalidUsernameCharacters" );
964 return self
::isUsableName( $name );
968 * Is the input a valid password for this user?
970 * @param string $password Desired password
973 public function isValidPassword( $password ) {
974 // simple boolean wrapper for getPasswordValidity
975 return $this->getPasswordValidity( $password ) === true;
979 * Given unvalidated password input, return error message on failure.
981 * @param string $password Desired password
982 * @return bool|string|array True on success, string or array of error message on failure
984 public function getPasswordValidity( $password ) {
985 $result = $this->checkPasswordValidity( $password );
986 if ( $result->isGood() ) {
990 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
991 $messages[] = $error['message'];
993 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
994 $messages[] = $warning['message'];
996 if ( count( $messages ) === 1 ) {
1004 * Check if this is a valid password for this user
1006 * Create a Status object based on the password's validity.
1007 * The Status should be set to fatal if the user should not
1008 * be allowed to log in, and should have any errors that
1009 * would block changing the password.
1011 * If the return value of this is not OK, the password
1012 * should not be checked. If the return value is not Good,
1013 * the password can be checked, but the user should not be
1014 * able to set their password to this.
1016 * @param string $password Desired password
1017 * @param string $purpose one of 'login', 'create', 'reset'
1021 public function checkPasswordValidity( $password, $purpose = 'login' ) {
1022 global $wgPasswordPolicy;
1024 $upp = new UserPasswordPolicy(
1025 $wgPasswordPolicy['policies'],
1026 $wgPasswordPolicy['checks']
1029 $status = Status
::newGood();
1030 $result = false; // init $result to false for the internal checks
1032 if ( !Hooks
::run( 'isValidPassword', [ $password, &$result, $this ] ) ) {
1033 $status->error( $result );
1037 if ( $result === false ) {
1038 $status->merge( $upp->checkUserPassword( $this, $password, $purpose ) );
1040 } elseif ( $result === true ) {
1043 $status->error( $result );
1044 return $status; // the isValidPassword hook set a string $result and returned true
1049 * Given unvalidated user input, return a canonical username, or false if
1050 * the username is invalid.
1051 * @param string $name User input
1052 * @param string|bool $validate Type of validation to use:
1053 * - false No validation
1054 * - 'valid' Valid for batch processes
1055 * - 'usable' Valid for batch processes and login
1056 * - 'creatable' Valid for batch processes, login and account creation
1058 * @throws InvalidArgumentException
1059 * @return bool|string
1061 public static function getCanonicalName( $name, $validate = 'valid' ) {
1062 // Force usernames to capital
1064 $name = $wgContLang->ucfirst( $name );
1066 # Reject names containing '#'; these will be cleaned up
1067 # with title normalisation, but then it's too late to
1069 if ( strpos( $name, '#' ) !== false ) {
1073 // Clean up name according to title rules,
1074 // but only when validation is requested (bug 12654)
1075 $t = ( $validate !== false ) ?
1076 Title
::newFromText( $name, NS_USER
) : Title
::makeTitle( NS_USER
, $name );
1077 // Check for invalid titles
1078 if ( is_null( $t ) ||
$t->getNamespace() !== NS_USER ||
$t->isExternal() ) {
1082 // Reject various classes of invalid names
1084 $name = $wgAuth->getCanonicalName( $t->getText() );
1086 switch ( $validate ) {
1090 if ( !User
::isValidUserName( $name ) ) {
1095 if ( !User
::isUsableName( $name ) ) {
1100 if ( !User
::isCreatableName( $name ) ) {
1105 throw new InvalidArgumentException(
1106 'Invalid parameter value for $validate in ' . __METHOD__
);
1112 * Count the number of edits of a user
1114 * @param int $uid User ID to check
1115 * @return int The user's edit count
1117 * @deprecated since 1.21 in favour of User::getEditCount
1119 public static function edits( $uid ) {
1120 wfDeprecated( __METHOD__
, '1.21' );
1121 $user = self
::newFromId( $uid );
1122 return $user->getEditCount();
1126 * Return a random password.
1128 * @deprecated since 1.27, use PasswordFactory::generateRandomPasswordString()
1129 * @return string New random password
1131 public static function randomPassword() {
1132 global $wgMinimalPasswordLength;
1133 return PasswordFactory
::generateRandomPasswordString( $wgMinimalPasswordLength );
1137 * Set cached properties to default.
1139 * @note This no longer clears uncached lazy-initialised properties;
1140 * the constructor does that instead.
1142 * @param string|bool $name
1144 public function loadDefaults( $name = false ) {
1146 $this->mName
= $name;
1147 $this->mRealName
= '';
1149 $this->mOptionOverrides
= null;
1150 $this->mOptionsLoaded
= false;
1152 $loggedOut = $this->mRequest
&& !defined( 'MW_NO_SESSION' )
1153 ?
$this->mRequest
->getSession()->getLoggedOutTimestamp() : 0;
1154 if ( $loggedOut !== 0 ) {
1155 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1157 $this->mTouched
= '1'; # Allow any pages to be cached
1160 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1161 $this->mEmailAuthenticated
= null;
1162 $this->mEmailToken
= '';
1163 $this->mEmailTokenExpires
= null;
1164 $this->mRegistration
= wfTimestamp( TS_MW
);
1165 $this->mGroups
= [];
1167 Hooks
::run( 'UserLoadDefaults', [ $this, $name ] );
1171 * Return whether an item has been loaded.
1173 * @param string $item Item to check. Current possibilities:
1177 * @param string $all 'all' to check if the whole object has been loaded
1178 * or any other string to check if only the item is available (e.g.
1182 public function isItemLoaded( $item, $all = 'all' ) {
1183 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1184 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1188 * Set that an item has been loaded
1190 * @param string $item
1192 protected function setItemLoaded( $item ) {
1193 if ( is_array( $this->mLoadedItems
) ) {
1194 $this->mLoadedItems
[$item] = true;
1199 * Load user data from the session.
1201 * @return bool True if the user is logged in, false otherwise.
1203 private function loadFromSession() {
1206 Hooks
::run( 'UserLoadFromSession', [ $this, &$result ], '1.27' );
1207 if ( $result !== null ) {
1211 // MediaWiki\Session\Session already did the necessary authentication of the user
1212 // returned here, so just use it if applicable.
1213 $session = $this->getRequest()->getSession();
1214 $user = $session->getUser();
1215 if ( $user->isLoggedIn() ) {
1216 $this->loadFromUserObject( $user );
1217 // Other code expects these to be set in the session, so set them.
1218 $session->set( 'wsUserID', $this->getId() );
1219 $session->set( 'wsUserName', $this->getName() );
1220 $session->set( 'wsToken', $this->getToken() );
1228 * Load user and user_group data from the database.
1229 * $this->mId must be set, this is how the user is identified.
1231 * @param integer $flags User::READ_* constant bitfield
1232 * @return bool True if the user exists, false if the user is anonymous
1234 public function loadFromDatabase( $flags = self
::READ_LATEST
) {
1236 $this->mId
= intval( $this->mId
);
1239 if ( !$this->mId
) {
1240 $this->loadDefaults();
1244 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
1245 $db = wfGetDB( $index );
1247 $s = $db->selectRow(
1249 self
::selectFields(),
1250 [ 'user_id' => $this->mId
],
1255 $this->queryFlagsUsed
= $flags;
1256 Hooks
::run( 'UserLoadFromDatabase', [ $this, &$s ] );
1258 if ( $s !== false ) {
1259 // Initialise user table data
1260 $this->loadFromRow( $s );
1261 $this->mGroups
= null; // deferred
1262 $this->getEditCount(); // revalidation for nulls
1267 $this->loadDefaults();
1273 * Initialize this object from a row from the user table.
1275 * @param stdClass $row Row from the user table to load.
1276 * @param array $data Further user data to load into the object
1278 * user_groups Array with groups out of the user_groups table
1279 * user_properties Array with properties out of the user_properties table
1281 protected function loadFromRow( $row, $data = null ) {
1284 $this->mGroups
= null; // deferred
1286 if ( isset( $row->user_name
) ) {
1287 $this->mName
= $row->user_name
;
1288 $this->mFrom
= 'name';
1289 $this->setItemLoaded( 'name' );
1294 if ( isset( $row->user_real_name
) ) {
1295 $this->mRealName
= $row->user_real_name
;
1296 $this->setItemLoaded( 'realname' );
1301 if ( isset( $row->user_id
) ) {
1302 $this->mId
= intval( $row->user_id
);
1303 $this->mFrom
= 'id';
1304 $this->setItemLoaded( 'id' );
1309 if ( isset( $row->user_id
) && isset( $row->user_name
) ) {
1310 self
::$idCacheByName[$row->user_name
] = $row->user_id
;
1313 if ( isset( $row->user_editcount
) ) {
1314 $this->mEditCount
= $row->user_editcount
;
1319 if ( isset( $row->user_touched
) ) {
1320 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1325 if ( isset( $row->user_token
) ) {
1326 // The definition for the column is binary(32), so trim the NULs
1327 // that appends. The previous definition was char(32), so trim
1329 $this->mToken
= rtrim( $row->user_token
, " \0" );
1330 if ( $this->mToken
=== '' ) {
1331 $this->mToken
= null;
1337 if ( isset( $row->user_email
) ) {
1338 $this->mEmail
= $row->user_email
;
1339 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1340 $this->mEmailToken
= $row->user_email_token
;
1341 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1342 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1348 $this->mLoadedItems
= true;
1351 if ( is_array( $data ) ) {
1352 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1353 $this->mGroups
= $data['user_groups'];
1355 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1356 $this->loadOptions( $data['user_properties'] );
1362 * Load the data for this user object from another user object.
1366 protected function loadFromUserObject( $user ) {
1368 $user->loadGroups();
1369 $user->loadOptions();
1370 foreach ( self
::$mCacheVars as $var ) {
1371 $this->$var = $user->$var;
1376 * Load the groups from the database if they aren't already loaded.
1378 private function loadGroups() {
1379 if ( is_null( $this->mGroups
) ) {
1380 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
1381 ?
wfGetDB( DB_MASTER
)
1382 : wfGetDB( DB_SLAVE
);
1383 $res = $db->select( 'user_groups',
1385 [ 'ug_user' => $this->mId
],
1387 $this->mGroups
= [];
1388 foreach ( $res as $row ) {
1389 $this->mGroups
[] = $row->ug_group
;
1395 * Add the user to the group if he/she meets given criteria.
1397 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1398 * possible to remove manually via Special:UserRights. In such case it
1399 * will not be re-added automatically. The user will also not lose the
1400 * group if they no longer meet the criteria.
1402 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1404 * @return array Array of groups the user has been promoted to.
1406 * @see $wgAutopromoteOnce
1408 public function addAutopromoteOnceGroups( $event ) {
1409 global $wgAutopromoteOnceLogInRC, $wgAuth;
1411 if ( wfReadOnly() ||
!$this->getId() ) {
1415 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1416 if ( !count( $toPromote ) ) {
1420 if ( !$this->checkAndSetTouched() ) {
1421 return []; // raced out (bug T48834)
1424 $oldGroups = $this->getGroups(); // previous groups
1425 foreach ( $toPromote as $group ) {
1426 $this->addGroup( $group );
1428 // update groups in external authentication database
1429 Hooks
::run( 'UserGroupsChanged', [ $this, $toPromote, [], false, false ] );
1430 $wgAuth->updateExternalDBGroups( $this, $toPromote );
1432 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1434 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1435 $logEntry->setPerformer( $this );
1436 $logEntry->setTarget( $this->getUserPage() );
1437 $logEntry->setParameters( [
1438 '4::oldgroups' => $oldGroups,
1439 '5::newgroups' => $newGroups,
1441 $logid = $logEntry->insert();
1442 if ( $wgAutopromoteOnceLogInRC ) {
1443 $logEntry->publish( $logid );
1450 * Bump user_touched if it didn't change since this object was loaded
1452 * On success, the mTouched field is updated.
1453 * The user serialization cache is always cleared.
1455 * @return bool Whether user_touched was actually updated
1458 protected function checkAndSetTouched() {
1461 if ( !$this->mId
) {
1462 return false; // anon
1465 // Get a new user_touched that is higher than the old one
1466 $oldTouched = $this->mTouched
;
1467 $newTouched = $this->newTouchedTimestamp();
1469 $dbw = wfGetDB( DB_MASTER
);
1470 $dbw->update( 'user',
1471 [ 'user_touched' => $dbw->timestamp( $newTouched ) ],
1473 'user_id' => $this->mId
,
1474 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
1478 $success = ( $dbw->affectedRows() > 0 );
1481 $this->mTouched
= $newTouched;
1482 $this->clearSharedCache();
1484 // Clears on failure too since that is desired if the cache is stale
1485 $this->clearSharedCache( 'refresh' );
1492 * Clear various cached data stored in this object. The cache of the user table
1493 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1495 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1496 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1498 public function clearInstanceCache( $reloadFrom = false ) {
1499 $this->mNewtalk
= -1;
1500 $this->mDatePreference
= null;
1501 $this->mBlockedby
= -1; # Unset
1502 $this->mHash
= false;
1503 $this->mRights
= null;
1504 $this->mEffectiveGroups
= null;
1505 $this->mImplicitGroups
= null;
1506 $this->mGroups
= null;
1507 $this->mOptions
= null;
1508 $this->mOptionsLoaded
= false;
1509 $this->mEditCount
= null;
1511 if ( $reloadFrom ) {
1512 $this->mLoadedItems
= [];
1513 $this->mFrom
= $reloadFrom;
1518 * Combine the language default options with any site-specific options
1519 * and add the default language variants.
1521 * @return array Array of String options
1523 public static function getDefaultOptions() {
1524 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1526 static $defOpt = null;
1527 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1528 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1529 // mid-request and see that change reflected in the return value of this function.
1530 // Which is insane and would never happen during normal MW operation
1534 $defOpt = $wgDefaultUserOptions;
1535 // Default language setting
1536 $defOpt['language'] = $wgContLang->getCode();
1537 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1538 $defOpt[$langCode == $wgContLang->getCode() ?
'variant' : "variant-$langCode"] = $langCode;
1540 $namespaces = MediaWikiServices
::getInstance()->getSearchEngineConfig()->searchableNamespaces();
1541 foreach ( $namespaces as $nsnum => $nsname ) {
1542 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1544 $defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1546 Hooks
::run( 'UserGetDefaultOptions', [ &$defOpt ] );
1552 * Get a given default option value.
1554 * @param string $opt Name of option to retrieve
1555 * @return string Default option value
1557 public static function getDefaultOption( $opt ) {
1558 $defOpts = self
::getDefaultOptions();
1559 if ( isset( $defOpts[$opt] ) ) {
1560 return $defOpts[$opt];
1567 * Get blocking information
1568 * @param bool $bFromSlave Whether to check the slave database first.
1569 * To improve performance, non-critical checks are done against slaves.
1570 * Check when actually saving should be done against master.
1572 private function getBlockedStatus( $bFromSlave = true ) {
1573 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1575 if ( -1 != $this->mBlockedby
) {
1579 wfDebug( __METHOD__
. ": checking...\n" );
1581 // Initialize data...
1582 // Otherwise something ends up stomping on $this->mBlockedby when
1583 // things get lazy-loaded later, causing false positive block hits
1584 // due to -1 !== 0. Probably session-related... Nothing should be
1585 // overwriting mBlockedby, surely?
1588 # We only need to worry about passing the IP address to the Block generator if the
1589 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1590 # know which IP address they're actually coming from
1592 if ( !$this->isAllowed( 'ipblock-exempt' ) ) {
1593 // $wgUser->getName() only works after the end of Setup.php. Until
1594 // then, assume it's a logged-out user.
1595 $globalUserName = $wgUser->isSafeToLoad()
1596 ?
$wgUser->getName()
1597 : IP
::sanitizeIP( $wgUser->getRequest()->getIP() );
1598 if ( $this->getName() === $globalUserName ) {
1599 $ip = $this->getRequest()->getIP();
1604 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1607 if ( !$block instanceof Block
&& $ip !== null && !in_array( $ip, $wgProxyWhitelist ) ) {
1609 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1611 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1612 $block->mReason
= wfMessage( 'proxyblockreason' )->text();
1613 $block->setTarget( $ip );
1614 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1616 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1617 $block->mReason
= wfMessage( 'sorbsreason' )->text();
1618 $block->setTarget( $ip );
1622 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1623 if ( !$block instanceof Block
1624 && $wgApplyIpBlocksToXff
1626 && !in_array( $ip, $wgProxyWhitelist )
1628 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1629 $xff = array_map( 'trim', explode( ',', $xff ) );
1630 $xff = array_diff( $xff, [ $ip ] );
1631 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1632 $block = Block
::chooseBlock( $xffblocks, $xff );
1633 if ( $block instanceof Block
) {
1634 # Mangle the reason to alert the user that the block
1635 # originated from matching the X-Forwarded-For header.
1636 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->text();
1640 if ( $block instanceof Block
) {
1641 wfDebug( __METHOD__
. ": Found block.\n" );
1642 $this->mBlock
= $block;
1643 $this->mBlockedby
= $block->getByName();
1644 $this->mBlockreason
= $block->mReason
;
1645 $this->mHideName
= $block->mHideName
;
1646 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1648 $this->mBlockedby
= '';
1649 $this->mHideName
= 0;
1650 $this->mAllowUsertalk
= false;
1654 Hooks
::run( 'GetBlockedStatus', [ &$this ] );
1659 * Whether the given IP is in a DNS blacklist.
1661 * @param string $ip IP to check
1662 * @param bool $checkWhitelist Whether to check the whitelist first
1663 * @return bool True if blacklisted.
1665 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1666 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1668 if ( !$wgEnableDnsBlacklist ) {
1672 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1676 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1680 * Whether the given IP is in a given DNS blacklist.
1682 * @param string $ip IP to check
1683 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1684 * @return bool True if blacklisted.
1686 public function inDnsBlacklist( $ip, $bases ) {
1689 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1690 if ( IP
::isIPv4( $ip ) ) {
1691 // Reverse IP, bug 21255
1692 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1694 foreach ( (array)$bases as $base ) {
1696 // If we have an access key, use that too (ProjectHoneypot, etc.)
1698 if ( is_array( $base ) ) {
1699 if ( count( $base ) >= 2 ) {
1700 // Access key is 1, base URL is 0
1701 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1703 $host = "$ipReversed.{$base[0]}";
1705 $basename = $base[0];
1707 $host = "$ipReversed.$base";
1711 $ipList = gethostbynamel( $host );
1714 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
1718 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
1727 * Check if an IP address is in the local proxy list
1733 public static function isLocallyBlockedProxy( $ip ) {
1734 global $wgProxyList;
1736 if ( !$wgProxyList ) {
1740 if ( !is_array( $wgProxyList ) ) {
1741 // Load from the specified file
1742 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1745 if ( !is_array( $wgProxyList ) ) {
1747 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1749 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1750 // Old-style flipped proxy list
1759 * Is this user subject to rate limiting?
1761 * @return bool True if rate limited
1763 public function isPingLimitable() {
1764 global $wgRateLimitsExcludedIPs;
1765 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1766 // No other good way currently to disable rate limits
1767 // for specific IPs. :P
1768 // But this is a crappy hack and should die.
1771 return !$this->isAllowed( 'noratelimit' );
1775 * Primitive rate limits: enforce maximum actions per time period
1776 * to put a brake on flooding.
1778 * The method generates both a generic profiling point and a per action one
1779 * (suffix being "-$action".
1781 * @note When using a shared cache like memcached, IP-address
1782 * last-hit counters will be shared across wikis.
1784 * @param string $action Action to enforce; 'edit' if unspecified
1785 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1786 * @return bool True if a rate limiter was tripped
1788 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1789 // Call the 'PingLimiter' hook
1791 if ( !Hooks
::run( 'PingLimiter', [ &$this, $action, &$result, $incrBy ] ) ) {
1795 global $wgRateLimits;
1796 if ( !isset( $wgRateLimits[$action] ) ) {
1800 // Some groups shouldn't trigger the ping limiter, ever
1801 if ( !$this->isPingLimitable() ) {
1805 $limits = $wgRateLimits[$action];
1807 $id = $this->getId();
1809 $isNewbie = $this->isNewbie();
1813 if ( isset( $limits['anon'] ) ) {
1814 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1817 // limits for logged-in users
1818 if ( isset( $limits['user'] ) ) {
1819 $userLimit = $limits['user'];
1821 // limits for newbie logged-in users
1822 if ( $isNewbie && isset( $limits['newbie'] ) ) {
1823 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1827 // limits for anons and for newbie logged-in users
1830 if ( isset( $limits['ip'] ) ) {
1831 $ip = $this->getRequest()->getIP();
1832 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1834 // subnet-based limits
1835 if ( isset( $limits['subnet'] ) ) {
1836 $ip = $this->getRequest()->getIP();
1837 $subnet = IP
::getSubnet( $ip );
1838 if ( $subnet !== false ) {
1839 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1844 // Check for group-specific permissions
1845 // If more than one group applies, use the group with the highest limit ratio (max/period)
1846 foreach ( $this->getGroups() as $group ) {
1847 if ( isset( $limits[$group] ) ) {
1848 if ( $userLimit === false
1849 ||
$limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1851 $userLimit = $limits[$group];
1856 // Set the user limit key
1857 if ( $userLimit !== false ) {
1858 list( $max, $period ) = $userLimit;
1859 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
1860 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1863 // ip-based limits for all ping-limitable users
1864 if ( isset( $limits['ip-all'] ) ) {
1865 $ip = $this->getRequest()->getIP();
1866 // ignore if user limit is more permissive
1867 if ( $isNewbie ||
$userLimit === false
1868 ||
$limits['ip-all'][0] / $limits['ip-all'][1] > $userLimit[0] / $userLimit[1] ) {
1869 $keys["mediawiki:limiter:$action:ip-all:$ip"] = $limits['ip-all'];
1873 // subnet-based limits for all ping-limitable users
1874 if ( isset( $limits['subnet-all'] ) ) {
1875 $ip = $this->getRequest()->getIP();
1876 $subnet = IP
::getSubnet( $ip );
1877 if ( $subnet !== false ) {
1878 // ignore if user limit is more permissive
1879 if ( $isNewbie ||
$userLimit === false
1880 ||
$limits['ip-all'][0] / $limits['ip-all'][1]
1881 > $userLimit[0] / $userLimit[1] ) {
1882 $keys["mediawiki:limiter:$action:subnet-all:$subnet"] = $limits['subnet-all'];
1887 $cache = ObjectCache
::getLocalClusterInstance();
1890 foreach ( $keys as $key => $limit ) {
1891 list( $max, $period ) = $limit;
1892 $summary = "(limit $max in {$period}s)";
1893 $count = $cache->get( $key );
1896 if ( $count >= $max ) {
1897 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1898 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1901 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1904 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1905 if ( $incrBy > 0 ) {
1906 $cache->add( $key, 0, intval( $period ) ); // first ping
1909 if ( $incrBy > 0 ) {
1910 $cache->incr( $key, $incrBy );
1918 * Check if user is blocked
1920 * @param bool $bFromSlave Whether to check the slave database instead of
1921 * the master. Hacked from false due to horrible probs on site.
1922 * @return bool True if blocked, false otherwise
1924 public function isBlocked( $bFromSlave = true ) {
1925 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
1929 * Get the block affecting the user, or null if the user is not blocked
1931 * @param bool $bFromSlave Whether to check the slave database instead of the master
1932 * @return Block|null
1934 public function getBlock( $bFromSlave = true ) {
1935 $this->getBlockedStatus( $bFromSlave );
1936 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
1940 * Check if user is blocked from editing a particular article
1942 * @param Title $title Title to check
1943 * @param bool $bFromSlave Whether to check the slave database instead of the master
1946 public function isBlockedFrom( $title, $bFromSlave = false ) {
1947 global $wgBlockAllowsUTEdit;
1949 $blocked = $this->isBlocked( $bFromSlave );
1950 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
1951 // If a user's name is suppressed, they cannot make edits anywhere
1952 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName()
1953 && $title->getNamespace() == NS_USER_TALK
) {
1955 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
1958 Hooks
::run( 'UserIsBlockedFrom', [ $this, $title, &$blocked, &$allowUsertalk ] );
1964 * If user is blocked, return the name of the user who placed the block
1965 * @return string Name of blocker
1967 public function blockedBy() {
1968 $this->getBlockedStatus();
1969 return $this->mBlockedby
;
1973 * If user is blocked, return the specified reason for the block
1974 * @return string Blocking reason
1976 public function blockedFor() {
1977 $this->getBlockedStatus();
1978 return $this->mBlockreason
;
1982 * If user is blocked, return the ID for the block
1983 * @return int Block ID
1985 public function getBlockId() {
1986 $this->getBlockedStatus();
1987 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
1991 * Check if user is blocked on all wikis.
1992 * Do not use for actual edit permission checks!
1993 * This is intended for quick UI checks.
1995 * @param string $ip IP address, uses current client if none given
1996 * @return bool True if blocked, false otherwise
1998 public function isBlockedGlobally( $ip = '' ) {
1999 return $this->getGlobalBlock( $ip ) instanceof Block
;
2003 * Check if user is blocked on all wikis.
2004 * Do not use for actual edit permission checks!
2005 * This is intended for quick UI checks.
2007 * @param string $ip IP address, uses current client if none given
2008 * @return Block|null Block object if blocked, null otherwise
2009 * @throws FatalError
2010 * @throws MWException
2012 public function getGlobalBlock( $ip = '' ) {
2013 if ( $this->mGlobalBlock
!== null ) {
2014 return $this->mGlobalBlock ?
: null;
2016 // User is already an IP?
2017 if ( IP
::isIPAddress( $this->getName() ) ) {
2018 $ip = $this->getName();
2020 $ip = $this->getRequest()->getIP();
2024 Hooks
::run( 'UserIsBlockedGlobally', [ &$this, $ip, &$blocked, &$block ] );
2026 if ( $blocked && $block === null ) {
2027 // back-compat: UserIsBlockedGlobally didn't have $block param first
2029 $block->setTarget( $ip );
2032 $this->mGlobalBlock
= $blocked ?
$block : false;
2033 return $this->mGlobalBlock ?
: null;
2037 * Check if user account is locked
2039 * @return bool True if locked, false otherwise
2041 public function isLocked() {
2042 if ( $this->mLocked
!== null ) {
2043 return $this->mLocked
;
2046 $authUser = $wgAuth->getUserInstance( $this );
2047 $this->mLocked
= (bool)$authUser->isLocked();
2048 Hooks
::run( 'UserIsLocked', [ $this, &$this->mLocked
] );
2049 return $this->mLocked
;
2053 * Check if user account is hidden
2055 * @return bool True if hidden, false otherwise
2057 public function isHidden() {
2058 if ( $this->mHideName
!== null ) {
2059 return $this->mHideName
;
2061 $this->getBlockedStatus();
2062 if ( !$this->mHideName
) {
2064 $authUser = $wgAuth->getUserInstance( $this );
2065 $this->mHideName
= (bool)$authUser->isHidden();
2066 Hooks
::run( 'UserIsHidden', [ $this, &$this->mHideName
] );
2068 return $this->mHideName
;
2072 * Get the user's ID.
2073 * @return int The user's ID; 0 if the user is anonymous or nonexistent
2075 public function getId() {
2076 if ( $this->mId
=== null && $this->mName
!== null && User
::isIP( $this->mName
) ) {
2077 // Special case, we know the user is anonymous
2079 } elseif ( !$this->isItemLoaded( 'id' ) ) {
2080 // Don't load if this was initialized from an ID
2084 return (int)$this->mId
;
2088 * Set the user and reload all fields according to a given ID
2089 * @param int $v User ID to reload
2091 public function setId( $v ) {
2093 $this->clearInstanceCache( 'id' );
2097 * Get the user name, or the IP of an anonymous user
2098 * @return string User's name or IP address
2100 public function getName() {
2101 if ( $this->isItemLoaded( 'name', 'only' ) ) {
2102 // Special case optimisation
2103 return $this->mName
;
2106 if ( $this->mName
=== false ) {
2108 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
2110 return $this->mName
;
2115 * Set the user name.
2117 * This does not reload fields from the database according to the given
2118 * name. Rather, it is used to create a temporary "nonexistent user" for
2119 * later addition to the database. It can also be used to set the IP
2120 * address for an anonymous user to something other than the current
2123 * @note User::newFromName() has roughly the same function, when the named user
2125 * @param string $str New user name to set
2127 public function setName( $str ) {
2129 $this->mName
= $str;
2133 * Get the user's name escaped by underscores.
2134 * @return string Username escaped by underscores.
2136 public function getTitleKey() {
2137 return str_replace( ' ', '_', $this->getName() );
2141 * Check if the user has new messages.
2142 * @return bool True if the user has new messages
2144 public function getNewtalk() {
2147 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2148 if ( $this->mNewtalk
=== -1 ) {
2149 $this->mNewtalk
= false; # reset talk page status
2151 // Check memcached separately for anons, who have no
2152 // entire User object stored in there.
2153 if ( !$this->mId
) {
2154 global $wgDisableAnonTalk;
2155 if ( $wgDisableAnonTalk ) {
2156 // Anon newtalk disabled by configuration.
2157 $this->mNewtalk
= false;
2159 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
2162 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2166 return (bool)$this->mNewtalk
;
2170 * Return the data needed to construct links for new talk page message
2171 * alerts. If there are new messages, this will return an associative array
2172 * with the following data:
2173 * wiki: The database name of the wiki
2174 * link: Root-relative link to the user's talk page
2175 * rev: The last talk page revision that the user has seen or null. This
2176 * is useful for building diff links.
2177 * If there are no new messages, it returns an empty array.
2178 * @note This function was designed to accomodate multiple talk pages, but
2179 * currently only returns a single link and revision.
2182 public function getNewMessageLinks() {
2184 if ( !Hooks
::run( 'UserRetrieveNewTalks', [ &$this, &$talks ] ) ) {
2186 } elseif ( !$this->getNewtalk() ) {
2189 $utp = $this->getTalkPage();
2190 $dbr = wfGetDB( DB_SLAVE
);
2191 // Get the "last viewed rev" timestamp from the oldest message notification
2192 $timestamp = $dbr->selectField( 'user_newtalk',
2193 'MIN(user_last_timestamp)',
2194 $this->isAnon() ?
[ 'user_ip' => $this->getName() ] : [ 'user_id' => $this->getId() ],
2196 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2197 return [ [ 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ] ];
2201 * Get the revision ID for the last talk page revision viewed by the talk
2203 * @return int|null Revision ID or null
2205 public function getNewMessageRevisionId() {
2206 $newMessageRevisionId = null;
2207 $newMessageLinks = $this->getNewMessageLinks();
2208 if ( $newMessageLinks ) {
2209 // Note: getNewMessageLinks() never returns more than a single link
2210 // and it is always for the same wiki, but we double-check here in
2211 // case that changes some time in the future.
2212 if ( count( $newMessageLinks ) === 1
2213 && $newMessageLinks[0]['wiki'] === wfWikiID()
2214 && $newMessageLinks[0]['rev']
2216 /** @var Revision $newMessageRevision */
2217 $newMessageRevision = $newMessageLinks[0]['rev'];
2218 $newMessageRevisionId = $newMessageRevision->getId();
2221 return $newMessageRevisionId;
2225 * Internal uncached check for new messages
2228 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2229 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2230 * @return bool True if the user has new messages
2232 protected function checkNewtalk( $field, $id ) {
2233 $dbr = wfGetDB( DB_SLAVE
);
2235 $ok = $dbr->selectField( 'user_newtalk', $field, [ $field => $id ], __METHOD__
);
2237 return $ok !== false;
2241 * Add or update the new messages flag
2242 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2243 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2244 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2245 * @return bool True if successful, false otherwise
2247 protected function updateNewtalk( $field, $id, $curRev = null ) {
2248 // Get timestamp of the talk page revision prior to the current one
2249 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2250 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2251 // Mark the user as having new messages since this revision
2252 $dbw = wfGetDB( DB_MASTER
);
2253 $dbw->insert( 'user_newtalk',
2254 [ $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ],
2257 if ( $dbw->affectedRows() ) {
2258 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2261 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2267 * Clear the new messages flag for the given user
2268 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2269 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2270 * @return bool True if successful, false otherwise
2272 protected function deleteNewtalk( $field, $id ) {
2273 $dbw = wfGetDB( DB_MASTER
);
2274 $dbw->delete( 'user_newtalk',
2277 if ( $dbw->affectedRows() ) {
2278 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2281 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2287 * Update the 'You have new messages!' status.
2288 * @param bool $val Whether the user has new messages
2289 * @param Revision $curRev New, as yet unseen revision of the user talk
2290 * page. Ignored if null or !$val.
2292 public function setNewtalk( $val, $curRev = null ) {
2293 if ( wfReadOnly() ) {
2298 $this->mNewtalk
= $val;
2300 if ( $this->isAnon() ) {
2302 $id = $this->getName();
2305 $id = $this->getId();
2309 $changed = $this->updateNewtalk( $field, $id, $curRev );
2311 $changed = $this->deleteNewtalk( $field, $id );
2315 $this->invalidateCache();
2320 * Generate a current or new-future timestamp to be stored in the
2321 * user_touched field when we update things.
2322 * @return string Timestamp in TS_MW format
2324 private function newTouchedTimestamp() {
2325 global $wgClockSkewFudge;
2327 $time = wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2328 if ( $this->mTouched
&& $time <= $this->mTouched
) {
2329 $time = wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $this->mTouched
) +
1 );
2336 * Clear user data from memcached
2338 * Use after applying updates to the database; caller's
2339 * responsibility to update user_touched if appropriate.
2341 * Called implicitly from invalidateCache() and saveSettings().
2343 * @param string $mode Use 'refresh' to clear now; otherwise before DB commit
2345 public function clearSharedCache( $mode = 'changed' ) {
2346 if ( !$this->getId() ) {
2350 $cache = ObjectCache
::getMainWANInstance();
2351 $processCache = self
::getInProcessCache();
2352 $key = $this->getCacheKey( $cache );
2353 if ( $mode === 'refresh' ) {
2354 $cache->delete( $key, 1 );
2355 $processCache->delete( $key );
2357 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle(
2358 function() use ( $cache, $processCache, $key ) {
2359 $cache->delete( $key );
2360 $processCache->delete( $key );
2367 * Immediately touch the user data cache for this account
2369 * Calls touch() and removes account data from memcached
2371 public function invalidateCache() {
2373 $this->clearSharedCache();
2377 * Update the "touched" timestamp for the user
2379 * This is useful on various login/logout events when making sure that
2380 * a browser or proxy that has multiple tenants does not suffer cache
2381 * pollution where the new user sees the old users content. The value
2382 * of getTouched() is checked when determining 304 vs 200 responses.
2383 * Unlike invalidateCache(), this preserves the User object cache and
2384 * avoids database writes.
2388 public function touch() {
2389 $id = $this->getId();
2391 $key = wfMemcKey( 'user-quicktouched', 'id', $id );
2392 ObjectCache
::getMainWANInstance()->touchCheckKey( $key );
2393 $this->mQuickTouched
= null;
2398 * Validate the cache for this account.
2399 * @param string $timestamp A timestamp in TS_MW format
2402 public function validateCache( $timestamp ) {
2403 return ( $timestamp >= $this->getTouched() );
2407 * Get the user touched timestamp
2409 * Use this value only to validate caches via inequalities
2410 * such as in the case of HTTP If-Modified-Since response logic
2412 * @return string TS_MW Timestamp
2414 public function getTouched() {
2418 if ( $this->mQuickTouched
=== null ) {
2419 $key = wfMemcKey( 'user-quicktouched', 'id', $this->mId
);
2420 $cache = ObjectCache
::getMainWANInstance();
2422 $this->mQuickTouched
= wfTimestamp( TS_MW
, $cache->getCheckKeyTime( $key ) );
2425 return max( $this->mTouched
, $this->mQuickTouched
);
2428 return $this->mTouched
;
2432 * Get the user_touched timestamp field (time of last DB updates)
2433 * @return string TS_MW Timestamp
2436 public function getDBTouched() {
2439 return $this->mTouched
;
2443 * @deprecated Removed in 1.27.
2447 public function getPassword() {
2448 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2452 * @deprecated Removed in 1.27.
2456 public function getTemporaryPassword() {
2457 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2461 * Set the password and reset the random token.
2462 * Calls through to authentication plugin if necessary;
2463 * will have no effect if the auth plugin refuses to
2464 * pass the change through or if the legal password
2467 * As a special case, setting the password to null
2468 * wipes it, so the account cannot be logged in until
2469 * a new password is set, for instance via e-mail.
2471 * @deprecated since 1.27. AuthManager is coming.
2472 * @param string $str New password to set
2473 * @throws PasswordError On failure
2476 public function setPassword( $str ) {
2479 if ( $str !== null ) {
2480 if ( !$wgAuth->allowPasswordChange() ) {
2481 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2484 $status = $this->checkPasswordValidity( $str );
2485 if ( !$status->isGood() ) {
2486 throw new PasswordError( $status->getMessage()->text() );
2490 if ( !$wgAuth->setPassword( $this, $str ) ) {
2491 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2494 $this->setOption( 'watchlisttoken', false );
2495 $this->setPasswordInternal( $str );
2496 SessionManager
::singleton()->invalidateSessionsForUser( $this );
2502 * Set the password and reset the random token unconditionally.
2504 * @deprecated since 1.27. AuthManager is coming.
2505 * @param string|null $str New password to set or null to set an invalid
2506 * password hash meaning that the user will not be able to log in
2507 * through the web interface.
2509 public function setInternalPassword( $str ) {
2512 if ( $wgAuth->allowSetLocalPassword() ) {
2513 $this->setOption( 'watchlisttoken', false );
2514 $this->setPasswordInternal( $str );
2515 SessionManager
::singleton()->invalidateSessionsForUser( $this );
2520 * Actually set the password and such
2521 * @since 1.27 cannot set a password for a user not in the database
2522 * @param string|null $str New password to set or null to set an invalid
2523 * password hash meaning that the user will not be able to log in
2524 * through the web interface.
2526 private function setPasswordInternal( $str ) {
2527 $id = self
::idFromName( $this->getName(), self
::READ_LATEST
);
2529 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2532 $passwordFactory = new PasswordFactory();
2533 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
2534 $dbw = wfGetDB( DB_MASTER
);
2538 'user_password' => $passwordFactory->newFromPlaintext( $str )->toString(),
2539 'user_newpassword' => PasswordFactory
::newInvalidPassword()->toString(),
2540 'user_newpass_time' => $dbw->timestampOrNull( null ),
2548 // When the main password is changed, invalidate all bot passwords too
2549 BotPassword
::invalidateAllPasswordsForUser( $this->getName() );
2553 * Get the user's current token.
2554 * @param bool $forceCreation Force the generation of a new token if the
2555 * user doesn't have one (default=true for backwards compatibility).
2556 * @return string|null Token
2558 public function getToken( $forceCreation = true ) {
2559 global $wgAuthenticationTokenVersion;
2562 if ( !$this->mToken
&& $forceCreation ) {
2566 if ( !$this->mToken
) {
2567 // The user doesn't have a token, return null to indicate that.
2569 } elseif ( $this->mToken
=== self
::INVALID_TOKEN
) {
2570 // We return a random value here so existing token checks are very
2572 return MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2573 } elseif ( $wgAuthenticationTokenVersion === null ) {
2574 // $wgAuthenticationTokenVersion not in use, so return the raw secret
2575 return $this->mToken
;
2577 // $wgAuthenticationTokenVersion in use, so hmac it.
2578 $ret = MWCryptHash
::hmac( $wgAuthenticationTokenVersion, $this->mToken
, false );
2580 // The raw hash can be overly long. Shorten it up.
2581 $len = max( 32, self
::TOKEN_LENGTH
);
2582 if ( strlen( $ret ) < $len ) {
2583 // Should never happen, even md5 is 128 bits
2584 throw new \
UnexpectedValueException( 'Hmac returned less than 128 bits' );
2586 return substr( $ret, -$len );
2591 * Set the random token (used for persistent authentication)
2592 * Called from loadDefaults() among other places.
2594 * @param string|bool $token If specified, set the token to this value
2596 public function setToken( $token = false ) {
2598 if ( $this->mToken
=== self
::INVALID_TOKEN
) {
2599 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
2600 ->debug( __METHOD__
. ": Ignoring attempt to set token for system user \"$this\"" );
2601 } elseif ( !$token ) {
2602 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2604 $this->mToken
= $token;
2609 * Set the password for a password reminder or new account email
2611 * @deprecated since 1.27, AuthManager is coming
2612 * @param string $str New password to set or null to set an invalid
2613 * password hash meaning that the user will not be able to use it
2614 * @param bool $throttle If true, reset the throttle timestamp to the present
2616 public function setNewpassword( $str, $throttle = true ) {
2617 $id = $this->getId();
2619 throw new LogicException( 'Cannot set new password for a user that is not in the database.' );
2622 $dbw = wfGetDB( DB_MASTER
);
2624 $passwordFactory = new PasswordFactory();
2625 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
2627 'user_newpassword' => $passwordFactory->newFromPlaintext( $str )->toString(),
2630 if ( $str === null ) {
2631 $update['user_newpass_time'] = null;
2632 } elseif ( $throttle ) {
2633 $update['user_newpass_time'] = $dbw->timestamp();
2636 $dbw->update( 'user', $update, [ 'user_id' => $id ], __METHOD__
);
2640 * Has password reminder email been sent within the last
2641 * $wgPasswordReminderResendTime hours?
2644 public function isPasswordReminderThrottled() {
2645 global $wgPasswordReminderResendTime;
2647 if ( !$wgPasswordReminderResendTime ) {
2653 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
2654 ?
wfGetDB( DB_MASTER
)
2655 : wfGetDB( DB_SLAVE
);
2656 $newpassTime = $db->selectField(
2658 'user_newpass_time',
2659 [ 'user_id' => $this->getId() ],
2663 if ( $newpassTime === null ) {
2666 $expiry = wfTimestamp( TS_UNIX
, $newpassTime ) +
$wgPasswordReminderResendTime * 3600;
2667 return time() < $expiry;
2671 * Get the user's e-mail address
2672 * @return string User's email address
2674 public function getEmail() {
2676 Hooks
::run( 'UserGetEmail', [ $this, &$this->mEmail
] );
2677 return $this->mEmail
;
2681 * Get the timestamp of the user's e-mail authentication
2682 * @return string TS_MW timestamp
2684 public function getEmailAuthenticationTimestamp() {
2686 Hooks
::run( 'UserGetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
2687 return $this->mEmailAuthenticated
;
2691 * Set the user's e-mail address
2692 * @param string $str New e-mail address
2694 public function setEmail( $str ) {
2696 if ( $str == $this->mEmail
) {
2699 $this->invalidateEmail();
2700 $this->mEmail
= $str;
2701 Hooks
::run( 'UserSetEmail', [ $this, &$this->mEmail
] );
2705 * Set the user's e-mail address and a confirmation mail if needed.
2708 * @param string $str New e-mail address
2711 public function setEmailWithConfirmation( $str ) {
2712 global $wgEnableEmail, $wgEmailAuthentication;
2714 if ( !$wgEnableEmail ) {
2715 return Status
::newFatal( 'emaildisabled' );
2718 $oldaddr = $this->getEmail();
2719 if ( $str === $oldaddr ) {
2720 return Status
::newGood( true );
2723 $type = $oldaddr != '' ?
'changed' : 'set';
2724 $notificationResult = null;
2726 if ( $wgEmailAuthentication ) {
2727 // Send the user an email notifying the user of the change in registered
2728 // email address on their previous email address
2729 if ( $type == 'changed' ) {
2730 $change = $str != '' ?
'changed' : 'removed';
2731 $notificationResult = $this->sendMail(
2732 wfMessage( 'notificationemail_subject_' . $change )->text(),
2733 wfMessage( 'notificationemail_body_' . $change,
2734 $this->getRequest()->getIP(),
2741 $this->setEmail( $str );
2743 if ( $str !== '' && $wgEmailAuthentication ) {
2744 // Send a confirmation request to the new address if needed
2745 $result = $this->sendConfirmationMail( $type );
2747 if ( $notificationResult !== null ) {
2748 $result->merge( $notificationResult );
2751 if ( $result->isGood() ) {
2752 // Say to the caller that a confirmation and notification mail has been sent
2753 $result->value
= 'eauth';
2756 $result = Status
::newGood( true );
2763 * Get the user's real name
2764 * @return string User's real name
2766 public function getRealName() {
2767 if ( !$this->isItemLoaded( 'realname' ) ) {
2771 return $this->mRealName
;
2775 * Set the user's real name
2776 * @param string $str New real name
2778 public function setRealName( $str ) {
2780 $this->mRealName
= $str;
2784 * Get the user's current setting for a given option.
2786 * @param string $oname The option to check
2787 * @param string $defaultOverride A default value returned if the option does not exist
2788 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2789 * @return string User's current value for the option
2790 * @see getBoolOption()
2791 * @see getIntOption()
2793 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2794 global $wgHiddenPrefs;
2795 $this->loadOptions();
2797 # We want 'disabled' preferences to always behave as the default value for
2798 # users, even if they have set the option explicitly in their settings (ie they
2799 # set it, and then it was disabled removing their ability to change it). But
2800 # we don't want to erase the preferences in the database in case the preference
2801 # is re-enabled again. So don't touch $mOptions, just override the returned value
2802 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2803 return self
::getDefaultOption( $oname );
2806 if ( array_key_exists( $oname, $this->mOptions
) ) {
2807 return $this->mOptions
[$oname];
2809 return $defaultOverride;
2814 * Get all user's options
2816 * @param int $flags Bitwise combination of:
2817 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2818 * to the default value. (Since 1.25)
2821 public function getOptions( $flags = 0 ) {
2822 global $wgHiddenPrefs;
2823 $this->loadOptions();
2824 $options = $this->mOptions
;
2826 # We want 'disabled' preferences to always behave as the default value for
2827 # users, even if they have set the option explicitly in their settings (ie they
2828 # set it, and then it was disabled removing their ability to change it). But
2829 # we don't want to erase the preferences in the database in case the preference
2830 # is re-enabled again. So don't touch $mOptions, just override the returned value
2831 foreach ( $wgHiddenPrefs as $pref ) {
2832 $default = self
::getDefaultOption( $pref );
2833 if ( $default !== null ) {
2834 $options[$pref] = $default;
2838 if ( $flags & self
::GETOPTIONS_EXCLUDE_DEFAULTS
) {
2839 $options = array_diff_assoc( $options, self
::getDefaultOptions() );
2846 * Get the user's current setting for a given option, as a boolean value.
2848 * @param string $oname The option to check
2849 * @return bool User's current value for the option
2852 public function getBoolOption( $oname ) {
2853 return (bool)$this->getOption( $oname );
2857 * Get the user's current setting for a given option, as an integer value.
2859 * @param string $oname The option to check
2860 * @param int $defaultOverride A default value returned if the option does not exist
2861 * @return int User's current value for the option
2864 public function getIntOption( $oname, $defaultOverride = 0 ) {
2865 $val = $this->getOption( $oname );
2867 $val = $defaultOverride;
2869 return intval( $val );
2873 * Set the given option for a user.
2875 * You need to call saveSettings() to actually write to the database.
2877 * @param string $oname The option to set
2878 * @param mixed $val New value to set
2880 public function setOption( $oname, $val ) {
2881 $this->loadOptions();
2883 // Explicitly NULL values should refer to defaults
2884 if ( is_null( $val ) ) {
2885 $val = self
::getDefaultOption( $oname );
2888 $this->mOptions
[$oname] = $val;
2892 * Get a token stored in the preferences (like the watchlist one),
2893 * resetting it if it's empty (and saving changes).
2895 * @param string $oname The option name to retrieve the token from
2896 * @return string|bool User's current value for the option, or false if this option is disabled.
2897 * @see resetTokenFromOption()
2899 * @deprecated 1.26 Applications should use the OAuth extension
2901 public function getTokenFromOption( $oname ) {
2902 global $wgHiddenPrefs;
2904 $id = $this->getId();
2905 if ( !$id ||
in_array( $oname, $wgHiddenPrefs ) ) {
2909 $token = $this->getOption( $oname );
2911 // Default to a value based on the user token to avoid space
2912 // wasted on storing tokens for all users. When this option
2913 // is set manually by the user, only then is it stored.
2914 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
2921 * Reset a token stored in the preferences (like the watchlist one).
2922 * *Does not* save user's preferences (similarly to setOption()).
2924 * @param string $oname The option name to reset the token in
2925 * @return string|bool New token value, or false if this option is disabled.
2926 * @see getTokenFromOption()
2929 public function resetTokenFromOption( $oname ) {
2930 global $wgHiddenPrefs;
2931 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2935 $token = MWCryptRand
::generateHex( 40 );
2936 $this->setOption( $oname, $token );
2941 * Return a list of the types of user options currently returned by
2942 * User::getOptionKinds().
2944 * Currently, the option kinds are:
2945 * - 'registered' - preferences which are registered in core MediaWiki or
2946 * by extensions using the UserGetDefaultOptions hook.
2947 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2948 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2949 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2950 * be used by user scripts.
2951 * - 'special' - "preferences" that are not accessible via User::getOptions
2952 * or User::setOptions.
2953 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2954 * These are usually legacy options, removed in newer versions.
2956 * The API (and possibly others) use this function to determine the possible
2957 * option types for validation purposes, so make sure to update this when a
2958 * new option kind is added.
2960 * @see User::getOptionKinds
2961 * @return array Option kinds
2963 public static function listOptionKinds() {
2966 'registered-multiselect',
2967 'registered-checkmatrix',
2975 * Return an associative array mapping preferences keys to the kind of a preference they're
2976 * used for. Different kinds are handled differently when setting or reading preferences.
2978 * See User::listOptionKinds for the list of valid option types that can be provided.
2980 * @see User::listOptionKinds
2981 * @param IContextSource $context
2982 * @param array $options Assoc. array with options keys to check as keys.
2983 * Defaults to $this->mOptions.
2984 * @return array The key => kind mapping data
2986 public function getOptionKinds( IContextSource
$context, $options = null ) {
2987 $this->loadOptions();
2988 if ( $options === null ) {
2989 $options = $this->mOptions
;
2992 $prefs = Preferences
::getPreferences( $this, $context );
2995 // Pull out the "special" options, so they don't get converted as
2996 // multiselect or checkmatrix.
2997 $specialOptions = array_fill_keys( Preferences
::getSaveBlacklist(), true );
2998 foreach ( $specialOptions as $name => $value ) {
2999 unset( $prefs[$name] );
3002 // Multiselect and checkmatrix options are stored in the database with
3003 // one key per option, each having a boolean value. Extract those keys.
3004 $multiselectOptions = [];
3005 foreach ( $prefs as $name => $info ) {
3006 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
3007 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
3008 $opts = HTMLFormField
::flattenOptions( $info['options'] );
3009 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
3011 foreach ( $opts as $value ) {
3012 $multiselectOptions["$prefix$value"] = true;
3015 unset( $prefs[$name] );
3018 $checkmatrixOptions = [];
3019 foreach ( $prefs as $name => $info ) {
3020 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
3021 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
3022 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
3023 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
3024 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
3026 foreach ( $columns as $column ) {
3027 foreach ( $rows as $row ) {
3028 $checkmatrixOptions["$prefix$column-$row"] = true;
3032 unset( $prefs[$name] );
3036 // $value is ignored
3037 foreach ( $options as $key => $value ) {
3038 if ( isset( $prefs[$key] ) ) {
3039 $mapping[$key] = 'registered';
3040 } elseif ( isset( $multiselectOptions[$key] ) ) {
3041 $mapping[$key] = 'registered-multiselect';
3042 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
3043 $mapping[$key] = 'registered-checkmatrix';
3044 } elseif ( isset( $specialOptions[$key] ) ) {
3045 $mapping[$key] = 'special';
3046 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
3047 $mapping[$key] = 'userjs';
3049 $mapping[$key] = 'unused';
3057 * Reset certain (or all) options to the site defaults
3059 * The optional parameter determines which kinds of preferences will be reset.
3060 * Supported values are everything that can be reported by getOptionKinds()
3061 * and 'all', which forces a reset of *all* preferences and overrides everything else.
3063 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
3064 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
3065 * for backwards-compatibility.
3066 * @param IContextSource|null $context Context source used when $resetKinds
3067 * does not contain 'all', passed to getOptionKinds().
3068 * Defaults to RequestContext::getMain() when null.
3070 public function resetOptions(
3071 $resetKinds = [ 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ],
3072 IContextSource
$context = null
3075 $defaultOptions = self
::getDefaultOptions();
3077 if ( !is_array( $resetKinds ) ) {
3078 $resetKinds = [ $resetKinds ];
3081 if ( in_array( 'all', $resetKinds ) ) {
3082 $newOptions = $defaultOptions;
3084 if ( $context === null ) {
3085 $context = RequestContext
::getMain();
3088 $optionKinds = $this->getOptionKinds( $context );
3089 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
3092 // Use default values for the options that should be deleted, and
3093 // copy old values for the ones that shouldn't.
3094 foreach ( $this->mOptions
as $key => $value ) {
3095 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
3096 if ( array_key_exists( $key, $defaultOptions ) ) {
3097 $newOptions[$key] = $defaultOptions[$key];
3100 $newOptions[$key] = $value;
3105 Hooks
::run( 'UserResetAllOptions', [ $this, &$newOptions, $this->mOptions
, $resetKinds ] );
3107 $this->mOptions
= $newOptions;
3108 $this->mOptionsLoaded
= true;
3112 * Get the user's preferred date format.
3113 * @return string User's preferred date format
3115 public function getDatePreference() {
3116 // Important migration for old data rows
3117 if ( is_null( $this->mDatePreference
) ) {
3119 $value = $this->getOption( 'date' );
3120 $map = $wgLang->getDatePreferenceMigrationMap();
3121 if ( isset( $map[$value] ) ) {
3122 $value = $map[$value];
3124 $this->mDatePreference
= $value;
3126 return $this->mDatePreference
;
3130 * Determine based on the wiki configuration and the user's options,
3131 * whether this user must be over HTTPS no matter what.
3135 public function requiresHTTPS() {
3136 global $wgSecureLogin;
3137 if ( !$wgSecureLogin ) {
3140 $https = $this->getBoolOption( 'prefershttps' );
3141 Hooks
::run( 'UserRequiresHTTPS', [ $this, &$https ] );
3143 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
3150 * Get the user preferred stub threshold
3154 public function getStubThreshold() {
3155 global $wgMaxArticleSize; # Maximum article size, in Kb
3156 $threshold = $this->getIntOption( 'stubthreshold' );
3157 if ( $threshold > $wgMaxArticleSize * 1024 ) {
3158 // If they have set an impossible value, disable the preference
3159 // so we can use the parser cache again.
3166 * Get the permissions this user has.
3167 * @return array Array of String permission names
3169 public function getRights() {
3170 if ( is_null( $this->mRights
) ) {
3171 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
3173 // Deny any rights denied by the user's session, unless this
3174 // endpoint has no sessions.
3175 if ( !defined( 'MW_NO_SESSION' ) ) {
3176 $allowedRights = $this->getRequest()->getSession()->getAllowedUserRights();
3177 if ( $allowedRights !== null ) {
3178 $this->mRights
= array_intersect( $this->mRights
, $allowedRights );
3182 Hooks
::run( 'UserGetRights', [ $this, &$this->mRights
] );
3183 // Force reindexation of rights when a hook has unset one of them
3184 $this->mRights
= array_values( array_unique( $this->mRights
) );
3186 return $this->mRights
;
3190 * Get the list of explicit group memberships this user has.
3191 * The implicit * and user groups are not included.
3192 * @return array Array of String internal group names
3194 public function getGroups() {
3196 $this->loadGroups();
3197 return $this->mGroups
;
3201 * Get the list of implicit group memberships this user has.
3202 * This includes all explicit groups, plus 'user' if logged in,
3203 * '*' for all accounts, and autopromoted groups
3204 * @param bool $recache Whether to avoid the cache
3205 * @return array Array of String internal group names
3207 public function getEffectiveGroups( $recache = false ) {
3208 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
3209 $this->mEffectiveGroups
= array_unique( array_merge(
3210 $this->getGroups(), // explicit groups
3211 $this->getAutomaticGroups( $recache ) // implicit groups
3213 // Hook for additional groups
3214 Hooks
::run( 'UserEffectiveGroups', [ &$this, &$this->mEffectiveGroups
] );
3215 // Force reindexation of groups when a hook has unset one of them
3216 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
3218 return $this->mEffectiveGroups
;
3222 * Get the list of implicit group memberships this user has.
3223 * This includes 'user' if logged in, '*' for all accounts,
3224 * and autopromoted groups
3225 * @param bool $recache Whether to avoid the cache
3226 * @return array Array of String internal group names
3228 public function getAutomaticGroups( $recache = false ) {
3229 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
3230 $this->mImplicitGroups
= [ '*' ];
3231 if ( $this->getId() ) {
3232 $this->mImplicitGroups
[] = 'user';
3234 $this->mImplicitGroups
= array_unique( array_merge(
3235 $this->mImplicitGroups
,
3236 Autopromote
::getAutopromoteGroups( $this )
3240 // Assure data consistency with rights/groups,
3241 // as getEffectiveGroups() depends on this function
3242 $this->mEffectiveGroups
= null;
3245 return $this->mImplicitGroups
;
3249 * Returns the groups the user has belonged to.
3251 * The user may still belong to the returned groups. Compare with getGroups().
3253 * The function will not return groups the user had belonged to before MW 1.17
3255 * @return array Names of the groups the user has belonged to.
3257 public function getFormerGroups() {
3260 if ( is_null( $this->mFormerGroups
) ) {
3261 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3262 ?
wfGetDB( DB_MASTER
)
3263 : wfGetDB( DB_SLAVE
);
3264 $res = $db->select( 'user_former_groups',
3266 [ 'ufg_user' => $this->mId
],
3268 $this->mFormerGroups
= [];
3269 foreach ( $res as $row ) {
3270 $this->mFormerGroups
[] = $row->ufg_group
;
3274 return $this->mFormerGroups
;
3278 * Get the user's edit count.
3279 * @return int|null Null for anonymous users
3281 public function getEditCount() {
3282 if ( !$this->getId() ) {
3286 if ( $this->mEditCount
=== null ) {
3287 /* Populate the count, if it has not been populated yet */
3288 $dbr = wfGetDB( DB_SLAVE
);
3289 // check if the user_editcount field has been initialized
3290 $count = $dbr->selectField(
3291 'user', 'user_editcount',
3292 [ 'user_id' => $this->mId
],
3296 if ( $count === null ) {
3297 // it has not been initialized. do so.
3298 $count = $this->initEditCount();
3300 $this->mEditCount
= $count;
3302 return (int)$this->mEditCount
;
3306 * Add the user to the given group.
3307 * This takes immediate effect.
3308 * @param string $group Name of the group to add
3311 public function addGroup( $group ) {
3314 if ( !Hooks
::run( 'UserAddGroup', [ $this, &$group ] ) ) {
3318 $dbw = wfGetDB( DB_MASTER
);
3319 if ( $this->getId() ) {
3320 $dbw->insert( 'user_groups',
3322 'ug_user' => $this->getId(),
3323 'ug_group' => $group,
3329 $this->loadGroups();
3330 $this->mGroups
[] = $group;
3331 // In case loadGroups was not called before, we now have the right twice.
3332 // Get rid of the duplicate.
3333 $this->mGroups
= array_unique( $this->mGroups
);
3335 // Refresh the groups caches, and clear the rights cache so it will be
3336 // refreshed on the next call to $this->getRights().
3337 $this->getEffectiveGroups( true );
3338 $this->mRights
= null;
3340 $this->invalidateCache();
3346 * Remove the user from the given group.
3347 * This takes immediate effect.
3348 * @param string $group Name of the group to remove
3351 public function removeGroup( $group ) {
3353 if ( !Hooks
::run( 'UserRemoveGroup', [ $this, &$group ] ) ) {
3357 $dbw = wfGetDB( DB_MASTER
);
3358 $dbw->delete( 'user_groups',
3360 'ug_user' => $this->getId(),
3361 'ug_group' => $group,
3364 // Remember that the user was in this group
3365 $dbw->insert( 'user_former_groups',
3367 'ufg_user' => $this->getId(),
3368 'ufg_group' => $group,
3374 $this->loadGroups();
3375 $this->mGroups
= array_diff( $this->mGroups
, [ $group ] );
3377 // Refresh the groups caches, and clear the rights cache so it will be
3378 // refreshed on the next call to $this->getRights().
3379 $this->getEffectiveGroups( true );
3380 $this->mRights
= null;
3382 $this->invalidateCache();
3388 * Get whether the user is logged in
3391 public function isLoggedIn() {
3392 return $this->getId() != 0;
3396 * Get whether the user is anonymous
3399 public function isAnon() {
3400 return !$this->isLoggedIn();
3404 * @return bool Whether this user is flagged as being a bot role account
3407 public function isBot() {
3408 if ( in_array( 'bot', $this->getGroups() ) && $this->isAllowed( 'bot' ) ) {
3413 Hooks
::run( "UserIsBot", [ $this, &$isBot ] );
3419 * Check if user is allowed to access a feature / make an action
3421 * @param string ... Permissions to test
3422 * @return bool True if user is allowed to perform *any* of the given actions
3424 public function isAllowedAny() {
3425 $permissions = func_get_args();
3426 foreach ( $permissions as $permission ) {
3427 if ( $this->isAllowed( $permission ) ) {
3436 * @param string ... Permissions to test
3437 * @return bool True if the user is allowed to perform *all* of the given actions
3439 public function isAllowedAll() {
3440 $permissions = func_get_args();
3441 foreach ( $permissions as $permission ) {
3442 if ( !$this->isAllowed( $permission ) ) {
3450 * Internal mechanics of testing a permission
3451 * @param string $action
3454 public function isAllowed( $action = '' ) {
3455 if ( $action === '' ) {
3456 return true; // In the spirit of DWIM
3458 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3459 // by misconfiguration: 0 == 'foo'
3460 return in_array( $action, $this->getRights(), true );
3464 * Check whether to enable recent changes patrol features for this user
3465 * @return bool True or false
3467 public function useRCPatrol() {
3468 global $wgUseRCPatrol;
3469 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3473 * Check whether to enable new pages patrol features for this user
3474 * @return bool True or false
3476 public function useNPPatrol() {
3477 global $wgUseRCPatrol, $wgUseNPPatrol;
3479 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3480 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3485 * Check whether to enable new files patrol features for this user
3486 * @return bool True or false
3488 public function useFilePatrol() {
3489 global $wgUseRCPatrol, $wgUseFilePatrol;
3491 ( $wgUseRCPatrol ||
$wgUseFilePatrol )
3492 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3497 * Get the WebRequest object to use with this object
3499 * @return WebRequest
3501 public function getRequest() {
3502 if ( $this->mRequest
) {
3503 return $this->mRequest
;
3511 * Check the watched status of an article.
3512 * @since 1.22 $checkRights parameter added
3513 * @param Title $title Title of the article to look at
3514 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3515 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3518 public function isWatched( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3519 if ( $title->isWatchable() && ( !$checkRights ||
$this->isAllowed( 'viewmywatchlist' ) ) ) {
3520 return MediaWikiServices
::getInstance()->getWatchedItemStore()->isWatched( $this, $title );
3527 * @since 1.22 $checkRights parameter added
3528 * @param Title $title Title of the article to look at
3529 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3530 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3532 public function addWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3533 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3534 MediaWikiServices
::getInstance()->getWatchedItemStore()->addWatchBatchForUser(
3536 [ $title->getSubjectPage(), $title->getTalkPage() ]
3539 $this->invalidateCache();
3543 * Stop watching an article.
3544 * @since 1.22 $checkRights parameter added
3545 * @param Title $title Title of the article to look at
3546 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3547 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3549 public function removeWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3550 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3551 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
3552 $store->removeWatch( $this, $title->getSubjectPage() );
3553 $store->removeWatch( $this, $title->getTalkPage() );
3555 $this->invalidateCache();
3559 * Clear the user's notification timestamp for the given title.
3560 * If e-notif e-mails are on, they will receive notification mails on
3561 * the next change of the page if it's watched etc.
3562 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3563 * @param Title $title Title of the article to look at
3564 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3566 public function clearNotification( &$title, $oldid = 0 ) {
3567 global $wgUseEnotif, $wgShowUpdatedMarker;
3569 // Do nothing if the database is locked to writes
3570 if ( wfReadOnly() ) {
3574 // Do nothing if not allowed to edit the watchlist
3575 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3579 // If we're working on user's talk page, we should update the talk page message indicator
3580 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3581 if ( !Hooks
::run( 'UserClearNewTalkNotification', [ &$this, $oldid ] ) ) {
3585 // Try to update the DB post-send and only if needed...
3586 DeferredUpdates
::addCallableUpdate( function() use ( $title, $oldid ) {
3587 if ( !$this->getNewtalk() ) {
3588 return; // no notifications to clear
3591 // Delete the last notifications (they stack up)
3592 $this->setNewtalk( false );
3594 // If there is a new, unseen, revision, use its timestamp
3596 ?
$title->getNextRevisionID( $oldid, Title
::GAID_FOR_UPDATE
)
3599 $this->setNewtalk( true, Revision
::newFromId( $nextid ) );
3604 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3608 if ( $this->isAnon() ) {
3609 // Nothing else to do...
3613 // Only update the timestamp if the page is being watched.
3614 // The query to find out if it is watched is cached both in memcached and per-invocation,
3615 // and when it does have to be executed, it can be on a slave
3616 // If this is the user's newtalk page, we always update the timestamp
3618 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3622 MediaWikiServices
::getInstance()->getWatchedItemStore()
3623 ->resetNotificationTimestamp( $this, $title, $force, $oldid );
3627 * Resets all of the given user's page-change notification timestamps.
3628 * If e-notif e-mails are on, they will receive notification mails on
3629 * the next change of any watched page.
3630 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3632 public function clearAllNotifications() {
3633 if ( wfReadOnly() ) {
3637 // Do nothing if not allowed to edit the watchlist
3638 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3642 global $wgUseEnotif, $wgShowUpdatedMarker;
3643 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3644 $this->setNewtalk( false );
3647 $id = $this->getId();
3649 $dbw = wfGetDB( DB_MASTER
);
3650 $dbw->update( 'watchlist',
3651 [ /* SET */ 'wl_notificationtimestamp' => null ],
3652 [ /* WHERE */ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ],
3655 // We also need to clear here the "you have new message" notification for the own user_talk page;
3656 // it's cleared one page view later in WikiPage::doViewUpdates().
3661 * Set a cookie on the user's client. Wrapper for
3662 * WebResponse::setCookie
3663 * @deprecated since 1.27
3664 * @param string $name Name of the cookie to set
3665 * @param string $value Value to set
3666 * @param int $exp Expiration time, as a UNIX time value;
3667 * if 0 or not specified, use the default $wgCookieExpiration
3668 * @param bool $secure
3669 * true: Force setting the secure attribute when setting the cookie
3670 * false: Force NOT setting the secure attribute when setting the cookie
3671 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3672 * @param array $params Array of options sent passed to WebResponse::setcookie()
3673 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3676 protected function setCookie(
3677 $name, $value, $exp = 0, $secure = null, $params = [], $request = null
3679 wfDeprecated( __METHOD__
, '1.27' );
3680 if ( $request === null ) {
3681 $request = $this->getRequest();
3683 $params['secure'] = $secure;
3684 $request->response()->setCookie( $name, $value, $exp, $params );
3688 * Clear a cookie on the user's client
3689 * @deprecated since 1.27
3690 * @param string $name Name of the cookie to clear
3691 * @param bool $secure
3692 * true: Force setting the secure attribute when setting the cookie
3693 * false: Force NOT setting the secure attribute when setting the cookie
3694 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3695 * @param array $params Array of options sent passed to WebResponse::setcookie()
3697 protected function clearCookie( $name, $secure = null, $params = [] ) {
3698 wfDeprecated( __METHOD__
, '1.27' );
3699 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3703 * Set an extended login cookie on the user's client. The expiry of the cookie
3704 * is controlled by the $wgExtendedLoginCookieExpiration configuration
3707 * @see User::setCookie
3709 * @deprecated since 1.27
3710 * @param string $name Name of the cookie to set
3711 * @param string $value Value to set
3712 * @param bool $secure
3713 * true: Force setting the secure attribute when setting the cookie
3714 * false: Force NOT setting the secure attribute when setting the cookie
3715 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3717 protected function setExtendedLoginCookie( $name, $value, $secure ) {
3718 global $wgExtendedLoginCookieExpiration, $wgCookieExpiration;
3720 wfDeprecated( __METHOD__
, '1.27' );
3723 $exp +
= $wgExtendedLoginCookieExpiration !== null
3724 ?
$wgExtendedLoginCookieExpiration
3725 : $wgCookieExpiration;
3727 $this->setCookie( $name, $value, $exp, $secure );
3731 * Persist this user's session (e.g. set cookies)
3733 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3735 * @param bool $secure Whether to force secure/insecure cookies or use default
3736 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3738 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3740 if ( 0 == $this->mId
) {
3744 $session = $this->getRequest()->getSession();
3745 if ( $request && $session->getRequest() !== $request ) {
3746 $session = $session->sessionWithRequest( $request );
3748 $delay = $session->delaySave();
3750 if ( !$session->getUser()->equals( $this ) ) {
3751 if ( !$session->canSetUser() ) {
3752 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3753 ->warning( __METHOD__
.
3754 ": Cannot save user \"$this\" to a user \"{$session->getUser()}\"'s immutable session"
3758 $session->setUser( $this );
3761 $session->setRememberUser( $rememberMe );
3762 if ( $secure !== null ) {
3763 $session->setForceHTTPS( $secure );
3766 $session->persist();
3768 ScopedCallback
::consume( $delay );
3772 * Log this user out.
3774 public function logout() {
3775 if ( Hooks
::run( 'UserLogout', [ &$this ] ) ) {
3781 * Clear the user's session, and reset the instance cache.
3784 public function doLogout() {
3785 $session = $this->getRequest()->getSession();
3786 if ( !$session->canSetUser() ) {
3787 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3788 ->warning( __METHOD__
. ": Cannot log out of an immutable session" );
3789 } elseif ( !$session->getUser()->equals( $this ) ) {
3790 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3791 ->warning( __METHOD__
.
3792 ": Cannot log user \"$this\" out of a user \"{$session->getUser()}\"'s session"
3794 // But we still may as well make this user object anon
3795 $this->clearInstanceCache( 'defaults' );
3797 $this->clearInstanceCache( 'defaults' );
3798 $delay = $session->delaySave();
3799 $session->unpersist(); // Clear cookies (T127436)
3800 $session->setLoggedOutTimestamp( time() );
3801 $session->setUser( new User
);
3802 $session->set( 'wsUserID', 0 ); // Other code expects this
3803 ScopedCallback
::consume( $delay );
3808 * Save this user's settings into the database.
3809 * @todo Only rarely do all these fields need to be set!
3811 public function saveSettings() {
3812 if ( wfReadOnly() ) {
3813 // @TODO: caller should deal with this instead!
3814 // This should really just be an exception.
3815 MWExceptionHandler
::logException( new DBExpectedError(
3817 "Could not update user with ID '{$this->mId}'; DB is read-only."
3823 if ( 0 == $this->mId
) {
3827 // Get a new user_touched that is higher than the old one.
3828 // This will be used for a CAS check as a last-resort safety
3829 // check against race conditions and slave lag.
3830 $oldTouched = $this->mTouched
;
3831 $newTouched = $this->newTouchedTimestamp();
3833 $dbw = wfGetDB( DB_MASTER
);
3834 $dbw->update( 'user',
3836 'user_name' => $this->mName
,
3837 'user_real_name' => $this->mRealName
,
3838 'user_email' => $this->mEmail
,
3839 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3840 'user_touched' => $dbw->timestamp( $newTouched ),
3841 'user_token' => strval( $this->mToken
),
3842 'user_email_token' => $this->mEmailToken
,
3843 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
3845 'user_id' => $this->mId
,
3846 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
3850 if ( !$dbw->affectedRows() ) {
3851 // Maybe the problem was a missed cache update; clear it to be safe
3852 $this->clearSharedCache( 'refresh' );
3853 // User was changed in the meantime or loaded with stale data
3854 $from = ( $this->queryFlagsUsed
& self
::READ_LATEST
) ?
'master' : 'slave';
3855 throw new MWException(
3856 "CAS update failed on user_touched for user ID '{$this->mId}' (read from $from);" .
3857 " the version of the user to be saved is older than the current version."
3861 $this->mTouched
= $newTouched;
3862 $this->saveOptions();
3864 Hooks
::run( 'UserSaveSettings', [ $this ] );
3865 $this->clearSharedCache();
3866 $this->getUserPage()->invalidateCache();
3870 * If only this user's username is known, and it exists, return the user ID.
3872 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
3875 public function idForName( $flags = 0 ) {
3876 $s = trim( $this->getName() );
3881 $db = ( ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
)
3882 ?
wfGetDB( DB_MASTER
)
3883 : wfGetDB( DB_SLAVE
);
3885 $options = ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
)
3886 ?
[ 'LOCK IN SHARE MODE' ]
3889 $id = $db->selectField( 'user',
3890 'user_id', [ 'user_name' => $s ], __METHOD__
, $options );
3896 * Add a user to the database, return the user object
3898 * @param string $name Username to add
3899 * @param array $params Array of Strings Non-default parameters to save to
3900 * the database as user_* fields:
3901 * - email: The user's email address.
3902 * - email_authenticated: The email authentication timestamp.
3903 * - real_name: The user's real name.
3904 * - options: An associative array of non-default options.
3905 * - token: Random authentication token. Do not set.
3906 * - registration: Registration timestamp. Do not set.
3908 * @return User|null User object, or null if the username already exists.
3910 public static function createNew( $name, $params = [] ) {
3911 foreach ( [ 'password', 'newpassword', 'newpass_time', 'password_expires' ] as $field ) {
3912 if ( isset( $params[$field] ) ) {
3913 wfDeprecated( __METHOD__
. " with param '$field'", '1.27' );
3914 unset( $params[$field] );
3920 $user->setToken(); // init token
3921 if ( isset( $params['options'] ) ) {
3922 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
3923 unset( $params['options'] );
3925 $dbw = wfGetDB( DB_MASTER
);
3926 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3928 $noPass = PasswordFactory
::newInvalidPassword()->toString();
3931 'user_id' => $seqVal,
3932 'user_name' => $name,
3933 'user_password' => $noPass,
3934 'user_newpassword' => $noPass,
3935 'user_email' => $user->mEmail
,
3936 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
3937 'user_real_name' => $user->mRealName
,
3938 'user_token' => strval( $user->mToken
),
3939 'user_registration' => $dbw->timestamp( $user->mRegistration
),
3940 'user_editcount' => 0,
3941 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
3943 foreach ( $params as $name => $value ) {
3944 $fields["user_$name"] = $value;
3946 $dbw->insert( 'user', $fields, __METHOD__
, [ 'IGNORE' ] );
3947 if ( $dbw->affectedRows() ) {
3948 $newUser = User
::newFromId( $dbw->insertId() );
3956 * Add this existing user object to the database. If the user already
3957 * exists, a fatal status object is returned, and the user object is
3958 * initialised with the data from the database.
3960 * Previously, this function generated a DB error due to a key conflict
3961 * if the user already existed. Many extension callers use this function
3962 * in code along the lines of:
3964 * $user = User::newFromName( $name );
3965 * if ( !$user->isLoggedIn() ) {
3966 * $user->addToDatabase();
3968 * // do something with $user...
3970 * However, this was vulnerable to a race condition (bug 16020). By
3971 * initialising the user object if the user exists, we aim to support this
3972 * calling sequence as far as possible.
3974 * Note that if the user exists, this function will acquire a write lock,
3975 * so it is still advisable to make the call conditional on isLoggedIn(),
3976 * and to commit the transaction after calling.
3978 * @throws MWException
3981 public function addToDatabase() {
3983 if ( !$this->mToken
) {
3984 $this->setToken(); // init token
3987 $this->mTouched
= $this->newTouchedTimestamp();
3989 $noPass = PasswordFactory
::newInvalidPassword()->toString();
3991 $dbw = wfGetDB( DB_MASTER
);
3992 $inWrite = $dbw->writesOrCallbacksPending();
3993 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3994 $dbw->insert( 'user',
3996 'user_id' => $seqVal,
3997 'user_name' => $this->mName
,
3998 'user_password' => $noPass,
3999 'user_newpassword' => $noPass,
4000 'user_email' => $this->mEmail
,
4001 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
4002 'user_real_name' => $this->mRealName
,
4003 'user_token' => strval( $this->mToken
),
4004 'user_registration' => $dbw->timestamp( $this->mRegistration
),
4005 'user_editcount' => 0,
4006 'user_touched' => $dbw->timestamp( $this->mTouched
),
4010 if ( !$dbw->affectedRows() ) {
4011 // The queries below cannot happen in the same REPEATABLE-READ snapshot.
4012 // Handle this by COMMIT, if possible, or by LOCK IN SHARE MODE otherwise.
4014 // Can't commit due to pending writes that may need atomicity.
4015 // This may cause some lock contention unlike the case below.
4016 $options = [ 'LOCK IN SHARE MODE' ];
4017 $flags = self
::READ_LOCKING
;
4019 // Often, this case happens early in views before any writes when
4020 // using CentralAuth. It's should be OK to commit and break the snapshot.
4021 $dbw->commit( __METHOD__
, 'flush' );
4023 $flags = self
::READ_LATEST
;
4025 $this->mId
= $dbw->selectField( 'user', 'user_id',
4026 [ 'user_name' => $this->mName
], __METHOD__
, $options );
4029 if ( $this->loadFromDatabase( $flags ) ) {
4034 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
4035 "to insert user '{$this->mName}' row, but it was not present in select!" );
4037 return Status
::newFatal( 'userexists' );
4039 $this->mId
= $dbw->insertId();
4040 self
::$idCacheByName[$this->mName
] = $this->mId
;
4042 // Clear instance cache other than user table data, which is already accurate
4043 $this->clearInstanceCache();
4045 $this->saveOptions();
4046 return Status
::newGood();
4050 * If this user is logged-in and blocked,
4051 * block any IP address they've successfully logged in from.
4052 * @return bool A block was spread
4054 public function spreadAnyEditBlock() {
4055 if ( $this->isLoggedIn() && $this->isBlocked() ) {
4056 return $this->spreadBlock();
4063 * If this (non-anonymous) user is blocked,
4064 * block the IP address they've successfully logged in from.
4065 * @return bool A block was spread
4067 protected function spreadBlock() {
4068 wfDebug( __METHOD__
. "()\n" );
4070 if ( $this->mId
== 0 ) {
4074 $userblock = Block
::newFromTarget( $this->getName() );
4075 if ( !$userblock ) {
4079 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
4083 * Get whether the user is explicitly blocked from account creation.
4084 * @return bool|Block
4086 public function isBlockedFromCreateAccount() {
4087 $this->getBlockedStatus();
4088 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
4089 return $this->mBlock
;
4092 # bug 13611: if the IP address the user is trying to create an account from is
4093 # blocked with createaccount disabled, prevent new account creation there even
4094 # when the user is logged in
4095 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
4096 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
4098 return $this->mBlockedFromCreateAccount
instanceof Block
4099 && $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
4100 ?
$this->mBlockedFromCreateAccount
4105 * Get whether the user is blocked from using Special:Emailuser.
4108 public function isBlockedFromEmailuser() {
4109 $this->getBlockedStatus();
4110 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
4114 * Get whether the user is allowed to create an account.
4117 public function isAllowedToCreateAccount() {
4118 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
4122 * Get this user's personal page title.
4124 * @return Title User's personal page title
4126 public function getUserPage() {
4127 return Title
::makeTitle( NS_USER
, $this->getName() );
4131 * Get this user's talk page title.
4133 * @return Title User's talk page title
4135 public function getTalkPage() {
4136 $title = $this->getUserPage();
4137 return $title->getTalkPage();
4141 * Determine whether the user is a newbie. Newbies are either
4142 * anonymous IPs, or the most recently created accounts.
4145 public function isNewbie() {
4146 return !$this->isAllowed( 'autoconfirmed' );
4150 * Check to see if the given clear-text password is one of the accepted passwords
4151 * @deprecated since 1.27. AuthManager is coming.
4152 * @param string $password User password
4153 * @return bool True if the given password is correct, otherwise False
4155 public function checkPassword( $password ) {
4156 global $wgAuth, $wgLegacyEncoding;
4160 // Some passwords will give a fatal Status, which means there is
4161 // some sort of technical or security reason for this password to
4162 // be completely invalid and should never be checked (e.g., T64685)
4163 if ( !$this->checkPasswordValidity( $password )->isOK() ) {
4167 // Certain authentication plugins do NOT want to save
4168 // domain passwords in a mysql database, so we should
4169 // check this (in case $wgAuth->strict() is false).
4170 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
4172 } elseif ( $wgAuth->strict() ) {
4173 // Auth plugin doesn't allow local authentication
4175 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
4176 // Auth plugin doesn't allow local authentication for this user name
4180 $passwordFactory = new PasswordFactory();
4181 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4182 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
4183 ?
wfGetDB( DB_MASTER
)
4184 : wfGetDB( DB_SLAVE
);
4187 $mPassword = $passwordFactory->newFromCiphertext( $db->selectField(
4188 'user', 'user_password', [ 'user_id' => $this->getId() ], __METHOD__
4190 } catch ( PasswordError
$e ) {
4191 wfDebug( 'Invalid password hash found in database.' );
4192 $mPassword = PasswordFactory
::newInvalidPassword();
4195 if ( !$mPassword->equals( $password ) ) {
4196 if ( $wgLegacyEncoding ) {
4197 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
4198 // Check for this with iconv
4199 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
4200 if ( $cp1252Password === $password ||
!$mPassword->equals( $cp1252Password ) ) {
4208 if ( $passwordFactory->needsUpdate( $mPassword ) && !wfReadOnly() ) {
4209 $this->setPasswordInternal( $password );
4216 * Check if the given clear-text password matches the temporary password
4217 * sent by e-mail for password reset operations.
4219 * @deprecated since 1.27. AuthManager is coming.
4220 * @param string $plaintext
4221 * @return bool True if matches, false otherwise
4223 public function checkTemporaryPassword( $plaintext ) {
4224 global $wgNewPasswordExpiry;
4228 $passwordFactory = new PasswordFactory();
4229 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4230 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
4231 ?
wfGetDB( DB_MASTER
)
4232 : wfGetDB( DB_SLAVE
);
4234 $row = $db->selectRow(
4236 [ 'user_newpassword', 'user_newpass_time' ],
4237 [ 'user_id' => $this->getId() ],
4241 $newPassword = $passwordFactory->newFromCiphertext( $row->user_newpassword
);
4242 } catch ( PasswordError
$e ) {
4243 wfDebug( 'Invalid password hash found in database.' );
4244 $newPassword = PasswordFactory
::newInvalidPassword();
4247 if ( $newPassword->equals( $plaintext ) ) {
4248 if ( is_null( $row->user_newpass_time
) ) {
4251 $expiry = wfTimestamp( TS_UNIX
, $row->user_newpass_time
) +
$wgNewPasswordExpiry;
4252 return ( time() < $expiry );
4259 * Initialize (if necessary) and return a session token value
4260 * which can be used in edit forms to show that the user's
4261 * login credentials aren't being hijacked with a foreign form
4265 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4266 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4267 * @return MediaWiki\Session\Token The new edit token
4269 public function getEditTokenObject( $salt = '', $request = null ) {
4270 if ( $this->isAnon() ) {
4271 return new LoggedOutEditToken();
4275 $request = $this->getRequest();
4277 return $request->getSession()->getToken( $salt );
4281 * Initialize (if necessary) and return a session token value
4282 * which can be used in edit forms to show that the user's
4283 * login credentials aren't being hijacked with a foreign form
4287 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4288 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4289 * @return string The new edit token
4291 public function getEditToken( $salt = '', $request = null ) {
4292 return $this->getEditTokenObject( $salt, $request )->toString();
4296 * Get the embedded timestamp from a token.
4297 * @deprecated since 1.27, use \MediaWiki\Session\Token::getTimestamp instead.
4298 * @param string $val Input token
4301 public static function getEditTokenTimestamp( $val ) {
4302 wfDeprecated( __METHOD__
, '1.27' );
4303 return MediaWiki\Session\Token
::getTimestamp( $val );
4307 * Check given value against the token value stored in the session.
4308 * A match should confirm that the form was submitted from the
4309 * user's own login session, not a form submission from a third-party
4312 * @param string $val Input value to compare
4313 * @param string $salt Optional function-specific data for hashing
4314 * @param WebRequest|null $request Object to use or null to use $wgRequest
4315 * @param int $maxage Fail tokens older than this, in seconds
4316 * @return bool Whether the token matches
4318 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4319 return $this->getEditTokenObject( $salt, $request )->match( $val, $maxage );
4323 * Check given value against the token value stored in the session,
4324 * ignoring the suffix.
4326 * @param string $val Input value to compare
4327 * @param string $salt Optional function-specific data for hashing
4328 * @param WebRequest|null $request Object to use or null to use $wgRequest
4329 * @param int $maxage Fail tokens older than this, in seconds
4330 * @return bool Whether the token matches
4332 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4333 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . Token
::SUFFIX
;
4334 return $this->matchEditToken( $val, $salt, $request, $maxage );
4338 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4339 * mail to the user's given address.
4341 * @param string $type Message to send, either "created", "changed" or "set"
4344 public function sendConfirmationMail( $type = 'created' ) {
4346 $expiration = null; // gets passed-by-ref and defined in next line.
4347 $token = $this->confirmationToken( $expiration );
4348 $url = $this->confirmationTokenUrl( $token );
4349 $invalidateURL = $this->invalidationTokenUrl( $token );
4350 $this->saveSettings();
4352 if ( $type == 'created' ||
$type === false ) {
4353 $message = 'confirmemail_body';
4354 } elseif ( $type === true ) {
4355 $message = 'confirmemail_body_changed';
4357 // Messages: confirmemail_body_changed, confirmemail_body_set
4358 $message = 'confirmemail_body_' . $type;
4361 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4362 wfMessage( $message,
4363 $this->getRequest()->getIP(),
4366 $wgLang->userTimeAndDate( $expiration, $this ),
4368 $wgLang->userDate( $expiration, $this ),
4369 $wgLang->userTime( $expiration, $this ) )->text() );
4373 * Send an e-mail to this user's account. Does not check for
4374 * confirmed status or validity.
4376 * @param string $subject Message subject
4377 * @param string $body Message body
4378 * @param User|null $from Optional sending user; if unspecified, default
4379 * $wgPasswordSender will be used.
4380 * @param string $replyto Reply-To address
4383 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4384 global $wgPasswordSender;
4386 if ( $from instanceof User
) {
4387 $sender = MailAddress
::newFromUser( $from );
4389 $sender = new MailAddress( $wgPasswordSender,
4390 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4392 $to = MailAddress
::newFromUser( $this );
4394 return UserMailer
::send( $to, $sender, $subject, $body, [
4395 'replyTo' => $replyto,
4400 * Generate, store, and return a new e-mail confirmation code.
4401 * A hash (unsalted, since it's used as a key) is stored.
4403 * @note Call saveSettings() after calling this function to commit
4404 * this change to the database.
4406 * @param string &$expiration Accepts the expiration time
4407 * @return string New token
4409 protected function confirmationToken( &$expiration ) {
4410 global $wgUserEmailConfirmationTokenExpiry;
4412 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4413 $expiration = wfTimestamp( TS_MW
, $expires );
4415 $token = MWCryptRand
::generateHex( 32 );
4416 $hash = md5( $token );
4417 $this->mEmailToken
= $hash;
4418 $this->mEmailTokenExpires
= $expiration;
4423 * Return a URL the user can use to confirm their email address.
4424 * @param string $token Accepts the email confirmation token
4425 * @return string New token URL
4427 protected function confirmationTokenUrl( $token ) {
4428 return $this->getTokenUrl( 'ConfirmEmail', $token );
4432 * Return a URL the user can use to invalidate their email address.
4433 * @param string $token Accepts the email confirmation token
4434 * @return string New token URL
4436 protected function invalidationTokenUrl( $token ) {
4437 return $this->getTokenUrl( 'InvalidateEmail', $token );
4441 * Internal function to format the e-mail validation/invalidation URLs.
4442 * This uses a quickie hack to use the
4443 * hardcoded English names of the Special: pages, for ASCII safety.
4445 * @note Since these URLs get dropped directly into emails, using the
4446 * short English names avoids insanely long URL-encoded links, which
4447 * also sometimes can get corrupted in some browsers/mailers
4448 * (bug 6957 with Gmail and Internet Explorer).
4450 * @param string $page Special page
4451 * @param string $token Token
4452 * @return string Formatted URL
4454 protected function getTokenUrl( $page, $token ) {
4455 // Hack to bypass localization of 'Special:'
4456 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4457 return $title->getCanonicalURL();
4461 * Mark the e-mail address confirmed.
4463 * @note Call saveSettings() after calling this function to commit the change.
4467 public function confirmEmail() {
4468 // Check if it's already confirmed, so we don't touch the database
4469 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4470 if ( !$this->isEmailConfirmed() ) {
4471 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4472 Hooks
::run( 'ConfirmEmailComplete', [ $this ] );
4478 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4479 * address if it was already confirmed.
4481 * @note Call saveSettings() after calling this function to commit the change.
4482 * @return bool Returns true
4484 public function invalidateEmail() {
4486 $this->mEmailToken
= null;
4487 $this->mEmailTokenExpires
= null;
4488 $this->setEmailAuthenticationTimestamp( null );
4490 Hooks
::run( 'InvalidateEmailComplete', [ $this ] );
4495 * Set the e-mail authentication timestamp.
4496 * @param string $timestamp TS_MW timestamp
4498 public function setEmailAuthenticationTimestamp( $timestamp ) {
4500 $this->mEmailAuthenticated
= $timestamp;
4501 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
4505 * Is this user allowed to send e-mails within limits of current
4506 * site configuration?
4509 public function canSendEmail() {
4510 global $wgEnableEmail, $wgEnableUserEmail;
4511 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4514 $canSend = $this->isEmailConfirmed();
4515 Hooks
::run( 'UserCanSendEmail', [ &$this, &$canSend ] );
4520 * Is this user allowed to receive e-mails within limits of current
4521 * site configuration?
4524 public function canReceiveEmail() {
4525 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4529 * Is this user's e-mail address valid-looking and confirmed within
4530 * limits of the current site configuration?
4532 * @note If $wgEmailAuthentication is on, this may require the user to have
4533 * confirmed their address by returning a code or using a password
4534 * sent to the address from the wiki.
4538 public function isEmailConfirmed() {
4539 global $wgEmailAuthentication;
4542 if ( Hooks
::run( 'EmailConfirmed', [ &$this, &$confirmed ] ) ) {
4543 if ( $this->isAnon() ) {
4546 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4549 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4559 * Check whether there is an outstanding request for e-mail confirmation.
4562 public function isEmailConfirmationPending() {
4563 global $wgEmailAuthentication;
4564 return $wgEmailAuthentication &&
4565 !$this->isEmailConfirmed() &&
4566 $this->mEmailToken
&&
4567 $this->mEmailTokenExpires
> wfTimestamp();
4571 * Get the timestamp of account creation.
4573 * @return string|bool|null Timestamp of account creation, false for
4574 * non-existent/anonymous user accounts, or null if existing account
4575 * but information is not in database.
4577 public function getRegistration() {
4578 if ( $this->isAnon() ) {
4582 return $this->mRegistration
;
4586 * Get the timestamp of the first edit
4588 * @return string|bool Timestamp of first edit, or false for
4589 * non-existent/anonymous user accounts.
4591 public function getFirstEditTimestamp() {
4592 if ( $this->getId() == 0 ) {
4593 return false; // anons
4595 $dbr = wfGetDB( DB_SLAVE
);
4596 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4597 [ 'rev_user' => $this->getId() ],
4599 [ 'ORDER BY' => 'rev_timestamp ASC' ]
4602 return false; // no edits
4604 return wfTimestamp( TS_MW
, $time );
4608 * Get the permissions associated with a given list of groups
4610 * @param array $groups Array of Strings List of internal group names
4611 * @return array Array of Strings List of permission key names for given groups combined
4613 public static function getGroupPermissions( $groups ) {
4614 global $wgGroupPermissions, $wgRevokePermissions;
4616 // grant every granted permission first
4617 foreach ( $groups as $group ) {
4618 if ( isset( $wgGroupPermissions[$group] ) ) {
4619 $rights = array_merge( $rights,
4620 // array_filter removes empty items
4621 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4624 // now revoke the revoked permissions
4625 foreach ( $groups as $group ) {
4626 if ( isset( $wgRevokePermissions[$group] ) ) {
4627 $rights = array_diff( $rights,
4628 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4631 return array_unique( $rights );
4635 * Get all the groups who have a given permission
4637 * @param string $role Role to check
4638 * @return array Array of Strings List of internal group names with the given permission
4640 public static function getGroupsWithPermission( $role ) {
4641 global $wgGroupPermissions;
4642 $allowedGroups = [];
4643 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4644 if ( self
::groupHasPermission( $group, $role ) ) {
4645 $allowedGroups[] = $group;
4648 return $allowedGroups;
4652 * Check, if the given group has the given permission
4654 * If you're wanting to check whether all users have a permission, use
4655 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4659 * @param string $group Group to check
4660 * @param string $role Role to check
4663 public static function groupHasPermission( $group, $role ) {
4664 global $wgGroupPermissions, $wgRevokePermissions;
4665 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4666 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4670 * Check if all users may be assumed to have the given permission
4672 * We generally assume so if the right is granted to '*' and isn't revoked
4673 * on any group. It doesn't attempt to take grants or other extension
4674 * limitations on rights into account in the general case, though, as that
4675 * would require it to always return false and defeat the purpose.
4676 * Specifically, session-based rights restrictions (such as OAuth or bot
4677 * passwords) are applied based on the current session.
4680 * @param string $right Right to check
4683 public static function isEveryoneAllowed( $right ) {
4684 global $wgGroupPermissions, $wgRevokePermissions;
4687 // Use the cached results, except in unit tests which rely on
4688 // being able change the permission mid-request
4689 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4690 return $cache[$right];
4693 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4694 $cache[$right] = false;
4698 // If it's revoked anywhere, then everyone doesn't have it
4699 foreach ( $wgRevokePermissions as $rights ) {
4700 if ( isset( $rights[$right] ) && $rights[$right] ) {
4701 $cache[$right] = false;
4706 // Remove any rights that aren't allowed to the global-session user,
4707 // unless there are no sessions for this endpoint.
4708 if ( !defined( 'MW_NO_SESSION' ) ) {
4709 $allowedRights = SessionManager
::getGlobalSession()->getAllowedUserRights();
4710 if ( $allowedRights !== null && !in_array( $right, $allowedRights, true ) ) {
4711 $cache[$right] = false;
4716 // Allow extensions to say false
4717 if ( !Hooks
::run( 'UserIsEveryoneAllowed', [ $right ] ) ) {
4718 $cache[$right] = false;
4722 $cache[$right] = true;
4727 * Get the localized descriptive name for a group, if it exists
4729 * @param string $group Internal group name
4730 * @return string Localized descriptive group name
4732 public static function getGroupName( $group ) {
4733 $msg = wfMessage( "group-$group" );
4734 return $msg->isBlank() ?
$group : $msg->text();
4738 * Get the localized descriptive name for a member of a group, if it exists
4740 * @param string $group Internal group name
4741 * @param string $username Username for gender (since 1.19)
4742 * @return string Localized name for group member
4744 public static function getGroupMember( $group, $username = '#' ) {
4745 $msg = wfMessage( "group-$group-member", $username );
4746 return $msg->isBlank() ?
$group : $msg->text();
4750 * Return the set of defined explicit groups.
4751 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4752 * are not included, as they are defined automatically, not in the database.
4753 * @return array Array of internal group names
4755 public static function getAllGroups() {
4756 global $wgGroupPermissions, $wgRevokePermissions;
4758 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4759 self
::getImplicitGroups()
4764 * Get a list of all available permissions.
4765 * @return string[] Array of permission names
4767 public static function getAllRights() {
4768 if ( self
::$mAllRights === false ) {
4769 global $wgAvailableRights;
4770 if ( count( $wgAvailableRights ) ) {
4771 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
4773 self
::$mAllRights = self
::$mCoreRights;
4775 Hooks
::run( 'UserGetAllRights', [ &self
::$mAllRights ] );
4777 return self
::$mAllRights;
4781 * Get a list of implicit groups
4782 * @return array Array of Strings Array of internal group names
4784 public static function getImplicitGroups() {
4785 global $wgImplicitGroups;
4787 $groups = $wgImplicitGroups;
4788 # Deprecated, use $wgImplicitGroups instead
4789 Hooks
::run( 'UserGetImplicitGroups', [ &$groups ], '1.25' );
4795 * Get the title of a page describing a particular group
4797 * @param string $group Internal group name
4798 * @return Title|bool Title of the page if it exists, false otherwise
4800 public static function getGroupPage( $group ) {
4801 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4802 if ( $msg->exists() ) {
4803 $title = Title
::newFromText( $msg->text() );
4804 if ( is_object( $title ) ) {
4812 * Create a link to the group in HTML, if available;
4813 * else return the group name.
4815 * @param string $group Internal name of the group
4816 * @param string $text The text of the link
4817 * @return string HTML link to the group
4819 public static function makeGroupLinkHTML( $group, $text = '' ) {
4820 if ( $text == '' ) {
4821 $text = self
::getGroupName( $group );
4823 $title = self
::getGroupPage( $group );
4825 return Linker
::link( $title, htmlspecialchars( $text ) );
4827 return htmlspecialchars( $text );
4832 * Create a link to the group in Wikitext, if available;
4833 * else return the group name.
4835 * @param string $group Internal name of the group
4836 * @param string $text The text of the link
4837 * @return string Wikilink to the group
4839 public static function makeGroupLinkWiki( $group, $text = '' ) {
4840 if ( $text == '' ) {
4841 $text = self
::getGroupName( $group );
4843 $title = self
::getGroupPage( $group );
4845 $page = $title->getFullText();
4846 return "[[$page|$text]]";
4853 * Returns an array of the groups that a particular group can add/remove.
4855 * @param string $group The group to check for whether it can add/remove
4856 * @return array Array( 'add' => array( addablegroups ),
4857 * 'remove' => array( removablegroups ),
4858 * 'add-self' => array( addablegroups to self),
4859 * 'remove-self' => array( removable groups from self) )
4861 public static function changeableByGroup( $group ) {
4862 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4871 if ( empty( $wgAddGroups[$group] ) ) {
4872 // Don't add anything to $groups
4873 } elseif ( $wgAddGroups[$group] === true ) {
4874 // You get everything
4875 $groups['add'] = self
::getAllGroups();
4876 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4877 $groups['add'] = $wgAddGroups[$group];
4880 // Same thing for remove
4881 if ( empty( $wgRemoveGroups[$group] ) ) {
4883 } elseif ( $wgRemoveGroups[$group] === true ) {
4884 $groups['remove'] = self
::getAllGroups();
4885 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4886 $groups['remove'] = $wgRemoveGroups[$group];
4889 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4890 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4891 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4892 if ( is_int( $key ) ) {
4893 $wgGroupsAddToSelf['user'][] = $value;
4898 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
4899 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4900 if ( is_int( $key ) ) {
4901 $wgGroupsRemoveFromSelf['user'][] = $value;
4906 // Now figure out what groups the user can add to him/herself
4907 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4909 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4910 // No idea WHY this would be used, but it's there
4911 $groups['add-self'] = User
::getAllGroups();
4912 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4913 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4916 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4918 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4919 $groups['remove-self'] = User
::getAllGroups();
4920 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4921 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4928 * Returns an array of groups that this user can add and remove
4929 * @return array Array( 'add' => array( addablegroups ),
4930 * 'remove' => array( removablegroups ),
4931 * 'add-self' => array( addablegroups to self),
4932 * 'remove-self' => array( removable groups from self) )
4934 public function changeableGroups() {
4935 if ( $this->isAllowed( 'userrights' ) ) {
4936 // This group gives the right to modify everything (reverse-
4937 // compatibility with old "userrights lets you change
4939 // Using array_merge to make the groups reindexed
4940 $all = array_merge( User
::getAllGroups() );
4949 // Okay, it's not so simple, we will have to go through the arrays
4956 $addergroups = $this->getEffectiveGroups();
4958 foreach ( $addergroups as $addergroup ) {
4959 $groups = array_merge_recursive(
4960 $groups, $this->changeableByGroup( $addergroup )
4962 $groups['add'] = array_unique( $groups['add'] );
4963 $groups['remove'] = array_unique( $groups['remove'] );
4964 $groups['add-self'] = array_unique( $groups['add-self'] );
4965 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4971 * Deferred version of incEditCountImmediate()
4973 public function incEditCount() {
4974 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle( function() {
4975 $this->incEditCountImmediate();
4980 * Increment the user's edit-count field.
4981 * Will have no effect for anonymous users.
4984 public function incEditCountImmediate() {
4985 if ( $this->isAnon() ) {
4989 $dbw = wfGetDB( DB_MASTER
);
4990 // No rows will be "affected" if user_editcount is NULL
4993 [ 'user_editcount=user_editcount+1' ],
4994 [ 'user_id' => $this->getId(), 'user_editcount IS NOT NULL' ],
4997 // Lazy initialization check...
4998 if ( $dbw->affectedRows() == 0 ) {
4999 // Now here's a goddamn hack...
5000 $dbr = wfGetDB( DB_SLAVE
);
5001 if ( $dbr !== $dbw ) {
5002 // If we actually have a slave server, the count is
5003 // at least one behind because the current transaction
5004 // has not been committed and replicated.
5005 $this->initEditCount( 1 );
5007 // But if DB_SLAVE is selecting the master, then the
5008 // count we just read includes the revision that was
5009 // just added in the working transaction.
5010 $this->initEditCount();
5013 // Edit count in user cache too
5014 $this->invalidateCache();
5018 * Initialize user_editcount from data out of the revision table
5020 * @param int $add Edits to add to the count from the revision table
5021 * @return int Number of edits
5023 protected function initEditCount( $add = 0 ) {
5024 // Pull from a slave to be less cruel to servers
5025 // Accuracy isn't the point anyway here
5026 $dbr = wfGetDB( DB_SLAVE
);
5027 $count = (int)$dbr->selectField(
5030 [ 'rev_user' => $this->getId() ],
5033 $count = $count +
$add;
5035 $dbw = wfGetDB( DB_MASTER
);
5038 [ 'user_editcount' => $count ],
5039 [ 'user_id' => $this->getId() ],
5047 * Get the description of a given right
5049 * @param string $right Right to query
5050 * @return string Localized description of the right
5052 public static function getRightDescription( $right ) {
5053 $key = "right-$right";
5054 $msg = wfMessage( $key );
5055 return $msg->isBlank() ?
$right : $msg->text();
5059 * Make a new-style password hash
5061 * @param string $password Plain-text password
5062 * @param bool|string $salt Optional salt, may be random or the user ID.
5063 * If unspecified or false, will generate one automatically
5064 * @return string Password hash
5065 * @deprecated since 1.24, use Password class
5067 public static function crypt( $password, $salt = false ) {
5068 wfDeprecated( __METHOD__
, '1.24' );
5069 $passwordFactory = new PasswordFactory();
5070 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
5071 $hash = $passwordFactory->newFromPlaintext( $password );
5072 return $hash->toString();
5076 * Compare a password hash with a plain-text password. Requires the user
5077 * ID if there's a chance that the hash is an old-style hash.
5079 * @param string $hash Password hash
5080 * @param string $password Plain-text password to compare
5081 * @param string|bool $userId User ID for old-style password salt
5084 * @deprecated since 1.24, use Password class
5086 public static function comparePasswords( $hash, $password, $userId = false ) {
5087 wfDeprecated( __METHOD__
, '1.24' );
5089 // Check for *really* old password hashes that don't even have a type
5090 // The old hash format was just an md5 hex hash, with no type information
5091 if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) {
5092 global $wgPasswordSalt;
5093 if ( $wgPasswordSalt ) {
5094 $password = ":B:{$userId}:{$hash}";
5096 $password = ":A:{$hash}";
5100 $passwordFactory = new PasswordFactory();
5101 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
5102 $hash = $passwordFactory->newFromCiphertext( $hash );
5103 return $hash->equals( $password );
5107 * Add a newuser log entry for this user.
5108 * Before 1.19 the return value was always true.
5110 * @param string|bool $action Account creation type.
5111 * - String, one of the following values:
5112 * - 'create' for an anonymous user creating an account for himself.
5113 * This will force the action's performer to be the created user itself,
5114 * no matter the value of $wgUser
5115 * - 'create2' for a logged in user creating an account for someone else
5116 * - 'byemail' when the created user will receive its password by e-mail
5117 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
5118 * - Boolean means whether the account was created by e-mail (deprecated):
5119 * - true will be converted to 'byemail'
5120 * - false will be converted to 'create' if this object is the same as
5121 * $wgUser and to 'create2' otherwise
5123 * @param string $reason User supplied reason
5125 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
5127 public function addNewUserLogEntry( $action = false, $reason = '' ) {
5128 global $wgUser, $wgNewUserLog;
5129 if ( empty( $wgNewUserLog ) ) {
5130 return true; // disabled
5133 if ( $action === true ) {
5134 $action = 'byemail';
5135 } elseif ( $action === false ) {
5136 if ( $this->equals( $wgUser ) ) {
5139 $action = 'create2';
5143 if ( $action === 'create' ||
$action === 'autocreate' ) {
5146 $performer = $wgUser;
5149 $logEntry = new ManualLogEntry( 'newusers', $action );
5150 $logEntry->setPerformer( $performer );
5151 $logEntry->setTarget( $this->getUserPage() );
5152 $logEntry->setComment( $reason );
5153 $logEntry->setParameters( [
5154 '4::userid' => $this->getId(),
5156 $logid = $logEntry->insert();
5158 if ( $action !== 'autocreate' ) {
5159 $logEntry->publish( $logid );
5166 * Add an autocreate newuser log entry for this user
5167 * Used by things like CentralAuth and perhaps other authplugins.
5168 * Consider calling addNewUserLogEntry() directly instead.
5172 public function addNewUserLogEntryAutoCreate() {
5173 $this->addNewUserLogEntry( 'autocreate' );
5179 * Load the user options either from cache, the database or an array
5181 * @param array $data Rows for the current user out of the user_properties table
5183 protected function loadOptions( $data = null ) {
5188 if ( $this->mOptionsLoaded
) {
5192 $this->mOptions
= self
::getDefaultOptions();
5194 if ( !$this->getId() ) {
5195 // For unlogged-in users, load language/variant options from request.
5196 // There's no need to do it for logged-in users: they can set preferences,
5197 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5198 // so don't override user's choice (especially when the user chooses site default).
5199 $variant = $wgContLang->getDefaultVariant();
5200 $this->mOptions
['variant'] = $variant;
5201 $this->mOptions
['language'] = $variant;
5202 $this->mOptionsLoaded
= true;
5206 // Maybe load from the object
5207 if ( !is_null( $this->mOptionOverrides
) ) {
5208 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5209 foreach ( $this->mOptionOverrides
as $key => $value ) {
5210 $this->mOptions
[$key] = $value;
5213 if ( !is_array( $data ) ) {
5214 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5215 // Load from database
5216 $dbr = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
5217 ?
wfGetDB( DB_MASTER
)
5218 : wfGetDB( DB_SLAVE
);
5220 $res = $dbr->select(
5222 [ 'up_property', 'up_value' ],
5223 [ 'up_user' => $this->getId() ],
5227 $this->mOptionOverrides
= [];
5229 foreach ( $res as $row ) {
5230 $data[$row->up_property
] = $row->up_value
;
5233 foreach ( $data as $property => $value ) {
5234 $this->mOptionOverrides
[$property] = $value;
5235 $this->mOptions
[$property] = $value;
5239 $this->mOptionsLoaded
= true;
5241 Hooks
::run( 'UserLoadOptions', [ $this, &$this->mOptions
] );
5245 * Saves the non-default options for this user, as previously set e.g. via
5246 * setOption(), in the database's "user_properties" (preferences) table.
5247 * Usually used via saveSettings().
5249 protected function saveOptions() {
5250 $this->loadOptions();
5252 // Not using getOptions(), to keep hidden preferences in database
5253 $saveOptions = $this->mOptions
;
5255 // Allow hooks to abort, for instance to save to a global profile.
5256 // Reset options to default state before saving.
5257 if ( !Hooks
::run( 'UserSaveOptions', [ $this, &$saveOptions ] ) ) {
5261 $userId = $this->getId();
5263 $insert_rows = []; // all the new preference rows
5264 foreach ( $saveOptions as $key => $value ) {
5265 // Don't bother storing default values
5266 $defaultOption = self
::getDefaultOption( $key );
5267 if ( ( $defaultOption === null && $value !== false && $value !== null )
5268 ||
$value != $defaultOption
5271 'up_user' => $userId,
5272 'up_property' => $key,
5273 'up_value' => $value,
5278 $dbw = wfGetDB( DB_MASTER
);
5280 $res = $dbw->select( 'user_properties',
5281 [ 'up_property', 'up_value' ], [ 'up_user' => $userId ], __METHOD__
);
5283 // Find prior rows that need to be removed or updated. These rows will
5284 // all be deleted (the later so that INSERT IGNORE applies the new values).
5286 foreach ( $res as $row ) {
5287 if ( !isset( $saveOptions[$row->up_property
] )
5288 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
5290 $keysDelete[] = $row->up_property
;
5294 if ( count( $keysDelete ) ) {
5295 // Do the DELETE by PRIMARY KEY for prior rows.
5296 // In the past a very large portion of calls to this function are for setting
5297 // 'rememberpassword' for new accounts (a preference that has since been removed).
5298 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5299 // caused gap locks on [max user ID,+infinity) which caused high contention since
5300 // updates would pile up on each other as they are for higher (newer) user IDs.
5301 // It might not be necessary these days, but it shouldn't hurt either.
5302 $dbw->delete( 'user_properties',
5303 [ 'up_user' => $userId, 'up_property' => $keysDelete ], __METHOD__
);
5305 // Insert the new preference rows
5306 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, [ 'IGNORE' ] );
5310 * Lazily instantiate and return a factory object for making passwords
5312 * @deprecated since 1.27, create a PasswordFactory directly instead
5313 * @return PasswordFactory
5315 public static function getPasswordFactory() {
5316 wfDeprecated( __METHOD__
, '1.27' );
5317 $ret = new PasswordFactory();
5318 $ret->init( RequestContext
::getMain()->getConfig() );
5323 * Provide an array of HTML5 attributes to put on an input element
5324 * intended for the user to enter a new password. This may include
5325 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
5327 * Do *not* use this when asking the user to enter his current password!
5328 * Regardless of configuration, users may have invalid passwords for whatever
5329 * reason (e.g., they were set before requirements were tightened up).
5330 * Only use it when asking for a new password, like on account creation or
5333 * Obviously, you still need to do server-side checking.
5335 * NOTE: A combination of bugs in various browsers means that this function
5336 * actually just returns array() unconditionally at the moment. May as
5337 * well keep it around for when the browser bugs get fixed, though.
5339 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
5341 * @deprecated since 1.27
5342 * @return array Array of HTML attributes suitable for feeding to
5343 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
5344 * That will get confused by the boolean attribute syntax used.)
5346 public static function passwordChangeInputAttribs() {
5347 global $wgMinimalPasswordLength;
5349 if ( $wgMinimalPasswordLength == 0 ) {
5353 # Note that the pattern requirement will always be satisfied if the
5354 # input is empty, so we need required in all cases.
5356 # @todo FIXME: Bug 23769: This needs to not claim the password is required
5357 # if e-mail confirmation is being used. Since HTML5 input validation
5358 # is b0rked anyway in some browsers, just return nothing. When it's
5359 # re-enabled, fix this code to not output required for e-mail
5361 # $ret = array( 'required' );
5364 # We can't actually do this right now, because Opera 9.6 will print out
5365 # the entered password visibly in its error message! When other
5366 # browsers add support for this attribute, or Opera fixes its support,
5367 # we can add support with a version check to avoid doing this on Opera
5368 # versions where it will be a problem. Reported to Opera as
5369 # DSK-262266, but they don't have a public bug tracker for us to follow.
5371 if ( $wgMinimalPasswordLength > 1 ) {
5372 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
5373 $ret['title'] = wfMessage( 'passwordtooshort' )
5374 ->numParams( $wgMinimalPasswordLength )->text();
5382 * Return the list of user fields that should be selected to create
5383 * a new user object.
5386 public static function selectFields() {
5394 'user_email_authenticated',
5396 'user_email_token_expires',
5397 'user_registration',
5403 * Factory function for fatal permission-denied errors
5406 * @param string $permission User right required
5409 static function newFatalPermissionDeniedStatus( $permission ) {
5412 $groups = array_map(
5413 [ 'User', 'makeGroupLinkWiki' ],
5414 User
::getGroupsWithPermission( $permission )
5418 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5420 return Status
::newFatal( 'badaccess-group0' );
5425 * Get a new instance of this user that was loaded from the master via a locking read
5427 * Use this instead of the main context User when updating that user. This avoids races
5428 * where that user was loaded from a slave or even the master but without proper locks.
5430 * @return User|null Returns null if the user was not found in the DB
5433 public function getInstanceForUpdate() {
5434 if ( !$this->getId() ) {
5435 return null; // anon
5438 $user = self
::newFromId( $this->getId() );
5439 if ( !$user->loadFromId( self
::READ_EXCLUSIVE
) ) {
5447 * Checks if two user objects point to the same user.
5453 public function equals( User
$user ) {
5454 return $this->getName() === $user->getName();