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\Session\SessionManager
;
24 use MediaWiki\Session\Token
;
27 * String Some punctuation to prevent editing from broken text-mangling proxies.
28 * @deprecated since 1.27, use \MediaWiki\Session\Token::SUFFIX
31 define( 'EDIT_TOKEN_SUFFIX', Token
::SUFFIX
);
34 * The User object encapsulates all of the user-specific settings (user_id,
35 * name, rights, email address, options, last login time). Client
36 * classes use the getXXX() functions to access these fields. These functions
37 * do all the work of determining whether the user is logged in,
38 * whether the requested option can be satisfied from cookies or
39 * whether a database query is needed. Most of the settings needed
40 * for rendering normal pages are set in the cookie to minimize use
43 class User
implements IDBAccessObject
{
45 * @const int Number of characters in user_token field.
47 const TOKEN_LENGTH
= 32;
50 * @const string An invalid value for user_token
52 const INVALID_TOKEN
= '*** INVALID ***';
55 * Global constant made accessible as class constants so that autoloader
57 * @deprecated since 1.27, use \MediaWiki\Session\Token::SUFFIX
59 const EDIT_TOKEN_SUFFIX
= EDIT_TOKEN_SUFFIX
;
62 * @const int Serialized record version.
67 * Exclude user options that are set to their default value.
70 const GETOPTIONS_EXCLUDE_DEFAULTS
= 1;
75 const CHECK_USER_RIGHTS
= true;
80 const IGNORE_USER_RIGHTS
= false;
83 * Array of Strings List of member variables which are saved to the
84 * shared cache (memcached). Any operation which changes the
85 * corresponding database fields must call a cache-clearing function.
88 protected static $mCacheVars = [
96 'mEmailAuthenticated',
103 // user_properties table
108 * Array of Strings Core rights.
109 * Each of these should have a corresponding message of the form
113 protected static $mCoreRights = [
143 'editusercssjs', # deprecated
156 'move-categorypages',
157 'move-rootuserpages',
161 'override-export-depth',
184 'userrights-interwiki',
192 * String Cached results of getAllRights()
194 protected static $mAllRights = false;
197 * An in-process cache for user data lookup
200 protected static $inProcessCache;
202 /** Cache variables */
213 /** @var string TS_MW timestamp from the DB */
215 /** @var string TS_MW timestamp from cache */
216 protected $mQuickTouched;
220 public $mEmailAuthenticated;
222 protected $mEmailToken;
224 protected $mEmailTokenExpires;
226 protected $mRegistration;
228 protected $mEditCount;
232 protected $mOptionOverrides;
236 * Bool Whether the cache variables have been loaded.
239 public $mOptionsLoaded;
242 * Array with already loaded items or true if all items have been loaded.
244 protected $mLoadedItems = [];
248 * String Initialization data source if mLoadedItems!==true. May be one of:
249 * - 'defaults' anonymous user initialised from class defaults
250 * - 'name' initialise from mName
251 * - 'id' initialise from mId
252 * - 'session' log in from session if possible
254 * Use the User::newFrom*() family of functions to set this.
259 * Lazy-initialized variables, invalidated with clearInstanceCache
263 protected $mDatePreference;
271 protected $mBlockreason;
273 protected $mEffectiveGroups;
275 protected $mImplicitGroups;
277 protected $mFormerGroups;
279 protected $mBlockedGlobally;
296 protected $mAllowUsertalk;
299 private $mBlockedFromCreateAccount = false;
301 /** @var integer User::READ_* constant bitfield used to load data */
302 protected $queryFlagsUsed = self
::READ_NORMAL
;
304 public static $idCacheByName = [];
307 * Lightweight constructor for an anonymous user.
308 * Use the User::newFrom* factory functions for other kinds of users.
312 * @see newFromConfirmationCode()
313 * @see newFromSession()
316 public function __construct() {
317 $this->clearInstanceCache( 'defaults' );
323 public function __toString() {
324 return $this->getName();
328 * Test if it's safe to load this User object.
330 * You should typically check this before using $wgUser or
331 * RequestContext::getUser in a method that might be called before the
332 * system has been fully initialized. If the object is unsafe, you should
333 * use an anonymous user:
335 * $user = $wgUser->isSafeToLoad() ? $wgUser : new User;
341 public function isSafeToLoad() {
342 global $wgFullyInitialised;
344 // The user is safe to load if:
345 // * MW_NO_SESSION is undefined AND $wgFullyInitialised is true (safe to use session data)
346 // * mLoadedItems === true (already loaded)
347 // * mFrom !== 'session' (sessions not involved at all)
349 return ( !defined( 'MW_NO_SESSION' ) && $wgFullyInitialised ) ||
350 $this->mLoadedItems
=== true ||
$this->mFrom
!== 'session';
354 * Load the user table data for this object from the source given by mFrom.
356 * @param integer $flags User::READ_* constant bitfield
358 public function load( $flags = self
::READ_NORMAL
) {
359 global $wgFullyInitialised;
361 if ( $this->mLoadedItems
=== true ) {
365 // Set it now to avoid infinite recursion in accessors
366 $oldLoadedItems = $this->mLoadedItems
;
367 $this->mLoadedItems
= true;
368 $this->queryFlagsUsed
= $flags;
370 // If this is called too early, things are likely to break.
371 if ( !$wgFullyInitialised && $this->mFrom
=== 'session' ) {
372 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
373 ->warning( 'User::loadFromSession called before the end of Setup.php', [
374 'exception' => new Exception( 'User::loadFromSession called before the end of Setup.php' ),
376 $this->loadDefaults();
377 $this->mLoadedItems
= $oldLoadedItems;
381 switch ( $this->mFrom
) {
383 $this->loadDefaults();
386 // Make sure this thread sees its own changes
387 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
388 $flags |
= self
::READ_LATEST
;
389 $this->queryFlagsUsed
= $flags;
392 $this->mId
= self
::idFromName( $this->mName
, $flags );
394 // Nonexistent user placeholder object
395 $this->loadDefaults( $this->mName
);
397 $this->loadFromId( $flags );
401 $this->loadFromId( $flags );
404 if ( !$this->loadFromSession() ) {
405 // Loading from session failed. Load defaults.
406 $this->loadDefaults();
408 Hooks
::run( 'UserLoadAfterLoadFromSession', [ $this ] );
411 throw new UnexpectedValueException(
412 "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
417 * Load user table data, given mId has already been set.
418 * @param integer $flags User::READ_* constant bitfield
419 * @return bool False if the ID does not exist, true otherwise
421 public function loadFromId( $flags = self
::READ_NORMAL
) {
422 if ( $this->mId
== 0 ) {
423 $this->loadDefaults();
427 // Try cache (unless this needs data from the master DB).
428 // NOTE: if this thread called saveSettings(), the cache was cleared.
429 $latest = DBAccessObjectUtils
::hasFlags( $flags, self
::READ_LATEST
);
430 if ( $latest ||
!$this->loadFromCache() ) {
431 wfDebug( "User: cache miss for user {$this->mId}\n" );
432 // Load from DB (make sure this thread sees its own changes)
433 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
434 $flags |
= self
::READ_LATEST
;
436 if ( !$this->loadFromDatabase( $flags ) ) {
437 // Can't load from ID, user is anonymous
440 $this->saveToCache();
443 $this->mLoadedItems
= true;
444 $this->queryFlagsUsed
= $flags;
451 * @param string $wikiId
452 * @param integer $userId
454 public static function purge( $wikiId, $userId ) {
455 $cache = ObjectCache
::getMainWANInstance();
456 $processCache = self
::getInProcessCache();
457 $key = $cache->makeGlobalKey( 'user', 'id', $wikiId, $userId );
458 $cache->delete( $key );
459 $processCache->delete( $key );
464 * @param WANObjectCache $cache
467 protected function getCacheKey( WANObjectCache
$cache ) {
468 return $cache->makeGlobalKey( 'user', 'id', wfWikiID(), $this->mId
);
473 * @return HashBagOStuff
475 protected static function getInProcessCache() {
476 if ( !self
::$inProcessCache ) {
477 self
::$inProcessCache = new HashBagOStuff( ['maxKeys' => 10] );
479 return self
::$inProcessCache;
483 * Load user data from shared cache, given mId has already been set.
485 * @return bool false if the ID does not exist or data is invalid, true otherwise
488 protected function loadFromCache() {
489 if ( $this->mId
== 0 ) {
490 $this->loadDefaults();
494 $cache = ObjectCache
::getMainWANInstance();
495 $processCache = self
::getInProcessCache();
496 $key = $this->getCacheKey( $cache );
497 $data = $processCache->get( $key );
498 if ( !is_array( $data ) ) {
499 $data = $cache->get( $key );
500 if ( !is_array( $data ) ||
$data['mVersion'] < self
::VERSION
) {
504 $processCache->set( $key, $data );
506 wfDebug( "User: got user {$this->mId} from cache\n" );
508 // Restore from cache
509 foreach ( self
::$mCacheVars as $name ) {
510 $this->$name = $data[$name];
517 * Save user data to the shared cache
519 * This method should not be called outside the User class
521 public function saveToCache() {
524 $this->loadOptions();
526 if ( $this->isAnon() ) {
527 // Anonymous users are uncached
532 foreach ( self
::$mCacheVars as $name ) {
533 $data[$name] = $this->$name;
535 $data['mVersion'] = self
::VERSION
;
536 $opts = Database
::getCacheSetOptions( wfGetDB( DB_SLAVE
) );
538 $cache = ObjectCache
::getMainWANInstance();
539 $processCache = self
::getInProcessCache();
540 $key = $this->getCacheKey( $cache );
541 $cache->set( $key, $data, $cache::TTL_HOUR
, $opts );
542 $processCache->set( $key, $data );
545 /** @name newFrom*() static factory methods */
549 * Static factory method for creation from username.
551 * This is slightly less efficient than newFromId(), so use newFromId() if
552 * you have both an ID and a name handy.
554 * @param string $name Username, validated by Title::newFromText()
555 * @param string|bool $validate Validate username. Takes the same parameters as
556 * User::getCanonicalName(), except that true is accepted as an alias
557 * for 'valid', for BC.
559 * @return User|bool User object, or false if the username is invalid
560 * (e.g. if it contains illegal characters or is an IP address). If the
561 * username is not present in the database, the result will be a user object
562 * with a name, zero user ID and default settings.
564 public static function newFromName( $name, $validate = 'valid' ) {
565 if ( $validate === true ) {
568 $name = self
::getCanonicalName( $name, $validate );
569 if ( $name === false ) {
572 // Create unloaded user object
576 $u->setItemLoaded( 'name' );
582 * Static factory method for creation from a given user ID.
584 * @param int $id Valid user ID
585 * @return User The corresponding User object
587 public static function newFromId( $id ) {
591 $u->setItemLoaded( 'id' );
596 * Factory method to fetch whichever user has a given email confirmation code.
597 * This code is generated when an account is created or its e-mail address
600 * If the code is invalid or has expired, returns NULL.
602 * @param string $code Confirmation code
603 * @param int $flags User::READ_* bitfield
606 public static function newFromConfirmationCode( $code, $flags = 0 ) {
607 $db = ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
608 ?
wfGetDB( DB_MASTER
)
609 : wfGetDB( DB_SLAVE
);
611 $id = $db->selectField(
615 'user_email_token' => md5( $code ),
616 'user_email_token_expires > ' . $db->addQuotes( $db->timestamp() ),
620 return $id ? User
::newFromId( $id ) : null;
624 * Create a new user object using data from session. If the login
625 * credentials are invalid, the result is an anonymous user.
627 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
630 public static function newFromSession( WebRequest
$request = null ) {
632 $user->mFrom
= 'session';
633 $user->mRequest
= $request;
638 * Create a new user object from a user row.
639 * The row should have the following fields from the user table in it:
640 * - either user_name or user_id to load further data if needed (or both)
642 * - all other fields (email, etc.)
643 * It is useless to provide the remaining fields if either user_id,
644 * user_name and user_real_name are not provided because the whole row
645 * will be loaded once more from the database when accessing them.
647 * @param stdClass $row A row from the user table
648 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
651 public static function newFromRow( $row, $data = null ) {
653 $user->loadFromRow( $row, $data );
658 * Static factory method for creation of a "system" user from username.
660 * A "system" user is an account that's used to attribute logged actions
661 * taken by MediaWiki itself, as opposed to a bot or human user. Examples
662 * might include the 'Maintenance script' or 'Conversion script' accounts
663 * used by various scripts in the maintenance/ directory or accounts such
664 * as 'MediaWiki message delivery' used by the MassMessage extension.
666 * This can optionally create the user if it doesn't exist, and "steal" the
667 * account if it does exist.
669 * @param string $name Username
670 * @param array $options Options are:
671 * - validate: As for User::getCanonicalName(), default 'valid'
672 * - create: Whether to create the user if it doesn't already exist, default true
673 * - steal: Whether to reset the account's password and email if it
674 * already exists, default false
677 public static function newSystemUser( $name, $options = [] ) {
679 'validate' => 'valid',
684 $name = self
::getCanonicalName( $name, $options['validate'] );
685 if ( $name === false ) {
689 $dbw = wfGetDB( DB_MASTER
);
690 $row = $dbw->selectRow(
693 self
::selectFields(),
694 [ 'user_password', 'user_newpassword' ]
696 [ 'user_name' => $name ],
700 // No user. Create it?
701 return $options['create'] ? self
::createNew( $name ) : null;
703 $user = self
::newFromRow( $row );
705 // A user is considered to exist as a non-system user if it has a
706 // password set, or a temporary password set, or an email set, or a
707 // non-invalid token.
708 $passwordFactory = new PasswordFactory();
709 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
711 $password = $passwordFactory->newFromCiphertext( $row->user_password
);
712 } catch ( PasswordError
$e ) {
713 wfDebug( 'Invalid password hash found in database.' );
714 $password = PasswordFactory
::newInvalidPassword();
717 $newpassword = $passwordFactory->newFromCiphertext( $row->user_newpassword
);
718 } catch ( PasswordError
$e ) {
719 wfDebug( 'Invalid password hash found in database.' );
720 $newpassword = PasswordFactory
::newInvalidPassword();
722 if ( !$password instanceof InvalidPassword ||
!$newpassword instanceof InvalidPassword
723 ||
$user->mEmail ||
$user->mToken
!== self
::INVALID_TOKEN
725 // User exists. Steal it?
726 if ( !$options['steal'] ) {
730 $nopass = PasswordFactory
::newInvalidPassword()->toString();
735 'user_password' => $nopass,
736 'user_newpassword' => $nopass,
737 'user_newpass_time' => null,
739 [ 'user_id' => $user->getId() ],
742 $user->invalidateEmail();
743 $user->mToken
= self
::INVALID_TOKEN
;
744 $user->saveSettings();
745 SessionManager
::singleton()->preventSessionsForUser( $user->getName() );
754 * Get the username corresponding to a given user ID
755 * @param int $id User ID
756 * @return string|bool The corresponding username
758 public static function whoIs( $id ) {
759 return UserCache
::singleton()->getProp( $id, 'name' );
763 * Get the real name of a user given their user ID
765 * @param int $id User ID
766 * @return string|bool The corresponding user's real name
768 public static function whoIsReal( $id ) {
769 return UserCache
::singleton()->getProp( $id, 'real_name' );
773 * Get database id given a user name
774 * @param string $name Username
775 * @param integer $flags User::READ_* constant bitfield
776 * @return int|null The corresponding user's ID, or null if user is nonexistent
778 public static function idFromName( $name, $flags = self
::READ_NORMAL
) {
779 $nt = Title
::makeTitleSafe( NS_USER
, $name );
780 if ( is_null( $nt ) ) {
785 if ( !( $flags & self
::READ_LATEST
) && isset( self
::$idCacheByName[$name] ) ) {
786 return self
::$idCacheByName[$name];
789 $db = ( $flags & self
::READ_LATEST
)
790 ?
wfGetDB( DB_MASTER
)
791 : wfGetDB( DB_SLAVE
);
796 [ 'user_name' => $nt->getText() ],
800 if ( $s === false ) {
803 $result = $s->user_id
;
806 self
::$idCacheByName[$name] = $result;
808 if ( count( self
::$idCacheByName ) > 1000 ) {
809 self
::$idCacheByName = [];
816 * Reset the cache used in idFromName(). For use in tests.
818 public static function resetIdByNameCache() {
819 self
::$idCacheByName = [];
823 * Does the string match an anonymous IPv4 address?
825 * This function exists for username validation, in order to reject
826 * usernames which are similar in form to IP addresses. Strings such
827 * as 300.300.300.300 will return true because it looks like an IP
828 * address, despite not being strictly valid.
830 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
831 * address because the usemod software would "cloak" anonymous IP
832 * addresses like this, if we allowed accounts like this to be created
833 * new users could get the old edits of these anonymous users.
835 * @param string $name Name to match
838 public static function isIP( $name ) {
839 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
840 || IP
::isIPv6( $name );
844 * Is the input a valid username?
846 * Checks if the input is a valid username, we don't want an empty string,
847 * an IP address, anything that contains slashes (would mess up subpages),
848 * is longer than the maximum allowed username size or doesn't begin with
851 * @param string $name Name to match
854 public static function isValidUserName( $name ) {
855 global $wgContLang, $wgMaxNameChars;
858 || User
::isIP( $name )
859 ||
strpos( $name, '/' ) !== false
860 ||
strlen( $name ) > $wgMaxNameChars
861 ||
$name != $wgContLang->ucfirst( $name )
866 // Ensure that the name can't be misresolved as a different title,
867 // such as with extra namespace keys at the start.
868 $parsed = Title
::newFromText( $name );
869 if ( is_null( $parsed )
870 ||
$parsed->getNamespace()
871 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
875 // Check an additional blacklist of troublemaker characters.
876 // Should these be merged into the title char list?
877 $unicodeBlacklist = '/[' .
878 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
879 '\x{00a0}' . # non-breaking space
880 '\x{2000}-\x{200f}' . # various whitespace
881 '\x{2028}-\x{202f}' . # breaks and control chars
882 '\x{3000}' . # ideographic space
883 '\x{e000}-\x{f8ff}' . # private use
885 if ( preg_match( $unicodeBlacklist, $name ) ) {
893 * Usernames which fail to pass this function will be blocked
894 * from user login and new account registrations, but may be used
895 * internally by batch processes.
897 * If an account already exists in this form, login will be blocked
898 * by a failure to pass this function.
900 * @param string $name Name to match
903 public static function isUsableName( $name ) {
904 global $wgReservedUsernames;
905 // Must be a valid username, obviously ;)
906 if ( !self
::isValidUserName( $name ) ) {
910 static $reservedUsernames = false;
911 if ( !$reservedUsernames ) {
912 $reservedUsernames = $wgReservedUsernames;
913 Hooks
::run( 'UserGetReservedNames', [ &$reservedUsernames ] );
916 // Certain names may be reserved for batch processes.
917 foreach ( $reservedUsernames as $reserved ) {
918 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
919 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
921 if ( $reserved == $name ) {
929 * Usernames which fail to pass this function will be blocked
930 * from new account registrations, but may be used internally
931 * either by batch processes or by user accounts which have
932 * already been created.
934 * Additional blacklisting may be added here rather than in
935 * isValidUserName() to avoid disrupting existing accounts.
937 * @param string $name String to match
940 public static function isCreatableName( $name ) {
941 global $wgInvalidUsernameCharacters;
943 // Ensure that the username isn't longer than 235 bytes, so that
944 // (at least for the builtin skins) user javascript and css files
945 // will work. (bug 23080)
946 if ( strlen( $name ) > 235 ) {
947 wfDebugLog( 'username', __METHOD__
.
948 ": '$name' invalid due to length" );
952 // Preg yells if you try to give it an empty string
953 if ( $wgInvalidUsernameCharacters !== '' ) {
954 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
955 wfDebugLog( 'username', __METHOD__
.
956 ": '$name' invalid due to wgInvalidUsernameCharacters" );
961 return self
::isUsableName( $name );
965 * Is the input a valid password for this user?
967 * @param string $password Desired password
970 public function isValidPassword( $password ) {
971 // simple boolean wrapper for getPasswordValidity
972 return $this->getPasswordValidity( $password ) === true;
976 * Given unvalidated password input, return error message on failure.
978 * @param string $password Desired password
979 * @return bool|string|array True on success, string or array of error message on failure
981 public function getPasswordValidity( $password ) {
982 $result = $this->checkPasswordValidity( $password );
983 if ( $result->isGood() ) {
987 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
988 $messages[] = $error['message'];
990 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
991 $messages[] = $warning['message'];
993 if ( count( $messages ) === 1 ) {
1001 * Check if this is a valid password for this user
1003 * Create a Status object based on the password's validity.
1004 * The Status should be set to fatal if the user should not
1005 * be allowed to log in, and should have any errors that
1006 * would block changing the password.
1008 * If the return value of this is not OK, the password
1009 * should not be checked. If the return value is not Good,
1010 * the password can be checked, but the user should not be
1011 * able to set their password to this.
1013 * @param string $password Desired password
1014 * @param string $purpose one of 'login', 'create', 'reset'
1018 public function checkPasswordValidity( $password, $purpose = 'login' ) {
1019 global $wgPasswordPolicy;
1021 $upp = new UserPasswordPolicy(
1022 $wgPasswordPolicy['policies'],
1023 $wgPasswordPolicy['checks']
1026 $status = Status
::newGood();
1027 $result = false; // init $result to false for the internal checks
1029 if ( !Hooks
::run( 'isValidPassword', [ $password, &$result, $this ] ) ) {
1030 $status->error( $result );
1034 if ( $result === false ) {
1035 $status->merge( $upp->checkUserPassword( $this, $password, $purpose ) );
1037 } elseif ( $result === true ) {
1040 $status->error( $result );
1041 return $status; // the isValidPassword hook set a string $result and returned true
1046 * Given unvalidated user input, return a canonical username, or false if
1047 * the username is invalid.
1048 * @param string $name User input
1049 * @param string|bool $validate Type of validation to use:
1050 * - false No validation
1051 * - 'valid' Valid for batch processes
1052 * - 'usable' Valid for batch processes and login
1053 * - 'creatable' Valid for batch processes, login and account creation
1055 * @throws InvalidArgumentException
1056 * @return bool|string
1058 public static function getCanonicalName( $name, $validate = 'valid' ) {
1059 // Force usernames to capital
1061 $name = $wgContLang->ucfirst( $name );
1063 # Reject names containing '#'; these will be cleaned up
1064 # with title normalisation, but then it's too late to
1066 if ( strpos( $name, '#' ) !== false ) {
1070 // Clean up name according to title rules,
1071 // but only when validation is requested (bug 12654)
1072 $t = ( $validate !== false ) ?
1073 Title
::newFromText( $name, NS_USER
) : Title
::makeTitle( NS_USER
, $name );
1074 // Check for invalid titles
1075 if ( is_null( $t ) ||
$t->getNamespace() !== NS_USER ||
$t->isExternal() ) {
1079 // Reject various classes of invalid names
1081 $name = $wgAuth->getCanonicalName( $t->getText() );
1083 switch ( $validate ) {
1087 if ( !User
::isValidUserName( $name ) ) {
1092 if ( !User
::isUsableName( $name ) ) {
1097 if ( !User
::isCreatableName( $name ) ) {
1102 throw new InvalidArgumentException(
1103 'Invalid parameter value for $validate in ' . __METHOD__
);
1109 * Count the number of edits of a user
1111 * @param int $uid User ID to check
1112 * @return int The user's edit count
1114 * @deprecated since 1.21 in favour of User::getEditCount
1116 public static function edits( $uid ) {
1117 wfDeprecated( __METHOD__
, '1.21' );
1118 $user = self
::newFromId( $uid );
1119 return $user->getEditCount();
1123 * Return a random password.
1125 * @deprecated since 1.27, use PasswordFactory::generateRandomPasswordString()
1126 * @return string New random password
1128 public static function randomPassword() {
1129 global $wgMinimalPasswordLength;
1130 return PasswordFactory
::generateRandomPasswordString( $wgMinimalPasswordLength );
1134 * Set cached properties to default.
1136 * @note This no longer clears uncached lazy-initialised properties;
1137 * the constructor does that instead.
1139 * @param string|bool $name
1141 public function loadDefaults( $name = false ) {
1143 $this->mName
= $name;
1144 $this->mRealName
= '';
1146 $this->mOptionOverrides
= null;
1147 $this->mOptionsLoaded
= false;
1149 $loggedOut = $this->mRequest
&& !defined( 'MW_NO_SESSION' )
1150 ?
$this->mRequest
->getSession()->getLoggedOutTimestamp() : 0;
1151 if ( $loggedOut !== 0 ) {
1152 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1154 $this->mTouched
= '1'; # Allow any pages to be cached
1157 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1158 $this->mEmailAuthenticated
= null;
1159 $this->mEmailToken
= '';
1160 $this->mEmailTokenExpires
= null;
1161 $this->mRegistration
= wfTimestamp( TS_MW
);
1162 $this->mGroups
= [];
1164 Hooks
::run( 'UserLoadDefaults', [ $this, $name ] );
1168 * Return whether an item has been loaded.
1170 * @param string $item Item to check. Current possibilities:
1174 * @param string $all 'all' to check if the whole object has been loaded
1175 * or any other string to check if only the item is available (e.g.
1179 public function isItemLoaded( $item, $all = 'all' ) {
1180 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1181 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1185 * Set that an item has been loaded
1187 * @param string $item
1189 protected function setItemLoaded( $item ) {
1190 if ( is_array( $this->mLoadedItems
) ) {
1191 $this->mLoadedItems
[$item] = true;
1196 * Load user data from the session.
1198 * @return bool True if the user is logged in, false otherwise.
1200 private function loadFromSession() {
1203 Hooks
::run( 'UserLoadFromSession', [ $this, &$result ], '1.27' );
1204 if ( $result !== null ) {
1208 // MediaWiki\Session\Session already did the necessary authentication of the user
1209 // returned here, so just use it if applicable.
1210 $session = $this->getRequest()->getSession();
1211 $user = $session->getUser();
1212 if ( $user->isLoggedIn() ) {
1213 $this->loadFromUserObject( $user );
1214 // Other code expects these to be set in the session, so set them.
1215 $session->set( 'wsUserID', $this->getId() );
1216 $session->set( 'wsUserName', $this->getName() );
1217 $session->set( 'wsToken', $this->getToken() );
1225 * Load user and user_group data from the database.
1226 * $this->mId must be set, this is how the user is identified.
1228 * @param integer $flags User::READ_* constant bitfield
1229 * @return bool True if the user exists, false if the user is anonymous
1231 public function loadFromDatabase( $flags = self
::READ_LATEST
) {
1233 $this->mId
= intval( $this->mId
);
1236 if ( !$this->mId
) {
1237 $this->loadDefaults();
1241 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
1242 $db = wfGetDB( $index );
1244 $s = $db->selectRow(
1246 self
::selectFields(),
1247 [ 'user_id' => $this->mId
],
1252 $this->queryFlagsUsed
= $flags;
1253 Hooks
::run( 'UserLoadFromDatabase', [ $this, &$s ] );
1255 if ( $s !== false ) {
1256 // Initialise user table data
1257 $this->loadFromRow( $s );
1258 $this->mGroups
= null; // deferred
1259 $this->getEditCount(); // revalidation for nulls
1264 $this->loadDefaults();
1270 * Initialize this object from a row from the user table.
1272 * @param stdClass $row Row from the user table to load.
1273 * @param array $data Further user data to load into the object
1275 * user_groups Array with groups out of the user_groups table
1276 * user_properties Array with properties out of the user_properties table
1278 protected function loadFromRow( $row, $data = null ) {
1281 $this->mGroups
= null; // deferred
1283 if ( isset( $row->user_name
) ) {
1284 $this->mName
= $row->user_name
;
1285 $this->mFrom
= 'name';
1286 $this->setItemLoaded( 'name' );
1291 if ( isset( $row->user_real_name
) ) {
1292 $this->mRealName
= $row->user_real_name
;
1293 $this->setItemLoaded( 'realname' );
1298 if ( isset( $row->user_id
) ) {
1299 $this->mId
= intval( $row->user_id
);
1300 $this->mFrom
= 'id';
1301 $this->setItemLoaded( 'id' );
1306 if ( isset( $row->user_id
) && isset( $row->user_name
) ) {
1307 self
::$idCacheByName[$row->user_name
] = $row->user_id
;
1310 if ( isset( $row->user_editcount
) ) {
1311 $this->mEditCount
= $row->user_editcount
;
1316 if ( isset( $row->user_touched
) ) {
1317 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1322 if ( isset( $row->user_token
) ) {
1323 // The definition for the column is binary(32), so trim the NULs
1324 // that appends. The previous definition was char(32), so trim
1326 $this->mToken
= rtrim( $row->user_token
, " \0" );
1327 if ( $this->mToken
=== '' ) {
1328 $this->mToken
= null;
1334 if ( isset( $row->user_email
) ) {
1335 $this->mEmail
= $row->user_email
;
1336 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1337 $this->mEmailToken
= $row->user_email_token
;
1338 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1339 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1345 $this->mLoadedItems
= true;
1348 if ( is_array( $data ) ) {
1349 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1350 $this->mGroups
= $data['user_groups'];
1352 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1353 $this->loadOptions( $data['user_properties'] );
1359 * Load the data for this user object from another user object.
1363 protected function loadFromUserObject( $user ) {
1365 $user->loadGroups();
1366 $user->loadOptions();
1367 foreach ( self
::$mCacheVars as $var ) {
1368 $this->$var = $user->$var;
1373 * Load the groups from the database if they aren't already loaded.
1375 private function loadGroups() {
1376 if ( is_null( $this->mGroups
) ) {
1377 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
1378 ?
wfGetDB( DB_MASTER
)
1379 : wfGetDB( DB_SLAVE
);
1380 $res = $db->select( 'user_groups',
1382 [ 'ug_user' => $this->mId
],
1384 $this->mGroups
= [];
1385 foreach ( $res as $row ) {
1386 $this->mGroups
[] = $row->ug_group
;
1392 * Add the user to the group if he/she meets given criteria.
1394 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1395 * possible to remove manually via Special:UserRights. In such case it
1396 * will not be re-added automatically. The user will also not lose the
1397 * group if they no longer meet the criteria.
1399 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1401 * @return array Array of groups the user has been promoted to.
1403 * @see $wgAutopromoteOnce
1405 public function addAutopromoteOnceGroups( $event ) {
1406 global $wgAutopromoteOnceLogInRC, $wgAuth;
1408 if ( wfReadOnly() ||
!$this->getId() ) {
1412 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1413 if ( !count( $toPromote ) ) {
1417 if ( !$this->checkAndSetTouched() ) {
1418 return []; // raced out (bug T48834)
1421 $oldGroups = $this->getGroups(); // previous groups
1422 foreach ( $toPromote as $group ) {
1423 $this->addGroup( $group );
1425 // update groups in external authentication database
1426 Hooks
::run( 'UserGroupsChanged', [ $this, $toPromote, [], false, false ] );
1427 $wgAuth->updateExternalDBGroups( $this, $toPromote );
1429 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1431 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1432 $logEntry->setPerformer( $this );
1433 $logEntry->setTarget( $this->getUserPage() );
1434 $logEntry->setParameters( [
1435 '4::oldgroups' => $oldGroups,
1436 '5::newgroups' => $newGroups,
1438 $logid = $logEntry->insert();
1439 if ( $wgAutopromoteOnceLogInRC ) {
1440 $logEntry->publish( $logid );
1447 * Bump user_touched if it didn't change since this object was loaded
1449 * On success, the mTouched field is updated.
1450 * The user serialization cache is always cleared.
1452 * @return bool Whether user_touched was actually updated
1455 protected function checkAndSetTouched() {
1458 if ( !$this->mId
) {
1459 return false; // anon
1462 // Get a new user_touched that is higher than the old one
1463 $oldTouched = $this->mTouched
;
1464 $newTouched = $this->newTouchedTimestamp();
1466 $dbw = wfGetDB( DB_MASTER
);
1467 $dbw->update( 'user',
1468 [ 'user_touched' => $dbw->timestamp( $newTouched ) ],
1470 'user_id' => $this->mId
,
1471 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
1475 $success = ( $dbw->affectedRows() > 0 );
1478 $this->mTouched
= $newTouched;
1479 $this->clearSharedCache();
1481 // Clears on failure too since that is desired if the cache is stale
1482 $this->clearSharedCache( 'refresh' );
1489 * Clear various cached data stored in this object. The cache of the user table
1490 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1492 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1493 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1495 public function clearInstanceCache( $reloadFrom = false ) {
1496 $this->mNewtalk
= -1;
1497 $this->mDatePreference
= null;
1498 $this->mBlockedby
= -1; # Unset
1499 $this->mHash
= false;
1500 $this->mRights
= null;
1501 $this->mEffectiveGroups
= null;
1502 $this->mImplicitGroups
= null;
1503 $this->mGroups
= null;
1504 $this->mOptions
= null;
1505 $this->mOptionsLoaded
= false;
1506 $this->mEditCount
= null;
1508 if ( $reloadFrom ) {
1509 $this->mLoadedItems
= [];
1510 $this->mFrom
= $reloadFrom;
1515 * Combine the language default options with any site-specific options
1516 * and add the default language variants.
1518 * @return array Array of String options
1520 public static function getDefaultOptions() {
1521 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1523 static $defOpt = null;
1524 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1525 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1526 // mid-request and see that change reflected in the return value of this function.
1527 // Which is insane and would never happen during normal MW operation
1531 $defOpt = $wgDefaultUserOptions;
1532 // Default language setting
1533 $defOpt['language'] = $wgContLang->getCode();
1534 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1535 $defOpt[$langCode == $wgContLang->getCode() ?
'variant' : "variant-$langCode"] = $langCode;
1537 foreach ( SearchEngine
::searchableNamespaces() as $nsnum => $nsname ) {
1538 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1540 $defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1542 Hooks
::run( 'UserGetDefaultOptions', [ &$defOpt ] );
1548 * Get a given default option value.
1550 * @param string $opt Name of option to retrieve
1551 * @return string Default option value
1553 public static function getDefaultOption( $opt ) {
1554 $defOpts = self
::getDefaultOptions();
1555 if ( isset( $defOpts[$opt] ) ) {
1556 return $defOpts[$opt];
1563 * Get blocking information
1564 * @param bool $bFromSlave Whether to check the slave database first.
1565 * To improve performance, non-critical checks are done against slaves.
1566 * Check when actually saving should be done against master.
1568 private function getBlockedStatus( $bFromSlave = true ) {
1569 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1571 if ( -1 != $this->mBlockedby
) {
1575 wfDebug( __METHOD__
. ": checking...\n" );
1577 // Initialize data...
1578 // Otherwise something ends up stomping on $this->mBlockedby when
1579 // things get lazy-loaded later, causing false positive block hits
1580 // due to -1 !== 0. Probably session-related... Nothing should be
1581 // overwriting mBlockedby, surely?
1584 # We only need to worry about passing the IP address to the Block generator if the
1585 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1586 # know which IP address they're actually coming from
1588 if ( !$this->isAllowed( 'ipblock-exempt' ) ) {
1589 // $wgUser->getName() only works after the end of Setup.php. Until
1590 // then, assume it's a logged-out user.
1591 $globalUserName = $wgUser->isSafeToLoad()
1592 ?
$wgUser->getName()
1593 : IP
::sanitizeIP( $wgUser->getRequest()->getIP() );
1594 if ( $this->getName() === $globalUserName ) {
1595 $ip = $this->getRequest()->getIP();
1600 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1603 if ( !$block instanceof Block
&& $ip !== null && !in_array( $ip, $wgProxyWhitelist ) ) {
1605 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1607 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1608 $block->mReason
= wfMessage( 'proxyblockreason' )->text();
1609 $block->setTarget( $ip );
1610 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1612 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1613 $block->mReason
= wfMessage( 'sorbsreason' )->text();
1614 $block->setTarget( $ip );
1618 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1619 if ( !$block instanceof Block
1620 && $wgApplyIpBlocksToXff
1622 && !in_array( $ip, $wgProxyWhitelist )
1624 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1625 $xff = array_map( 'trim', explode( ',', $xff ) );
1626 $xff = array_diff( $xff, [ $ip ] );
1627 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1628 $block = Block
::chooseBlock( $xffblocks, $xff );
1629 if ( $block instanceof Block
) {
1630 # Mangle the reason to alert the user that the block
1631 # originated from matching the X-Forwarded-For header.
1632 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->text();
1636 if ( $block instanceof Block
) {
1637 wfDebug( __METHOD__
. ": Found block.\n" );
1638 $this->mBlock
= $block;
1639 $this->mBlockedby
= $block->getByName();
1640 $this->mBlockreason
= $block->mReason
;
1641 $this->mHideName
= $block->mHideName
;
1642 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1644 $this->mBlockedby
= '';
1645 $this->mHideName
= 0;
1646 $this->mAllowUsertalk
= false;
1650 Hooks
::run( 'GetBlockedStatus', [ &$this ] );
1655 * Whether the given IP is in a DNS blacklist.
1657 * @param string $ip IP to check
1658 * @param bool $checkWhitelist Whether to check the whitelist first
1659 * @return bool True if blacklisted.
1661 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1662 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1664 if ( !$wgEnableDnsBlacklist ) {
1668 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1672 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1676 * Whether the given IP is in a given DNS blacklist.
1678 * @param string $ip IP to check
1679 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1680 * @return bool True if blacklisted.
1682 public function inDnsBlacklist( $ip, $bases ) {
1685 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1686 if ( IP
::isIPv4( $ip ) ) {
1687 // Reverse IP, bug 21255
1688 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1690 foreach ( (array)$bases as $base ) {
1692 // If we have an access key, use that too (ProjectHoneypot, etc.)
1694 if ( is_array( $base ) ) {
1695 if ( count( $base ) >= 2 ) {
1696 // Access key is 1, base URL is 0
1697 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1699 $host = "$ipReversed.{$base[0]}";
1701 $basename = $base[0];
1703 $host = "$ipReversed.$base";
1707 $ipList = gethostbynamel( $host );
1710 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
1714 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
1723 * Check if an IP address is in the local proxy list
1729 public static function isLocallyBlockedProxy( $ip ) {
1730 global $wgProxyList;
1732 if ( !$wgProxyList ) {
1736 if ( !is_array( $wgProxyList ) ) {
1737 // Load from the specified file
1738 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1741 if ( !is_array( $wgProxyList ) ) {
1743 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1745 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1746 // Old-style flipped proxy list
1755 * Is this user subject to rate limiting?
1757 * @return bool True if rate limited
1759 public function isPingLimitable() {
1760 global $wgRateLimitsExcludedIPs;
1761 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1762 // No other good way currently to disable rate limits
1763 // for specific IPs. :P
1764 // But this is a crappy hack and should die.
1767 return !$this->isAllowed( 'noratelimit' );
1771 * Primitive rate limits: enforce maximum actions per time period
1772 * to put a brake on flooding.
1774 * The method generates both a generic profiling point and a per action one
1775 * (suffix being "-$action".
1777 * @note When using a shared cache like memcached, IP-address
1778 * last-hit counters will be shared across wikis.
1780 * @param string $action Action to enforce; 'edit' if unspecified
1781 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1782 * @return bool True if a rate limiter was tripped
1784 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1785 // Call the 'PingLimiter' hook
1787 if ( !Hooks
::run( 'PingLimiter', [ &$this, $action, &$result, $incrBy ] ) ) {
1791 global $wgRateLimits;
1792 if ( !isset( $wgRateLimits[$action] ) ) {
1796 // Some groups shouldn't trigger the ping limiter, ever
1797 if ( !$this->isPingLimitable() ) {
1801 $limits = $wgRateLimits[$action];
1803 $id = $this->getId();
1805 $isNewbie = $this->isNewbie();
1809 if ( isset( $limits['anon'] ) ) {
1810 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1813 // limits for logged-in users
1814 if ( isset( $limits['user'] ) ) {
1815 $userLimit = $limits['user'];
1817 // limits for newbie logged-in users
1818 if ( $isNewbie && isset( $limits['newbie'] ) ) {
1819 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1823 // limits for anons and for newbie logged-in users
1826 if ( isset( $limits['ip'] ) ) {
1827 $ip = $this->getRequest()->getIP();
1828 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1830 // subnet-based limits
1831 if ( isset( $limits['subnet'] ) ) {
1832 $ip = $this->getRequest()->getIP();
1833 $subnet = IP
::getSubnet( $ip );
1834 if ( $subnet !== false ) {
1835 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1840 // Check for group-specific permissions
1841 // If more than one group applies, use the group with the highest limit ratio (max/period)
1842 foreach ( $this->getGroups() as $group ) {
1843 if ( isset( $limits[$group] ) ) {
1844 if ( $userLimit === false
1845 ||
$limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1847 $userLimit = $limits[$group];
1852 // Set the user limit key
1853 if ( $userLimit !== false ) {
1854 list( $max, $period ) = $userLimit;
1855 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
1856 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1859 // ip-based limits for all ping-limitable users
1860 if ( isset( $limits['ip-all'] ) ) {
1861 $ip = $this->getRequest()->getIP();
1862 // ignore if user limit is more permissive
1863 if ( $isNewbie ||
$userLimit === false
1864 ||
$limits['ip-all'][0] / $limits['ip-all'][1] > $userLimit[0] / $userLimit[1] ) {
1865 $keys["mediawiki:limiter:$action:ip-all:$ip"] = $limits['ip-all'];
1869 // subnet-based limits for all ping-limitable users
1870 if ( isset( $limits['subnet-all'] ) ) {
1871 $ip = $this->getRequest()->getIP();
1872 $subnet = IP
::getSubnet( $ip );
1873 if ( $subnet !== false ) {
1874 // ignore if user limit is more permissive
1875 if ( $isNewbie ||
$userLimit === false
1876 ||
$limits['ip-all'][0] / $limits['ip-all'][1]
1877 > $userLimit[0] / $userLimit[1] ) {
1878 $keys["mediawiki:limiter:$action:subnet-all:$subnet"] = $limits['subnet-all'];
1883 $cache = ObjectCache
::getLocalClusterInstance();
1886 foreach ( $keys as $key => $limit ) {
1887 list( $max, $period ) = $limit;
1888 $summary = "(limit $max in {$period}s)";
1889 $count = $cache->get( $key );
1892 if ( $count >= $max ) {
1893 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1894 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1897 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1900 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1901 if ( $incrBy > 0 ) {
1902 $cache->add( $key, 0, intval( $period ) ); // first ping
1905 if ( $incrBy > 0 ) {
1906 $cache->incr( $key, $incrBy );
1914 * Check if user is blocked
1916 * @param bool $bFromSlave Whether to check the slave database instead of
1917 * the master. Hacked from false due to horrible probs on site.
1918 * @return bool True if blocked, false otherwise
1920 public function isBlocked( $bFromSlave = true ) {
1921 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
1925 * Get the block affecting the user, or null if the user is not blocked
1927 * @param bool $bFromSlave Whether to check the slave database instead of the master
1928 * @return Block|null
1930 public function getBlock( $bFromSlave = true ) {
1931 $this->getBlockedStatus( $bFromSlave );
1932 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
1936 * Check if user is blocked from editing a particular article
1938 * @param Title $title Title to check
1939 * @param bool $bFromSlave Whether to check the slave database instead of the master
1942 public function isBlockedFrom( $title, $bFromSlave = false ) {
1943 global $wgBlockAllowsUTEdit;
1945 $blocked = $this->isBlocked( $bFromSlave );
1946 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
1947 // If a user's name is suppressed, they cannot make edits anywhere
1948 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName()
1949 && $title->getNamespace() == NS_USER_TALK
) {
1951 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
1954 Hooks
::run( 'UserIsBlockedFrom', [ $this, $title, &$blocked, &$allowUsertalk ] );
1960 * If user is blocked, return the name of the user who placed the block
1961 * @return string Name of blocker
1963 public function blockedBy() {
1964 $this->getBlockedStatus();
1965 return $this->mBlockedby
;
1969 * If user is blocked, return the specified reason for the block
1970 * @return string Blocking reason
1972 public function blockedFor() {
1973 $this->getBlockedStatus();
1974 return $this->mBlockreason
;
1978 * If user is blocked, return the ID for the block
1979 * @return int Block ID
1981 public function getBlockId() {
1982 $this->getBlockedStatus();
1983 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
1987 * Check if user is blocked on all wikis.
1988 * Do not use for actual edit permission checks!
1989 * This is intended for quick UI checks.
1991 * @param string $ip IP address, uses current client if none given
1992 * @return bool True if blocked, false otherwise
1994 public function isBlockedGlobally( $ip = '' ) {
1995 if ( $this->mBlockedGlobally
!== null ) {
1996 return $this->mBlockedGlobally
;
1998 // User is already an IP?
1999 if ( IP
::isIPAddress( $this->getName() ) ) {
2000 $ip = $this->getName();
2002 $ip = $this->getRequest()->getIP();
2005 Hooks
::run( 'UserIsBlockedGlobally', [ &$this, $ip, &$blocked ] );
2006 $this->mBlockedGlobally
= (bool)$blocked;
2007 return $this->mBlockedGlobally
;
2011 * Check if user account is locked
2013 * @return bool True if locked, false otherwise
2015 public function isLocked() {
2016 if ( $this->mLocked
!== null ) {
2017 return $this->mLocked
;
2020 $authUser = $wgAuth->getUserInstance( $this );
2021 $this->mLocked
= (bool)$authUser->isLocked();
2022 Hooks
::run( 'UserIsLocked', [ $this, &$this->mLocked
] );
2023 return $this->mLocked
;
2027 * Check if user account is hidden
2029 * @return bool True if hidden, false otherwise
2031 public function isHidden() {
2032 if ( $this->mHideName
!== null ) {
2033 return $this->mHideName
;
2035 $this->getBlockedStatus();
2036 if ( !$this->mHideName
) {
2038 $authUser = $wgAuth->getUserInstance( $this );
2039 $this->mHideName
= (bool)$authUser->isHidden();
2040 Hooks
::run( 'UserIsHidden', [ $this, &$this->mHideName
] );
2042 return $this->mHideName
;
2046 * Get the user's ID.
2047 * @return int The user's ID; 0 if the user is anonymous or nonexistent
2049 public function getId() {
2050 if ( $this->mId
=== null && $this->mName
!== null && User
::isIP( $this->mName
) ) {
2051 // Special case, we know the user is anonymous
2053 } elseif ( !$this->isItemLoaded( 'id' ) ) {
2054 // Don't load if this was initialized from an ID
2058 return (int)$this->mId
;
2062 * Set the user and reload all fields according to a given ID
2063 * @param int $v User ID to reload
2065 public function setId( $v ) {
2067 $this->clearInstanceCache( 'id' );
2071 * Get the user name, or the IP of an anonymous user
2072 * @return string User's name or IP address
2074 public function getName() {
2075 if ( $this->isItemLoaded( 'name', 'only' ) ) {
2076 // Special case optimisation
2077 return $this->mName
;
2080 if ( $this->mName
=== false ) {
2082 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
2084 return $this->mName
;
2089 * Set the user name.
2091 * This does not reload fields from the database according to the given
2092 * name. Rather, it is used to create a temporary "nonexistent user" for
2093 * later addition to the database. It can also be used to set the IP
2094 * address for an anonymous user to something other than the current
2097 * @note User::newFromName() has roughly the same function, when the named user
2099 * @param string $str New user name to set
2101 public function setName( $str ) {
2103 $this->mName
= $str;
2107 * Get the user's name escaped by underscores.
2108 * @return string Username escaped by underscores.
2110 public function getTitleKey() {
2111 return str_replace( ' ', '_', $this->getName() );
2115 * Check if the user has new messages.
2116 * @return bool True if the user has new messages
2118 public function getNewtalk() {
2121 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2122 if ( $this->mNewtalk
=== -1 ) {
2123 $this->mNewtalk
= false; # reset talk page status
2125 // Check memcached separately for anons, who have no
2126 // entire User object stored in there.
2127 if ( !$this->mId
) {
2128 global $wgDisableAnonTalk;
2129 if ( $wgDisableAnonTalk ) {
2130 // Anon newtalk disabled by configuration.
2131 $this->mNewtalk
= false;
2133 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
2136 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2140 return (bool)$this->mNewtalk
;
2144 * Return the data needed to construct links for new talk page message
2145 * alerts. If there are new messages, this will return an associative array
2146 * with the following data:
2147 * wiki: The database name of the wiki
2148 * link: Root-relative link to the user's talk page
2149 * rev: The last talk page revision that the user has seen or null. This
2150 * is useful for building diff links.
2151 * If there are no new messages, it returns an empty array.
2152 * @note This function was designed to accomodate multiple talk pages, but
2153 * currently only returns a single link and revision.
2156 public function getNewMessageLinks() {
2158 if ( !Hooks
::run( 'UserRetrieveNewTalks', [ &$this, &$talks ] ) ) {
2160 } elseif ( !$this->getNewtalk() ) {
2163 $utp = $this->getTalkPage();
2164 $dbr = wfGetDB( DB_SLAVE
);
2165 // Get the "last viewed rev" timestamp from the oldest message notification
2166 $timestamp = $dbr->selectField( 'user_newtalk',
2167 'MIN(user_last_timestamp)',
2168 $this->isAnon() ?
[ 'user_ip' => $this->getName() ] : [ 'user_id' => $this->getId() ],
2170 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2171 return [ [ 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ] ];
2175 * Get the revision ID for the last talk page revision viewed by the talk
2177 * @return int|null Revision ID or null
2179 public function getNewMessageRevisionId() {
2180 $newMessageRevisionId = null;
2181 $newMessageLinks = $this->getNewMessageLinks();
2182 if ( $newMessageLinks ) {
2183 // Note: getNewMessageLinks() never returns more than a single link
2184 // and it is always for the same wiki, but we double-check here in
2185 // case that changes some time in the future.
2186 if ( count( $newMessageLinks ) === 1
2187 && $newMessageLinks[0]['wiki'] === wfWikiID()
2188 && $newMessageLinks[0]['rev']
2190 /** @var Revision $newMessageRevision */
2191 $newMessageRevision = $newMessageLinks[0]['rev'];
2192 $newMessageRevisionId = $newMessageRevision->getId();
2195 return $newMessageRevisionId;
2199 * Internal uncached check for new messages
2202 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2203 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2204 * @return bool True if the user has new messages
2206 protected function checkNewtalk( $field, $id ) {
2207 $dbr = wfGetDB( DB_SLAVE
);
2209 $ok = $dbr->selectField( 'user_newtalk', $field, [ $field => $id ], __METHOD__
);
2211 return $ok !== false;
2215 * Add or update the new messages flag
2216 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2217 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2218 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2219 * @return bool True if successful, false otherwise
2221 protected function updateNewtalk( $field, $id, $curRev = null ) {
2222 // Get timestamp of the talk page revision prior to the current one
2223 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2224 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2225 // Mark the user as having new messages since this revision
2226 $dbw = wfGetDB( DB_MASTER
);
2227 $dbw->insert( 'user_newtalk',
2228 [ $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ],
2231 if ( $dbw->affectedRows() ) {
2232 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2235 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2241 * Clear the new messages flag for the given user
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 * @return bool True if successful, false otherwise
2246 protected function deleteNewtalk( $field, $id ) {
2247 $dbw = wfGetDB( DB_MASTER
);
2248 $dbw->delete( 'user_newtalk',
2251 if ( $dbw->affectedRows() ) {
2252 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2255 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2261 * Update the 'You have new messages!' status.
2262 * @param bool $val Whether the user has new messages
2263 * @param Revision $curRev New, as yet unseen revision of the user talk
2264 * page. Ignored if null or !$val.
2266 public function setNewtalk( $val, $curRev = null ) {
2267 if ( wfReadOnly() ) {
2272 $this->mNewtalk
= $val;
2274 if ( $this->isAnon() ) {
2276 $id = $this->getName();
2279 $id = $this->getId();
2283 $changed = $this->updateNewtalk( $field, $id, $curRev );
2285 $changed = $this->deleteNewtalk( $field, $id );
2289 $this->invalidateCache();
2294 * Generate a current or new-future timestamp to be stored in the
2295 * user_touched field when we update things.
2296 * @return string Timestamp in TS_MW format
2298 private function newTouchedTimestamp() {
2299 global $wgClockSkewFudge;
2301 $time = wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2302 if ( $this->mTouched
&& $time <= $this->mTouched
) {
2303 $time = wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $this->mTouched
) +
1 );
2310 * Clear user data from memcached
2312 * Use after applying updates to the database; caller's
2313 * responsibility to update user_touched if appropriate.
2315 * Called implicitly from invalidateCache() and saveSettings().
2317 * @param string $mode Use 'refresh' to clear now; otherwise before DB commit
2319 public function clearSharedCache( $mode = 'changed' ) {
2320 if ( !$this->getId() ) {
2324 $cache = ObjectCache
::getMainWANInstance();
2325 $processCache = self
::getInProcessCache();
2326 $key = $this->getCacheKey( $cache );
2327 if ( $mode === 'refresh' ) {
2328 $cache->delete( $key, 1 );
2329 $processCache->delete( $key );
2331 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle(
2332 function() use ( $cache, $processCache, $key ) {
2333 $cache->delete( $key );
2334 $processCache->delete( $key );
2341 * Immediately touch the user data cache for this account
2343 * Calls touch() and removes account data from memcached
2345 public function invalidateCache() {
2347 $this->clearSharedCache();
2351 * Update the "touched" timestamp for the user
2353 * This is useful on various login/logout events when making sure that
2354 * a browser or proxy that has multiple tenants does not suffer cache
2355 * pollution where the new user sees the old users content. The value
2356 * of getTouched() is checked when determining 304 vs 200 responses.
2357 * Unlike invalidateCache(), this preserves the User object cache and
2358 * avoids database writes.
2362 public function touch() {
2363 $id = $this->getId();
2365 $key = wfMemcKey( 'user-quicktouched', 'id', $id );
2366 ObjectCache
::getMainWANInstance()->touchCheckKey( $key );
2367 $this->mQuickTouched
= null;
2372 * Validate the cache for this account.
2373 * @param string $timestamp A timestamp in TS_MW format
2376 public function validateCache( $timestamp ) {
2377 return ( $timestamp >= $this->getTouched() );
2381 * Get the user touched timestamp
2383 * Use this value only to validate caches via inequalities
2384 * such as in the case of HTTP If-Modified-Since response logic
2386 * @return string TS_MW Timestamp
2388 public function getTouched() {
2392 if ( $this->mQuickTouched
=== null ) {
2393 $key = wfMemcKey( 'user-quicktouched', 'id', $this->mId
);
2394 $cache = ObjectCache
::getMainWANInstance();
2396 $this->mQuickTouched
= wfTimestamp( TS_MW
, $cache->getCheckKeyTime( $key ) );
2399 return max( $this->mTouched
, $this->mQuickTouched
);
2402 return $this->mTouched
;
2406 * Get the user_touched timestamp field (time of last DB updates)
2407 * @return string TS_MW Timestamp
2410 public function getDBTouched() {
2413 return $this->mTouched
;
2417 * @deprecated Removed in 1.27.
2421 public function getPassword() {
2422 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2426 * @deprecated Removed in 1.27.
2430 public function getTemporaryPassword() {
2431 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2435 * Set the password and reset the random token.
2436 * Calls through to authentication plugin if necessary;
2437 * will have no effect if the auth plugin refuses to
2438 * pass the change through or if the legal password
2441 * As a special case, setting the password to null
2442 * wipes it, so the account cannot be logged in until
2443 * a new password is set, for instance via e-mail.
2445 * @deprecated since 1.27. AuthManager is coming.
2446 * @param string $str New password to set
2447 * @throws PasswordError On failure
2450 public function setPassword( $str ) {
2453 if ( $str !== null ) {
2454 if ( !$wgAuth->allowPasswordChange() ) {
2455 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2458 $status = $this->checkPasswordValidity( $str );
2459 if ( !$status->isGood() ) {
2460 throw new PasswordError( $status->getMessage()->text() );
2464 if ( !$wgAuth->setPassword( $this, $str ) ) {
2465 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2469 $this->setOption( 'watchlisttoken', false );
2470 $this->setPasswordInternal( $str );
2476 * Set the password and reset the random token unconditionally.
2478 * @deprecated since 1.27. AuthManager is coming.
2479 * @param string|null $str New password to set or null to set an invalid
2480 * password hash meaning that the user will not be able to log in
2481 * through the web interface.
2483 public function setInternalPassword( $str ) {
2486 if ( $wgAuth->allowSetLocalPassword() ) {
2488 $this->setOption( 'watchlisttoken', false );
2489 $this->setPasswordInternal( $str );
2494 * Actually set the password and such
2495 * @since 1.27 cannot set a password for a user not in the database
2496 * @param string|null $str New password to set or null to set an invalid
2497 * password hash meaning that the user will not be able to log in
2498 * through the web interface.
2500 private function setPasswordInternal( $str ) {
2501 $id = self
::idFromName( $this->getName(), self
::READ_LATEST
);
2503 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2506 $passwordFactory = new PasswordFactory();
2507 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
2508 $dbw = wfGetDB( DB_MASTER
);
2512 'user_password' => $passwordFactory->newFromPlaintext( $str )->toString(),
2513 'user_newpassword' => PasswordFactory
::newInvalidPassword()->toString(),
2514 'user_newpass_time' => $dbw->timestampOrNull( null ),
2522 // When the main password is changed, invalidate all bot passwords too
2523 BotPassword
::invalidateAllPasswordsForUser( $this->getName() );
2527 * Get the user's current token.
2528 * @param bool $forceCreation Force the generation of a new token if the
2529 * user doesn't have one (default=true for backwards compatibility).
2530 * @return string|null Token
2532 public function getToken( $forceCreation = true ) {
2533 global $wgAuthenticationTokenVersion;
2536 if ( !$this->mToken
&& $forceCreation ) {
2540 if ( !$this->mToken
) {
2541 // The user doesn't have a token, return null to indicate that.
2543 } elseif ( $this->mToken
=== self
::INVALID_TOKEN
) {
2544 // We return a random value here so existing token checks are very
2546 return MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2547 } elseif ( $wgAuthenticationTokenVersion === null ) {
2548 // $wgAuthenticationTokenVersion not in use, so return the raw secret
2549 return $this->mToken
;
2551 // $wgAuthenticationTokenVersion in use, so hmac it.
2552 $ret = MWCryptHash
::hmac( $wgAuthenticationTokenVersion, $this->mToken
, false );
2554 // The raw hash can be overly long. Shorten it up.
2555 $len = max( 32, self
::TOKEN_LENGTH
);
2556 if ( strlen( $ret ) < $len ) {
2557 // Should never happen, even md5 is 128 bits
2558 throw new \
UnexpectedValueException( 'Hmac returned less than 128 bits' );
2560 return substr( $ret, -$len );
2565 * Set the random token (used for persistent authentication)
2566 * Called from loadDefaults() among other places.
2568 * @param string|bool $token If specified, set the token to this value
2570 public function setToken( $token = false ) {
2572 if ( $this->mToken
=== self
::INVALID_TOKEN
) {
2573 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
2574 ->debug( __METHOD__
. ": Ignoring attempt to set token for system user \"$this\"" );
2575 } elseif ( !$token ) {
2576 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2578 $this->mToken
= $token;
2583 * Set the password for a password reminder or new account email
2585 * @deprecated since 1.27, AuthManager is coming
2586 * @param string $str New password to set or null to set an invalid
2587 * password hash meaning that the user will not be able to use it
2588 * @param bool $throttle If true, reset the throttle timestamp to the present
2590 public function setNewpassword( $str, $throttle = true ) {
2591 $id = $this->getId();
2593 throw new LogicException( 'Cannot set new password for a user that is not in the database.' );
2596 $dbw = wfGetDB( DB_MASTER
);
2598 $passwordFactory = new PasswordFactory();
2599 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
2601 'user_newpassword' => $passwordFactory->newFromPlaintext( $str )->toString(),
2604 if ( $str === null ) {
2605 $update['user_newpass_time'] = null;
2606 } elseif ( $throttle ) {
2607 $update['user_newpass_time'] = $dbw->timestamp();
2610 $dbw->update( 'user', $update, [ 'user_id' => $id ], __METHOD__
);
2614 * Has password reminder email been sent within the last
2615 * $wgPasswordReminderResendTime hours?
2618 public function isPasswordReminderThrottled() {
2619 global $wgPasswordReminderResendTime;
2621 if ( !$wgPasswordReminderResendTime ) {
2627 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
2628 ?
wfGetDB( DB_MASTER
)
2629 : wfGetDB( DB_SLAVE
);
2630 $newpassTime = $db->selectField(
2632 'user_newpass_time',
2633 [ 'user_id' => $this->getId() ],
2637 if ( $newpassTime === null ) {
2640 $expiry = wfTimestamp( TS_UNIX
, $newpassTime ) +
$wgPasswordReminderResendTime * 3600;
2641 return time() < $expiry;
2645 * Get the user's e-mail address
2646 * @return string User's email address
2648 public function getEmail() {
2650 Hooks
::run( 'UserGetEmail', [ $this, &$this->mEmail
] );
2651 return $this->mEmail
;
2655 * Get the timestamp of the user's e-mail authentication
2656 * @return string TS_MW timestamp
2658 public function getEmailAuthenticationTimestamp() {
2660 Hooks
::run( 'UserGetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
2661 return $this->mEmailAuthenticated
;
2665 * Set the user's e-mail address
2666 * @param string $str New e-mail address
2668 public function setEmail( $str ) {
2670 if ( $str == $this->mEmail
) {
2673 $this->invalidateEmail();
2674 $this->mEmail
= $str;
2675 Hooks
::run( 'UserSetEmail', [ $this, &$this->mEmail
] );
2679 * Set the user's e-mail address and a confirmation mail if needed.
2682 * @param string $str New e-mail address
2685 public function setEmailWithConfirmation( $str ) {
2686 global $wgEnableEmail, $wgEmailAuthentication;
2688 if ( !$wgEnableEmail ) {
2689 return Status
::newFatal( 'emaildisabled' );
2692 $oldaddr = $this->getEmail();
2693 if ( $str === $oldaddr ) {
2694 return Status
::newGood( true );
2697 $type = $oldaddr != '' ?
'changed' : 'set';
2698 $notificationResult = null;
2700 if ( $wgEmailAuthentication ) {
2701 // Send the user an email notifying the user of the change in registered
2702 // email address on their previous email address
2703 if ( $type == 'changed' ) {
2704 $change = $str != '' ?
'changed' : 'removed';
2705 $notificationResult = $this->sendMail(
2706 wfMessage( 'notificationemail_subject_' . $change )->text(),
2707 wfMessage( 'notificationemail_body_' . $change,
2708 $this->getRequest()->getIP(),
2715 $this->setEmail( $str );
2717 if ( $str !== '' && $wgEmailAuthentication ) {
2718 // Send a confirmation request to the new address if needed
2719 $result = $this->sendConfirmationMail( $type );
2721 if ( $notificationResult !== null ) {
2722 $result->merge( $notificationResult );
2725 if ( $result->isGood() ) {
2726 // Say to the caller that a confirmation and notification mail has been sent
2727 $result->value
= 'eauth';
2730 $result = Status
::newGood( true );
2737 * Get the user's real name
2738 * @return string User's real name
2740 public function getRealName() {
2741 if ( !$this->isItemLoaded( 'realname' ) ) {
2745 return $this->mRealName
;
2749 * Set the user's real name
2750 * @param string $str New real name
2752 public function setRealName( $str ) {
2754 $this->mRealName
= $str;
2758 * Get the user's current setting for a given option.
2760 * @param string $oname The option to check
2761 * @param string $defaultOverride A default value returned if the option does not exist
2762 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2763 * @return string User's current value for the option
2764 * @see getBoolOption()
2765 * @see getIntOption()
2767 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2768 global $wgHiddenPrefs;
2769 $this->loadOptions();
2771 # We want 'disabled' preferences to always behave as the default value for
2772 # users, even if they have set the option explicitly in their settings (ie they
2773 # set it, and then it was disabled removing their ability to change it). But
2774 # we don't want to erase the preferences in the database in case the preference
2775 # is re-enabled again. So don't touch $mOptions, just override the returned value
2776 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2777 return self
::getDefaultOption( $oname );
2780 if ( array_key_exists( $oname, $this->mOptions
) ) {
2781 return $this->mOptions
[$oname];
2783 return $defaultOverride;
2788 * Get all user's options
2790 * @param int $flags Bitwise combination of:
2791 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2792 * to the default value. (Since 1.25)
2795 public function getOptions( $flags = 0 ) {
2796 global $wgHiddenPrefs;
2797 $this->loadOptions();
2798 $options = $this->mOptions
;
2800 # We want 'disabled' preferences to always behave as the default value for
2801 # users, even if they have set the option explicitly in their settings (ie they
2802 # set it, and then it was disabled removing their ability to change it). But
2803 # we don't want to erase the preferences in the database in case the preference
2804 # is re-enabled again. So don't touch $mOptions, just override the returned value
2805 foreach ( $wgHiddenPrefs as $pref ) {
2806 $default = self
::getDefaultOption( $pref );
2807 if ( $default !== null ) {
2808 $options[$pref] = $default;
2812 if ( $flags & self
::GETOPTIONS_EXCLUDE_DEFAULTS
) {
2813 $options = array_diff_assoc( $options, self
::getDefaultOptions() );
2820 * Get the user's current setting for a given option, as a boolean value.
2822 * @param string $oname The option to check
2823 * @return bool User's current value for the option
2826 public function getBoolOption( $oname ) {
2827 return (bool)$this->getOption( $oname );
2831 * Get the user's current setting for a given option, as an integer value.
2833 * @param string $oname The option to check
2834 * @param int $defaultOverride A default value returned if the option does not exist
2835 * @return int User's current value for the option
2838 public function getIntOption( $oname, $defaultOverride = 0 ) {
2839 $val = $this->getOption( $oname );
2841 $val = $defaultOverride;
2843 return intval( $val );
2847 * Set the given option for a user.
2849 * You need to call saveSettings() to actually write to the database.
2851 * @param string $oname The option to set
2852 * @param mixed $val New value to set
2854 public function setOption( $oname, $val ) {
2855 $this->loadOptions();
2857 // Explicitly NULL values should refer to defaults
2858 if ( is_null( $val ) ) {
2859 $val = self
::getDefaultOption( $oname );
2862 $this->mOptions
[$oname] = $val;
2866 * Get a token stored in the preferences (like the watchlist one),
2867 * resetting it if it's empty (and saving changes).
2869 * @param string $oname The option name to retrieve the token from
2870 * @return string|bool User's current value for the option, or false if this option is disabled.
2871 * @see resetTokenFromOption()
2873 * @deprecated 1.26 Applications should use the OAuth extension
2875 public function getTokenFromOption( $oname ) {
2876 global $wgHiddenPrefs;
2878 $id = $this->getId();
2879 if ( !$id ||
in_array( $oname, $wgHiddenPrefs ) ) {
2883 $token = $this->getOption( $oname );
2885 // Default to a value based on the user token to avoid space
2886 // wasted on storing tokens for all users. When this option
2887 // is set manually by the user, only then is it stored.
2888 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
2895 * Reset a token stored in the preferences (like the watchlist one).
2896 * *Does not* save user's preferences (similarly to setOption()).
2898 * @param string $oname The option name to reset the token in
2899 * @return string|bool New token value, or false if this option is disabled.
2900 * @see getTokenFromOption()
2903 public function resetTokenFromOption( $oname ) {
2904 global $wgHiddenPrefs;
2905 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2909 $token = MWCryptRand
::generateHex( 40 );
2910 $this->setOption( $oname, $token );
2915 * Return a list of the types of user options currently returned by
2916 * User::getOptionKinds().
2918 * Currently, the option kinds are:
2919 * - 'registered' - preferences which are registered in core MediaWiki or
2920 * by extensions using the UserGetDefaultOptions hook.
2921 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2922 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2923 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2924 * be used by user scripts.
2925 * - 'special' - "preferences" that are not accessible via User::getOptions
2926 * or User::setOptions.
2927 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2928 * These are usually legacy options, removed in newer versions.
2930 * The API (and possibly others) use this function to determine the possible
2931 * option types for validation purposes, so make sure to update this when a
2932 * new option kind is added.
2934 * @see User::getOptionKinds
2935 * @return array Option kinds
2937 public static function listOptionKinds() {
2940 'registered-multiselect',
2941 'registered-checkmatrix',
2949 * Return an associative array mapping preferences keys to the kind of a preference they're
2950 * used for. Different kinds are handled differently when setting or reading preferences.
2952 * See User::listOptionKinds for the list of valid option types that can be provided.
2954 * @see User::listOptionKinds
2955 * @param IContextSource $context
2956 * @param array $options Assoc. array with options keys to check as keys.
2957 * Defaults to $this->mOptions.
2958 * @return array The key => kind mapping data
2960 public function getOptionKinds( IContextSource
$context, $options = null ) {
2961 $this->loadOptions();
2962 if ( $options === null ) {
2963 $options = $this->mOptions
;
2966 $prefs = Preferences
::getPreferences( $this, $context );
2969 // Pull out the "special" options, so they don't get converted as
2970 // multiselect or checkmatrix.
2971 $specialOptions = array_fill_keys( Preferences
::getSaveBlacklist(), true );
2972 foreach ( $specialOptions as $name => $value ) {
2973 unset( $prefs[$name] );
2976 // Multiselect and checkmatrix options are stored in the database with
2977 // one key per option, each having a boolean value. Extract those keys.
2978 $multiselectOptions = [];
2979 foreach ( $prefs as $name => $info ) {
2980 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2981 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2982 $opts = HTMLFormField
::flattenOptions( $info['options'] );
2983 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2985 foreach ( $opts as $value ) {
2986 $multiselectOptions["$prefix$value"] = true;
2989 unset( $prefs[$name] );
2992 $checkmatrixOptions = [];
2993 foreach ( $prefs as $name => $info ) {
2994 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2995 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2996 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
2997 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
2998 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
3000 foreach ( $columns as $column ) {
3001 foreach ( $rows as $row ) {
3002 $checkmatrixOptions["$prefix$column-$row"] = true;
3006 unset( $prefs[$name] );
3010 // $value is ignored
3011 foreach ( $options as $key => $value ) {
3012 if ( isset( $prefs[$key] ) ) {
3013 $mapping[$key] = 'registered';
3014 } elseif ( isset( $multiselectOptions[$key] ) ) {
3015 $mapping[$key] = 'registered-multiselect';
3016 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
3017 $mapping[$key] = 'registered-checkmatrix';
3018 } elseif ( isset( $specialOptions[$key] ) ) {
3019 $mapping[$key] = 'special';
3020 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
3021 $mapping[$key] = 'userjs';
3023 $mapping[$key] = 'unused';
3031 * Reset certain (or all) options to the site defaults
3033 * The optional parameter determines which kinds of preferences will be reset.
3034 * Supported values are everything that can be reported by getOptionKinds()
3035 * and 'all', which forces a reset of *all* preferences and overrides everything else.
3037 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
3038 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
3039 * for backwards-compatibility.
3040 * @param IContextSource|null $context Context source used when $resetKinds
3041 * does not contain 'all', passed to getOptionKinds().
3042 * Defaults to RequestContext::getMain() when null.
3044 public function resetOptions(
3045 $resetKinds = [ 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ],
3046 IContextSource
$context = null
3049 $defaultOptions = self
::getDefaultOptions();
3051 if ( !is_array( $resetKinds ) ) {
3052 $resetKinds = [ $resetKinds ];
3055 if ( in_array( 'all', $resetKinds ) ) {
3056 $newOptions = $defaultOptions;
3058 if ( $context === null ) {
3059 $context = RequestContext
::getMain();
3062 $optionKinds = $this->getOptionKinds( $context );
3063 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
3066 // Use default values for the options that should be deleted, and
3067 // copy old values for the ones that shouldn't.
3068 foreach ( $this->mOptions
as $key => $value ) {
3069 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
3070 if ( array_key_exists( $key, $defaultOptions ) ) {
3071 $newOptions[$key] = $defaultOptions[$key];
3074 $newOptions[$key] = $value;
3079 Hooks
::run( 'UserResetAllOptions', [ $this, &$newOptions, $this->mOptions
, $resetKinds ] );
3081 $this->mOptions
= $newOptions;
3082 $this->mOptionsLoaded
= true;
3086 * Get the user's preferred date format.
3087 * @return string User's preferred date format
3089 public function getDatePreference() {
3090 // Important migration for old data rows
3091 if ( is_null( $this->mDatePreference
) ) {
3093 $value = $this->getOption( 'date' );
3094 $map = $wgLang->getDatePreferenceMigrationMap();
3095 if ( isset( $map[$value] ) ) {
3096 $value = $map[$value];
3098 $this->mDatePreference
= $value;
3100 return $this->mDatePreference
;
3104 * Determine based on the wiki configuration and the user's options,
3105 * whether this user must be over HTTPS no matter what.
3109 public function requiresHTTPS() {
3110 global $wgSecureLogin;
3111 if ( !$wgSecureLogin ) {
3114 $https = $this->getBoolOption( 'prefershttps' );
3115 Hooks
::run( 'UserRequiresHTTPS', [ $this, &$https ] );
3117 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
3124 * Get the user preferred stub threshold
3128 public function getStubThreshold() {
3129 global $wgMaxArticleSize; # Maximum article size, in Kb
3130 $threshold = $this->getIntOption( 'stubthreshold' );
3131 if ( $threshold > $wgMaxArticleSize * 1024 ) {
3132 // If they have set an impossible value, disable the preference
3133 // so we can use the parser cache again.
3140 * Get the permissions this user has.
3141 * @return array Array of String permission names
3143 public function getRights() {
3144 if ( is_null( $this->mRights
) ) {
3145 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
3147 // Deny any rights denied by the user's session, unless this
3148 // endpoint has no sessions.
3149 if ( !defined( 'MW_NO_SESSION' ) ) {
3150 $allowedRights = $this->getRequest()->getSession()->getAllowedUserRights();
3151 if ( $allowedRights !== null ) {
3152 $this->mRights
= array_intersect( $this->mRights
, $allowedRights );
3156 Hooks
::run( 'UserGetRights', [ $this, &$this->mRights
] );
3157 // Force reindexation of rights when a hook has unset one of them
3158 $this->mRights
= array_values( array_unique( $this->mRights
) );
3160 return $this->mRights
;
3164 * Get the list of explicit group memberships this user has.
3165 * The implicit * and user groups are not included.
3166 * @return array Array of String internal group names
3168 public function getGroups() {
3170 $this->loadGroups();
3171 return $this->mGroups
;
3175 * Get the list of implicit group memberships this user has.
3176 * This includes all explicit groups, plus 'user' if logged in,
3177 * '*' for all accounts, and autopromoted groups
3178 * @param bool $recache Whether to avoid the cache
3179 * @return array Array of String internal group names
3181 public function getEffectiveGroups( $recache = false ) {
3182 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
3183 $this->mEffectiveGroups
= array_unique( array_merge(
3184 $this->getGroups(), // explicit groups
3185 $this->getAutomaticGroups( $recache ) // implicit groups
3187 // Hook for additional groups
3188 Hooks
::run( 'UserEffectiveGroups', [ &$this, &$this->mEffectiveGroups
] );
3189 // Force reindexation of groups when a hook has unset one of them
3190 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
3192 return $this->mEffectiveGroups
;
3196 * Get the list of implicit group memberships this user has.
3197 * This includes 'user' if logged in, '*' for all accounts,
3198 * and autopromoted groups
3199 * @param bool $recache Whether to avoid the cache
3200 * @return array Array of String internal group names
3202 public function getAutomaticGroups( $recache = false ) {
3203 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
3204 $this->mImplicitGroups
= [ '*' ];
3205 if ( $this->getId() ) {
3206 $this->mImplicitGroups
[] = 'user';
3208 $this->mImplicitGroups
= array_unique( array_merge(
3209 $this->mImplicitGroups
,
3210 Autopromote
::getAutopromoteGroups( $this )
3214 // Assure data consistency with rights/groups,
3215 // as getEffectiveGroups() depends on this function
3216 $this->mEffectiveGroups
= null;
3219 return $this->mImplicitGroups
;
3223 * Returns the groups the user has belonged to.
3225 * The user may still belong to the returned groups. Compare with getGroups().
3227 * The function will not return groups the user had belonged to before MW 1.17
3229 * @return array Names of the groups the user has belonged to.
3231 public function getFormerGroups() {
3234 if ( is_null( $this->mFormerGroups
) ) {
3235 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3236 ?
wfGetDB( DB_MASTER
)
3237 : wfGetDB( DB_SLAVE
);
3238 $res = $db->select( 'user_former_groups',
3240 [ 'ufg_user' => $this->mId
],
3242 $this->mFormerGroups
= [];
3243 foreach ( $res as $row ) {
3244 $this->mFormerGroups
[] = $row->ufg_group
;
3248 return $this->mFormerGroups
;
3252 * Get the user's edit count.
3253 * @return int|null Null for anonymous users
3255 public function getEditCount() {
3256 if ( !$this->getId() ) {
3260 if ( $this->mEditCount
=== null ) {
3261 /* Populate the count, if it has not been populated yet */
3262 $dbr = wfGetDB( DB_SLAVE
);
3263 // check if the user_editcount field has been initialized
3264 $count = $dbr->selectField(
3265 'user', 'user_editcount',
3266 [ 'user_id' => $this->mId
],
3270 if ( $count === null ) {
3271 // it has not been initialized. do so.
3272 $count = $this->initEditCount();
3274 $this->mEditCount
= $count;
3276 return (int)$this->mEditCount
;
3280 * Add the user to the given group.
3281 * This takes immediate effect.
3282 * @param string $group Name of the group to add
3285 public function addGroup( $group ) {
3288 if ( !Hooks
::run( 'UserAddGroup', [ $this, &$group ] ) ) {
3292 $dbw = wfGetDB( DB_MASTER
);
3293 if ( $this->getId() ) {
3294 $dbw->insert( 'user_groups',
3296 'ug_user' => $this->getId(),
3297 'ug_group' => $group,
3303 $this->loadGroups();
3304 $this->mGroups
[] = $group;
3305 // In case loadGroups was not called before, we now have the right twice.
3306 // Get rid of the duplicate.
3307 $this->mGroups
= array_unique( $this->mGroups
);
3309 // Refresh the groups caches, and clear the rights cache so it will be
3310 // refreshed on the next call to $this->getRights().
3311 $this->getEffectiveGroups( true );
3312 $this->mRights
= null;
3314 $this->invalidateCache();
3320 * Remove the user from the given group.
3321 * This takes immediate effect.
3322 * @param string $group Name of the group to remove
3325 public function removeGroup( $group ) {
3327 if ( !Hooks
::run( 'UserRemoveGroup', [ $this, &$group ] ) ) {
3331 $dbw = wfGetDB( DB_MASTER
);
3332 $dbw->delete( 'user_groups',
3334 'ug_user' => $this->getId(),
3335 'ug_group' => $group,
3338 // Remember that the user was in this group
3339 $dbw->insert( 'user_former_groups',
3341 'ufg_user' => $this->getId(),
3342 'ufg_group' => $group,
3348 $this->loadGroups();
3349 $this->mGroups
= array_diff( $this->mGroups
, [ $group ] );
3351 // Refresh the groups caches, and clear the rights cache so it will be
3352 // refreshed on the next call to $this->getRights().
3353 $this->getEffectiveGroups( true );
3354 $this->mRights
= null;
3356 $this->invalidateCache();
3362 * Get whether the user is logged in
3365 public function isLoggedIn() {
3366 return $this->getId() != 0;
3370 * Get whether the user is anonymous
3373 public function isAnon() {
3374 return !$this->isLoggedIn();
3378 * Check if user is allowed to access a feature / make an action
3380 * @param string ... Permissions to test
3381 * @return bool True if user is allowed to perform *any* of the given actions
3383 public function isAllowedAny() {
3384 $permissions = func_get_args();
3385 foreach ( $permissions as $permission ) {
3386 if ( $this->isAllowed( $permission ) ) {
3395 * @param string ... Permissions to test
3396 * @return bool True if the user is allowed to perform *all* of the given actions
3398 public function isAllowedAll() {
3399 $permissions = func_get_args();
3400 foreach ( $permissions as $permission ) {
3401 if ( !$this->isAllowed( $permission ) ) {
3409 * Internal mechanics of testing a permission
3410 * @param string $action
3413 public function isAllowed( $action = '' ) {
3414 if ( $action === '' ) {
3415 return true; // In the spirit of DWIM
3417 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3418 // by misconfiguration: 0 == 'foo'
3419 return in_array( $action, $this->getRights(), true );
3423 * Check whether to enable recent changes patrol features for this user
3424 * @return bool True or false
3426 public function useRCPatrol() {
3427 global $wgUseRCPatrol;
3428 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3432 * Check whether to enable new pages patrol features for this user
3433 * @return bool True or false
3435 public function useNPPatrol() {
3436 global $wgUseRCPatrol, $wgUseNPPatrol;
3438 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3439 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3444 * Check whether to enable new files patrol features for this user
3445 * @return bool True or false
3447 public function useFilePatrol() {
3448 global $wgUseRCPatrol, $wgUseFilePatrol;
3450 ( $wgUseRCPatrol ||
$wgUseFilePatrol )
3451 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3456 * Get the WebRequest object to use with this object
3458 * @return WebRequest
3460 public function getRequest() {
3461 if ( $this->mRequest
) {
3462 return $this->mRequest
;
3470 * Check the watched status of an article.
3471 * @since 1.22 $checkRights parameter added
3472 * @param Title $title Title of the article to look at
3473 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3474 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3477 public function isWatched( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3478 if ( $title->isWatchable() && ( !$checkRights ||
$this->isAllowed( 'viewmywatchlist' ) ) ) {
3479 return WatchedItemStore
::getDefaultInstance()->isWatched( $this, $title );
3486 * @since 1.22 $checkRights parameter added
3487 * @param Title $title Title of the article to look at
3488 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3489 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3491 public function addWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3492 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3493 WatchedItemStore
::getDefaultInstance()->addWatchBatchForUser(
3495 [ $title->getSubjectPage(), $title->getTalkPage() ]
3498 $this->invalidateCache();
3502 * Stop watching an article.
3503 * @since 1.22 $checkRights parameter added
3504 * @param Title $title Title of the article to look at
3505 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3506 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3508 public function removeWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3509 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3510 WatchedItemStore
::getDefaultInstance()->removeWatch( $this, $title->getSubjectPage() );
3511 WatchedItemStore
::getDefaultInstance()->removeWatch( $this, $title->getTalkPage() );
3513 $this->invalidateCache();
3517 * Clear the user's notification timestamp for the given title.
3518 * If e-notif e-mails are on, they will receive notification mails on
3519 * the next change of the page if it's watched etc.
3520 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3521 * @param Title $title Title of the article to look at
3522 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3524 public function clearNotification( &$title, $oldid = 0 ) {
3525 global $wgUseEnotif, $wgShowUpdatedMarker;
3527 // Do nothing if the database is locked to writes
3528 if ( wfReadOnly() ) {
3532 // Do nothing if not allowed to edit the watchlist
3533 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3537 // If we're working on user's talk page, we should update the talk page message indicator
3538 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3539 if ( !Hooks
::run( 'UserClearNewTalkNotification', [ &$this, $oldid ] ) ) {
3543 // Try to update the DB post-send and only if needed...
3544 DeferredUpdates
::addCallableUpdate( function() use ( $title, $oldid ) {
3545 if ( !$this->getNewtalk() ) {
3546 return; // no notifications to clear
3549 // Delete the last notifications (they stack up)
3550 $this->setNewtalk( false );
3552 // If there is a new, unseen, revision, use its timestamp
3554 ?
$title->getNextRevisionID( $oldid, Title
::GAID_FOR_UPDATE
)
3557 $this->setNewtalk( true, Revision
::newFromId( $nextid ) );
3562 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3566 if ( $this->isAnon() ) {
3567 // Nothing else to do...
3571 // Only update the timestamp if the page is being watched.
3572 // The query to find out if it is watched is cached both in memcached and per-invocation,
3573 // and when it does have to be executed, it can be on a slave
3574 // If this is the user's newtalk page, we always update the timestamp
3576 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3580 WatchedItemStore
::getDefaultInstance()
3581 ->resetNotificationTimestamp( $this, $title, $force, $oldid );
3585 * Resets all of the given user's page-change notification timestamps.
3586 * If e-notif e-mails are on, they will receive notification mails on
3587 * the next change of any watched page.
3588 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3590 public function clearAllNotifications() {
3591 if ( wfReadOnly() ) {
3595 // Do nothing if not allowed to edit the watchlist
3596 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3600 global $wgUseEnotif, $wgShowUpdatedMarker;
3601 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3602 $this->setNewtalk( false );
3605 $id = $this->getId();
3607 $dbw = wfGetDB( DB_MASTER
);
3608 $dbw->update( 'watchlist',
3609 [ /* SET */ 'wl_notificationtimestamp' => null ],
3610 [ /* WHERE */ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ],
3613 // We also need to clear here the "you have new message" notification for the own user_talk page;
3614 // it's cleared one page view later in WikiPage::doViewUpdates().
3619 * Set a cookie on the user's client. Wrapper for
3620 * WebResponse::setCookie
3621 * @deprecated since 1.27
3622 * @param string $name Name of the cookie to set
3623 * @param string $value Value to set
3624 * @param int $exp Expiration time, as a UNIX time value;
3625 * if 0 or not specified, use the default $wgCookieExpiration
3626 * @param bool $secure
3627 * true: Force setting the secure attribute when setting the cookie
3628 * false: Force NOT setting the secure attribute when setting the cookie
3629 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3630 * @param array $params Array of options sent passed to WebResponse::setcookie()
3631 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3634 protected function setCookie(
3635 $name, $value, $exp = 0, $secure = null, $params = [], $request = null
3637 wfDeprecated( __METHOD__
, '1.27' );
3638 if ( $request === null ) {
3639 $request = $this->getRequest();
3641 $params['secure'] = $secure;
3642 $request->response()->setCookie( $name, $value, $exp, $params );
3646 * Clear a cookie on the user's client
3647 * @deprecated since 1.27
3648 * @param string $name Name of the cookie to clear
3649 * @param bool $secure
3650 * true: Force setting the secure attribute when setting the cookie
3651 * false: Force NOT setting the secure attribute when setting the cookie
3652 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3653 * @param array $params Array of options sent passed to WebResponse::setcookie()
3655 protected function clearCookie( $name, $secure = null, $params = [] ) {
3656 wfDeprecated( __METHOD__
, '1.27' );
3657 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3661 * Set an extended login cookie on the user's client. The expiry of the cookie
3662 * is controlled by the $wgExtendedLoginCookieExpiration configuration
3665 * @see User::setCookie
3667 * @deprecated since 1.27
3668 * @param string $name Name of the cookie to set
3669 * @param string $value Value to set
3670 * @param bool $secure
3671 * true: Force setting the secure attribute when setting the cookie
3672 * false: Force NOT setting the secure attribute when setting the cookie
3673 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3675 protected function setExtendedLoginCookie( $name, $value, $secure ) {
3676 global $wgExtendedLoginCookieExpiration, $wgCookieExpiration;
3678 wfDeprecated( __METHOD__
, '1.27' );
3681 $exp +
= $wgExtendedLoginCookieExpiration !== null
3682 ?
$wgExtendedLoginCookieExpiration
3683 : $wgCookieExpiration;
3685 $this->setCookie( $name, $value, $exp, $secure );
3689 * Persist this user's session (e.g. set cookies)
3691 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3693 * @param bool $secure Whether to force secure/insecure cookies or use default
3694 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3696 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3698 if ( 0 == $this->mId
) {
3702 $session = $this->getRequest()->getSession();
3703 if ( $request && $session->getRequest() !== $request ) {
3704 $session = $session->sessionWithRequest( $request );
3706 $delay = $session->delaySave();
3708 if ( !$session->getUser()->equals( $this ) ) {
3709 if ( !$session->canSetUser() ) {
3710 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3711 ->warning( __METHOD__
.
3712 ": Cannot save user \"$this\" to a user \"{$session->getUser()}\"'s immutable session"
3716 $session->setUser( $this );
3719 $session->setRememberUser( $rememberMe );
3720 if ( $secure !== null ) {
3721 $session->setForceHTTPS( $secure );
3724 $session->persist();
3726 ScopedCallback
::consume( $delay );
3730 * Log this user out.
3732 public function logout() {
3733 if ( Hooks
::run( 'UserLogout', [ &$this ] ) ) {
3739 * Clear the user's session, and reset the instance cache.
3742 public function doLogout() {
3743 $session = $this->getRequest()->getSession();
3744 if ( !$session->canSetUser() ) {
3745 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3746 ->warning( __METHOD__
. ": Cannot log out of an immutable session" );
3747 } elseif ( !$session->getUser()->equals( $this ) ) {
3748 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3749 ->warning( __METHOD__
.
3750 ": Cannot log user \"$this\" out of a user \"{$session->getUser()}\"'s session"
3752 // But we still may as well make this user object anon
3753 $this->clearInstanceCache( 'defaults' );
3755 $this->clearInstanceCache( 'defaults' );
3756 $delay = $session->delaySave();
3757 $session->unpersist(); // Clear cookies (T127436)
3758 $session->setLoggedOutTimestamp( time() );
3759 $session->setUser( new User
);
3760 $session->set( 'wsUserID', 0 ); // Other code expects this
3761 ScopedCallback
::consume( $delay );
3766 * Save this user's settings into the database.
3767 * @todo Only rarely do all these fields need to be set!
3769 public function saveSettings() {
3770 if ( wfReadOnly() ) {
3771 // @TODO: caller should deal with this instead!
3772 // This should really just be an exception.
3773 MWExceptionHandler
::logException( new DBExpectedError(
3775 "Could not update user with ID '{$this->mId}'; DB is read-only."
3781 if ( 0 == $this->mId
) {
3785 // Get a new user_touched that is higher than the old one.
3786 // This will be used for a CAS check as a last-resort safety
3787 // check against race conditions and slave lag.
3788 $oldTouched = $this->mTouched
;
3789 $newTouched = $this->newTouchedTimestamp();
3791 $dbw = wfGetDB( DB_MASTER
);
3792 $dbw->update( 'user',
3794 'user_name' => $this->mName
,
3795 'user_real_name' => $this->mRealName
,
3796 'user_email' => $this->mEmail
,
3797 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3798 'user_touched' => $dbw->timestamp( $newTouched ),
3799 'user_token' => strval( $this->mToken
),
3800 'user_email_token' => $this->mEmailToken
,
3801 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
3803 'user_id' => $this->mId
,
3804 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
3808 if ( !$dbw->affectedRows() ) {
3809 // Maybe the problem was a missed cache update; clear it to be safe
3810 $this->clearSharedCache( 'refresh' );
3811 // User was changed in the meantime or loaded with stale data
3812 $from = ( $this->queryFlagsUsed
& self
::READ_LATEST
) ?
'master' : 'slave';
3813 throw new MWException(
3814 "CAS update failed on user_touched for user ID '{$this->mId}' (read from $from);" .
3815 " the version of the user to be saved is older than the current version."
3819 $this->mTouched
= $newTouched;
3820 $this->saveOptions();
3822 Hooks
::run( 'UserSaveSettings', [ $this ] );
3823 $this->clearSharedCache();
3824 $this->getUserPage()->invalidateCache();
3828 * If only this user's username is known, and it exists, return the user ID.
3830 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
3833 public function idForName( $flags = 0 ) {
3834 $s = trim( $this->getName() );
3839 $db = ( ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
)
3840 ?
wfGetDB( DB_MASTER
)
3841 : wfGetDB( DB_SLAVE
);
3843 $options = ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
)
3844 ?
[ 'LOCK IN SHARE MODE' ]
3847 $id = $db->selectField( 'user',
3848 'user_id', [ 'user_name' => $s ], __METHOD__
, $options );
3854 * Add a user to the database, return the user object
3856 * @param string $name Username to add
3857 * @param array $params Array of Strings Non-default parameters to save to
3858 * the database as user_* fields:
3859 * - email: The user's email address.
3860 * - email_authenticated: The email authentication timestamp.
3861 * - real_name: The user's real name.
3862 * - options: An associative array of non-default options.
3863 * - token: Random authentication token. Do not set.
3864 * - registration: Registration timestamp. Do not set.
3866 * @return User|null User object, or null if the username already exists.
3868 public static function createNew( $name, $params = [] ) {
3869 foreach ( [ 'password', 'newpassword', 'newpass_time', 'password_expires' ] as $field ) {
3870 if ( isset( $params[$field] ) ) {
3871 wfDeprecated( __METHOD__
. " with param '$field'", '1.27' );
3872 unset( $params[$field] );
3878 $user->setToken(); // init token
3879 if ( isset( $params['options'] ) ) {
3880 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
3881 unset( $params['options'] );
3883 $dbw = wfGetDB( DB_MASTER
);
3884 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3886 $noPass = PasswordFactory
::newInvalidPassword()->toString();
3889 'user_id' => $seqVal,
3890 'user_name' => $name,
3891 'user_password' => $noPass,
3892 'user_newpassword' => $noPass,
3893 'user_email' => $user->mEmail
,
3894 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
3895 'user_real_name' => $user->mRealName
,
3896 'user_token' => strval( $user->mToken
),
3897 'user_registration' => $dbw->timestamp( $user->mRegistration
),
3898 'user_editcount' => 0,
3899 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
3901 foreach ( $params as $name => $value ) {
3902 $fields["user_$name"] = $value;
3904 $dbw->insert( 'user', $fields, __METHOD__
, [ 'IGNORE' ] );
3905 if ( $dbw->affectedRows() ) {
3906 $newUser = User
::newFromId( $dbw->insertId() );
3914 * Add this existing user object to the database. If the user already
3915 * exists, a fatal status object is returned, and the user object is
3916 * initialised with the data from the database.
3918 * Previously, this function generated a DB error due to a key conflict
3919 * if the user already existed. Many extension callers use this function
3920 * in code along the lines of:
3922 * $user = User::newFromName( $name );
3923 * if ( !$user->isLoggedIn() ) {
3924 * $user->addToDatabase();
3926 * // do something with $user...
3928 * However, this was vulnerable to a race condition (bug 16020). By
3929 * initialising the user object if the user exists, we aim to support this
3930 * calling sequence as far as possible.
3932 * Note that if the user exists, this function will acquire a write lock,
3933 * so it is still advisable to make the call conditional on isLoggedIn(),
3934 * and to commit the transaction after calling.
3936 * @throws MWException
3939 public function addToDatabase() {
3941 if ( !$this->mToken
) {
3942 $this->setToken(); // init token
3945 $this->mTouched
= $this->newTouchedTimestamp();
3947 $noPass = PasswordFactory
::newInvalidPassword()->toString();
3949 $dbw = wfGetDB( DB_MASTER
);
3950 $inWrite = $dbw->writesOrCallbacksPending();
3951 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3952 $dbw->insert( 'user',
3954 'user_id' => $seqVal,
3955 'user_name' => $this->mName
,
3956 'user_password' => $noPass,
3957 'user_newpassword' => $noPass,
3958 'user_email' => $this->mEmail
,
3959 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3960 'user_real_name' => $this->mRealName
,
3961 'user_token' => strval( $this->mToken
),
3962 'user_registration' => $dbw->timestamp( $this->mRegistration
),
3963 'user_editcount' => 0,
3964 'user_touched' => $dbw->timestamp( $this->mTouched
),
3968 if ( !$dbw->affectedRows() ) {
3969 // The queries below cannot happen in the same REPEATABLE-READ snapshot.
3970 // Handle this by COMMIT, if possible, or by LOCK IN SHARE MODE otherwise.
3972 // Can't commit due to pending writes that may need atomicity.
3973 // This may cause some lock contention unlike the case below.
3974 $options = [ 'LOCK IN SHARE MODE' ];
3975 $flags = self
::READ_LOCKING
;
3977 // Often, this case happens early in views before any writes when
3978 // using CentralAuth. It's should be OK to commit and break the snapshot.
3979 $dbw->commit( __METHOD__
, 'flush' );
3981 $flags = self
::READ_LATEST
;
3983 $this->mId
= $dbw->selectField( 'user', 'user_id',
3984 [ 'user_name' => $this->mName
], __METHOD__
, $options );
3987 if ( $this->loadFromDatabase( $flags ) ) {
3992 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
3993 "to insert user '{$this->mName}' row, but it was not present in select!" );
3995 return Status
::newFatal( 'userexists' );
3997 $this->mId
= $dbw->insertId();
3998 self
::$idCacheByName[$this->mName
] = $this->mId
;
4000 // Clear instance cache other than user table data, which is already accurate
4001 $this->clearInstanceCache();
4003 $this->saveOptions();
4004 return Status
::newGood();
4008 * If this user is logged-in and blocked,
4009 * block any IP address they've successfully logged in from.
4010 * @return bool A block was spread
4012 public function spreadAnyEditBlock() {
4013 if ( $this->isLoggedIn() && $this->isBlocked() ) {
4014 return $this->spreadBlock();
4021 * If this (non-anonymous) user is blocked,
4022 * block the IP address they've successfully logged in from.
4023 * @return bool A block was spread
4025 protected function spreadBlock() {
4026 wfDebug( __METHOD__
. "()\n" );
4028 if ( $this->mId
== 0 ) {
4032 $userblock = Block
::newFromTarget( $this->getName() );
4033 if ( !$userblock ) {
4037 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
4041 * Get whether the user is explicitly blocked from account creation.
4042 * @return bool|Block
4044 public function isBlockedFromCreateAccount() {
4045 $this->getBlockedStatus();
4046 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
4047 return $this->mBlock
;
4050 # bug 13611: if the IP address the user is trying to create an account from is
4051 # blocked with createaccount disabled, prevent new account creation there even
4052 # when the user is logged in
4053 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
4054 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
4056 return $this->mBlockedFromCreateAccount
instanceof Block
4057 && $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
4058 ?
$this->mBlockedFromCreateAccount
4063 * Get whether the user is blocked from using Special:Emailuser.
4066 public function isBlockedFromEmailuser() {
4067 $this->getBlockedStatus();
4068 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
4072 * Get whether the user is allowed to create an account.
4075 public function isAllowedToCreateAccount() {
4076 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
4080 * Get this user's personal page title.
4082 * @return Title User's personal page title
4084 public function getUserPage() {
4085 return Title
::makeTitle( NS_USER
, $this->getName() );
4089 * Get this user's talk page title.
4091 * @return Title User's talk page title
4093 public function getTalkPage() {
4094 $title = $this->getUserPage();
4095 return $title->getTalkPage();
4099 * Determine whether the user is a newbie. Newbies are either
4100 * anonymous IPs, or the most recently created accounts.
4103 public function isNewbie() {
4104 return !$this->isAllowed( 'autoconfirmed' );
4108 * Check to see if the given clear-text password is one of the accepted passwords
4109 * @deprecated since 1.27. AuthManager is coming.
4110 * @param string $password User password
4111 * @return bool True if the given password is correct, otherwise False
4113 public function checkPassword( $password ) {
4114 global $wgAuth, $wgLegacyEncoding;
4118 // Some passwords will give a fatal Status, which means there is
4119 // some sort of technical or security reason for this password to
4120 // be completely invalid and should never be checked (e.g., T64685)
4121 if ( !$this->checkPasswordValidity( $password )->isOK() ) {
4125 // Certain authentication plugins do NOT want to save
4126 // domain passwords in a mysql database, so we should
4127 // check this (in case $wgAuth->strict() is false).
4128 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
4130 } elseif ( $wgAuth->strict() ) {
4131 // Auth plugin doesn't allow local authentication
4133 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
4134 // Auth plugin doesn't allow local authentication for this user name
4138 $passwordFactory = new PasswordFactory();
4139 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4140 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
4141 ?
wfGetDB( DB_MASTER
)
4142 : wfGetDB( DB_SLAVE
);
4145 $mPassword = $passwordFactory->newFromCiphertext( $db->selectField(
4146 'user', 'user_password', [ 'user_id' => $this->getId() ], __METHOD__
4148 } catch ( PasswordError
$e ) {
4149 wfDebug( 'Invalid password hash found in database.' );
4150 $mPassword = PasswordFactory
::newInvalidPassword();
4153 if ( !$mPassword->equals( $password ) ) {
4154 if ( $wgLegacyEncoding ) {
4155 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
4156 // Check for this with iconv
4157 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
4158 if ( $cp1252Password === $password ||
!$mPassword->equals( $cp1252Password ) ) {
4166 if ( $passwordFactory->needsUpdate( $mPassword ) && !wfReadOnly() ) {
4167 $this->setPasswordInternal( $password );
4174 * Check if the given clear-text password matches the temporary password
4175 * sent by e-mail for password reset operations.
4177 * @deprecated since 1.27. AuthManager is coming.
4178 * @param string $plaintext
4179 * @return bool True if matches, false otherwise
4181 public function checkTemporaryPassword( $plaintext ) {
4182 global $wgNewPasswordExpiry;
4186 $passwordFactory = new PasswordFactory();
4187 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4188 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
4189 ?
wfGetDB( DB_MASTER
)
4190 : wfGetDB( DB_SLAVE
);
4192 $row = $db->selectRow(
4194 [ 'user_newpassword', 'user_newpass_time' ],
4195 [ 'user_id' => $this->getId() ],
4199 $newPassword = $passwordFactory->newFromCiphertext( $row->user_newpassword
);
4200 } catch ( PasswordError
$e ) {
4201 wfDebug( 'Invalid password hash found in database.' );
4202 $newPassword = PasswordFactory
::newInvalidPassword();
4205 if ( $newPassword->equals( $plaintext ) ) {
4206 if ( is_null( $row->user_newpass_time
) ) {
4209 $expiry = wfTimestamp( TS_UNIX
, $row->user_newpass_time
) +
$wgNewPasswordExpiry;
4210 return ( time() < $expiry );
4217 * Initialize (if necessary) and return a session token value
4218 * which can be used in edit forms to show that the user's
4219 * login credentials aren't being hijacked with a foreign form
4223 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4224 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4225 * @return MediaWiki\Session\Token The new edit token
4227 public function getEditTokenObject( $salt = '', $request = null ) {
4228 if ( $this->isAnon() ) {
4229 return new LoggedOutEditToken();
4233 $request = $this->getRequest();
4235 return $request->getSession()->getToken( $salt );
4239 * Initialize (if necessary) and return a session token value
4240 * which can be used in edit forms to show that the user's
4241 * login credentials aren't being hijacked with a foreign form
4245 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4246 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4247 * @return string The new edit token
4249 public function getEditToken( $salt = '', $request = null ) {
4250 return $this->getEditTokenObject( $salt, $request )->toString();
4254 * Get the embedded timestamp from a token.
4255 * @deprecated since 1.27, use \MediaWiki\Session\Token::getTimestamp instead.
4256 * @param string $val Input token
4259 public static function getEditTokenTimestamp( $val ) {
4260 wfDeprecated( __METHOD__
, '1.27' );
4261 return MediaWiki\Session\Token
::getTimestamp( $val );
4265 * Check given value against the token value stored in the session.
4266 * A match should confirm that the form was submitted from the
4267 * user's own login session, not a form submission from a third-party
4270 * @param string $val Input value to compare
4271 * @param string $salt Optional function-specific data for hashing
4272 * @param WebRequest|null $request Object to use or null to use $wgRequest
4273 * @param int $maxage Fail tokens older than this, in seconds
4274 * @return bool Whether the token matches
4276 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4277 return $this->getEditTokenObject( $salt, $request )->match( $val, $maxage );
4281 * Check given value against the token value stored in the session,
4282 * ignoring the suffix.
4284 * @param string $val Input value to compare
4285 * @param string $salt Optional function-specific data for hashing
4286 * @param WebRequest|null $request Object to use or null to use $wgRequest
4287 * @param int $maxage Fail tokens older than this, in seconds
4288 * @return bool Whether the token matches
4290 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4291 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . Token
::SUFFIX
;
4292 return $this->matchEditToken( $val, $salt, $request, $maxage );
4296 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4297 * mail to the user's given address.
4299 * @param string $type Message to send, either "created", "changed" or "set"
4302 public function sendConfirmationMail( $type = 'created' ) {
4304 $expiration = null; // gets passed-by-ref and defined in next line.
4305 $token = $this->confirmationToken( $expiration );
4306 $url = $this->confirmationTokenUrl( $token );
4307 $invalidateURL = $this->invalidationTokenUrl( $token );
4308 $this->saveSettings();
4310 if ( $type == 'created' ||
$type === false ) {
4311 $message = 'confirmemail_body';
4312 } elseif ( $type === true ) {
4313 $message = 'confirmemail_body_changed';
4315 // Messages: confirmemail_body_changed, confirmemail_body_set
4316 $message = 'confirmemail_body_' . $type;
4319 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4320 wfMessage( $message,
4321 $this->getRequest()->getIP(),
4324 $wgLang->userTimeAndDate( $expiration, $this ),
4326 $wgLang->userDate( $expiration, $this ),
4327 $wgLang->userTime( $expiration, $this ) )->text() );
4331 * Send an e-mail to this user's account. Does not check for
4332 * confirmed status or validity.
4334 * @param string $subject Message subject
4335 * @param string $body Message body
4336 * @param User|null $from Optional sending user; if unspecified, default
4337 * $wgPasswordSender will be used.
4338 * @param string $replyto Reply-To address
4341 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4342 global $wgPasswordSender;
4344 if ( $from instanceof User
) {
4345 $sender = MailAddress
::newFromUser( $from );
4347 $sender = new MailAddress( $wgPasswordSender,
4348 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4350 $to = MailAddress
::newFromUser( $this );
4352 return UserMailer
::send( $to, $sender, $subject, $body, [
4353 'replyTo' => $replyto,
4358 * Generate, store, and return a new e-mail confirmation code.
4359 * A hash (unsalted, since it's used as a key) is stored.
4361 * @note Call saveSettings() after calling this function to commit
4362 * this change to the database.
4364 * @param string &$expiration Accepts the expiration time
4365 * @return string New token
4367 protected function confirmationToken( &$expiration ) {
4368 global $wgUserEmailConfirmationTokenExpiry;
4370 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4371 $expiration = wfTimestamp( TS_MW
, $expires );
4373 $token = MWCryptRand
::generateHex( 32 );
4374 $hash = md5( $token );
4375 $this->mEmailToken
= $hash;
4376 $this->mEmailTokenExpires
= $expiration;
4381 * Return a URL the user can use to confirm their email address.
4382 * @param string $token Accepts the email confirmation token
4383 * @return string New token URL
4385 protected function confirmationTokenUrl( $token ) {
4386 return $this->getTokenUrl( 'ConfirmEmail', $token );
4390 * Return a URL the user can use to invalidate their email address.
4391 * @param string $token Accepts the email confirmation token
4392 * @return string New token URL
4394 protected function invalidationTokenUrl( $token ) {
4395 return $this->getTokenUrl( 'InvalidateEmail', $token );
4399 * Internal function to format the e-mail validation/invalidation URLs.
4400 * This uses a quickie hack to use the
4401 * hardcoded English names of the Special: pages, for ASCII safety.
4403 * @note Since these URLs get dropped directly into emails, using the
4404 * short English names avoids insanely long URL-encoded links, which
4405 * also sometimes can get corrupted in some browsers/mailers
4406 * (bug 6957 with Gmail and Internet Explorer).
4408 * @param string $page Special page
4409 * @param string $token Token
4410 * @return string Formatted URL
4412 protected function getTokenUrl( $page, $token ) {
4413 // Hack to bypass localization of 'Special:'
4414 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4415 return $title->getCanonicalURL();
4419 * Mark the e-mail address confirmed.
4421 * @note Call saveSettings() after calling this function to commit the change.
4425 public function confirmEmail() {
4426 // Check if it's already confirmed, so we don't touch the database
4427 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4428 if ( !$this->isEmailConfirmed() ) {
4429 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4430 Hooks
::run( 'ConfirmEmailComplete', [ $this ] );
4436 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4437 * address if it was already confirmed.
4439 * @note Call saveSettings() after calling this function to commit the change.
4440 * @return bool Returns true
4442 public function invalidateEmail() {
4444 $this->mEmailToken
= null;
4445 $this->mEmailTokenExpires
= null;
4446 $this->setEmailAuthenticationTimestamp( null );
4448 Hooks
::run( 'InvalidateEmailComplete', [ $this ] );
4453 * Set the e-mail authentication timestamp.
4454 * @param string $timestamp TS_MW timestamp
4456 public function setEmailAuthenticationTimestamp( $timestamp ) {
4458 $this->mEmailAuthenticated
= $timestamp;
4459 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
4463 * Is this user allowed to send e-mails within limits of current
4464 * site configuration?
4467 public function canSendEmail() {
4468 global $wgEnableEmail, $wgEnableUserEmail;
4469 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4472 $canSend = $this->isEmailConfirmed();
4473 Hooks
::run( 'UserCanSendEmail', [ &$this, &$canSend ] );
4478 * Is this user allowed to receive e-mails within limits of current
4479 * site configuration?
4482 public function canReceiveEmail() {
4483 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4487 * Is this user's e-mail address valid-looking and confirmed within
4488 * limits of the current site configuration?
4490 * @note If $wgEmailAuthentication is on, this may require the user to have
4491 * confirmed their address by returning a code or using a password
4492 * sent to the address from the wiki.
4496 public function isEmailConfirmed() {
4497 global $wgEmailAuthentication;
4500 if ( Hooks
::run( 'EmailConfirmed', [ &$this, &$confirmed ] ) ) {
4501 if ( $this->isAnon() ) {
4504 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4507 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4517 * Check whether there is an outstanding request for e-mail confirmation.
4520 public function isEmailConfirmationPending() {
4521 global $wgEmailAuthentication;
4522 return $wgEmailAuthentication &&
4523 !$this->isEmailConfirmed() &&
4524 $this->mEmailToken
&&
4525 $this->mEmailTokenExpires
> wfTimestamp();
4529 * Get the timestamp of account creation.
4531 * @return string|bool|null Timestamp of account creation, false for
4532 * non-existent/anonymous user accounts, or null if existing account
4533 * but information is not in database.
4535 public function getRegistration() {
4536 if ( $this->isAnon() ) {
4540 return $this->mRegistration
;
4544 * Get the timestamp of the first edit
4546 * @return string|bool Timestamp of first edit, or false for
4547 * non-existent/anonymous user accounts.
4549 public function getFirstEditTimestamp() {
4550 if ( $this->getId() == 0 ) {
4551 return false; // anons
4553 $dbr = wfGetDB( DB_SLAVE
);
4554 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4555 [ 'rev_user' => $this->getId() ],
4557 [ 'ORDER BY' => 'rev_timestamp ASC' ]
4560 return false; // no edits
4562 return wfTimestamp( TS_MW
, $time );
4566 * Get the permissions associated with a given list of groups
4568 * @param array $groups Array of Strings List of internal group names
4569 * @return array Array of Strings List of permission key names for given groups combined
4571 public static function getGroupPermissions( $groups ) {
4572 global $wgGroupPermissions, $wgRevokePermissions;
4574 // grant every granted permission first
4575 foreach ( $groups as $group ) {
4576 if ( isset( $wgGroupPermissions[$group] ) ) {
4577 $rights = array_merge( $rights,
4578 // array_filter removes empty items
4579 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4582 // now revoke the revoked permissions
4583 foreach ( $groups as $group ) {
4584 if ( isset( $wgRevokePermissions[$group] ) ) {
4585 $rights = array_diff( $rights,
4586 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4589 return array_unique( $rights );
4593 * Get all the groups who have a given permission
4595 * @param string $role Role to check
4596 * @return array Array of Strings List of internal group names with the given permission
4598 public static function getGroupsWithPermission( $role ) {
4599 global $wgGroupPermissions;
4600 $allowedGroups = [];
4601 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4602 if ( self
::groupHasPermission( $group, $role ) ) {
4603 $allowedGroups[] = $group;
4606 return $allowedGroups;
4610 * Check, if the given group has the given permission
4612 * If you're wanting to check whether all users have a permission, use
4613 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4617 * @param string $group Group to check
4618 * @param string $role Role to check
4621 public static function groupHasPermission( $group, $role ) {
4622 global $wgGroupPermissions, $wgRevokePermissions;
4623 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4624 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4628 * Check if all users may be assumed to have the given permission
4630 * We generally assume so if the right is granted to '*' and isn't revoked
4631 * on any group. It doesn't attempt to take grants or other extension
4632 * limitations on rights into account in the general case, though, as that
4633 * would require it to always return false and defeat the purpose.
4634 * Specifically, session-based rights restrictions (such as OAuth or bot
4635 * passwords) are applied based on the current session.
4638 * @param string $right Right to check
4641 public static function isEveryoneAllowed( $right ) {
4642 global $wgGroupPermissions, $wgRevokePermissions;
4645 // Use the cached results, except in unit tests which rely on
4646 // being able change the permission mid-request
4647 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4648 return $cache[$right];
4651 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4652 $cache[$right] = false;
4656 // If it's revoked anywhere, then everyone doesn't have it
4657 foreach ( $wgRevokePermissions as $rights ) {
4658 if ( isset( $rights[$right] ) && $rights[$right] ) {
4659 $cache[$right] = false;
4664 // Remove any rights that aren't allowed to the global-session user,
4665 // unless there are no sessions for this endpoint.
4666 if ( !defined( 'MW_NO_SESSION' ) ) {
4667 $allowedRights = SessionManager
::getGlobalSession()->getAllowedUserRights();
4668 if ( $allowedRights !== null && !in_array( $right, $allowedRights, true ) ) {
4669 $cache[$right] = false;
4674 // Allow extensions to say false
4675 if ( !Hooks
::run( 'UserIsEveryoneAllowed', [ $right ] ) ) {
4676 $cache[$right] = false;
4680 $cache[$right] = true;
4685 * Get the localized descriptive name for a group, if it exists
4687 * @param string $group Internal group name
4688 * @return string Localized descriptive group name
4690 public static function getGroupName( $group ) {
4691 $msg = wfMessage( "group-$group" );
4692 return $msg->isBlank() ?
$group : $msg->text();
4696 * Get the localized descriptive name for a member of a group, if it exists
4698 * @param string $group Internal group name
4699 * @param string $username Username for gender (since 1.19)
4700 * @return string Localized name for group member
4702 public static function getGroupMember( $group, $username = '#' ) {
4703 $msg = wfMessage( "group-$group-member", $username );
4704 return $msg->isBlank() ?
$group : $msg->text();
4708 * Return the set of defined explicit groups.
4709 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4710 * are not included, as they are defined automatically, not in the database.
4711 * @return array Array of internal group names
4713 public static function getAllGroups() {
4714 global $wgGroupPermissions, $wgRevokePermissions;
4716 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4717 self
::getImplicitGroups()
4722 * Get a list of all available permissions.
4723 * @return string[] Array of permission names
4725 public static function getAllRights() {
4726 if ( self
::$mAllRights === false ) {
4727 global $wgAvailableRights;
4728 if ( count( $wgAvailableRights ) ) {
4729 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
4731 self
::$mAllRights = self
::$mCoreRights;
4733 Hooks
::run( 'UserGetAllRights', [ &self
::$mAllRights ] );
4735 return self
::$mAllRights;
4739 * Get a list of implicit groups
4740 * @return array Array of Strings Array of internal group names
4742 public static function getImplicitGroups() {
4743 global $wgImplicitGroups;
4745 $groups = $wgImplicitGroups;
4746 # Deprecated, use $wgImplicitGroups instead
4747 Hooks
::run( 'UserGetImplicitGroups', [ &$groups ], '1.25' );
4753 * Get the title of a page describing a particular group
4755 * @param string $group Internal group name
4756 * @return Title|bool Title of the page if it exists, false otherwise
4758 public static function getGroupPage( $group ) {
4759 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4760 if ( $msg->exists() ) {
4761 $title = Title
::newFromText( $msg->text() );
4762 if ( is_object( $title ) ) {
4770 * Create a link to the group in HTML, if available;
4771 * else return the group name.
4773 * @param string $group Internal name of the group
4774 * @param string $text The text of the link
4775 * @return string HTML link to the group
4777 public static function makeGroupLinkHTML( $group, $text = '' ) {
4778 if ( $text == '' ) {
4779 $text = self
::getGroupName( $group );
4781 $title = self
::getGroupPage( $group );
4783 return Linker
::link( $title, htmlspecialchars( $text ) );
4785 return htmlspecialchars( $text );
4790 * Create a link to the group in Wikitext, if available;
4791 * else return the group name.
4793 * @param string $group Internal name of the group
4794 * @param string $text The text of the link
4795 * @return string Wikilink to the group
4797 public static function makeGroupLinkWiki( $group, $text = '' ) {
4798 if ( $text == '' ) {
4799 $text = self
::getGroupName( $group );
4801 $title = self
::getGroupPage( $group );
4803 $page = $title->getFullText();
4804 return "[[$page|$text]]";
4811 * Returns an array of the groups that a particular group can add/remove.
4813 * @param string $group The group to check for whether it can add/remove
4814 * @return array Array( 'add' => array( addablegroups ),
4815 * 'remove' => array( removablegroups ),
4816 * 'add-self' => array( addablegroups to self),
4817 * 'remove-self' => array( removable groups from self) )
4819 public static function changeableByGroup( $group ) {
4820 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4829 if ( empty( $wgAddGroups[$group] ) ) {
4830 // Don't add anything to $groups
4831 } elseif ( $wgAddGroups[$group] === true ) {
4832 // You get everything
4833 $groups['add'] = self
::getAllGroups();
4834 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4835 $groups['add'] = $wgAddGroups[$group];
4838 // Same thing for remove
4839 if ( empty( $wgRemoveGroups[$group] ) ) {
4841 } elseif ( $wgRemoveGroups[$group] === true ) {
4842 $groups['remove'] = self
::getAllGroups();
4843 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4844 $groups['remove'] = $wgRemoveGroups[$group];
4847 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4848 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4849 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4850 if ( is_int( $key ) ) {
4851 $wgGroupsAddToSelf['user'][] = $value;
4856 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
4857 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4858 if ( is_int( $key ) ) {
4859 $wgGroupsRemoveFromSelf['user'][] = $value;
4864 // Now figure out what groups the user can add to him/herself
4865 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4867 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4868 // No idea WHY this would be used, but it's there
4869 $groups['add-self'] = User
::getAllGroups();
4870 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4871 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4874 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4876 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4877 $groups['remove-self'] = User
::getAllGroups();
4878 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4879 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4886 * Returns an array of groups that this user can add and remove
4887 * @return array Array( 'add' => array( addablegroups ),
4888 * 'remove' => array( removablegroups ),
4889 * 'add-self' => array( addablegroups to self),
4890 * 'remove-self' => array( removable groups from self) )
4892 public function changeableGroups() {
4893 if ( $this->isAllowed( 'userrights' ) ) {
4894 // This group gives the right to modify everything (reverse-
4895 // compatibility with old "userrights lets you change
4897 // Using array_merge to make the groups reindexed
4898 $all = array_merge( User
::getAllGroups() );
4907 // Okay, it's not so simple, we will have to go through the arrays
4914 $addergroups = $this->getEffectiveGroups();
4916 foreach ( $addergroups as $addergroup ) {
4917 $groups = array_merge_recursive(
4918 $groups, $this->changeableByGroup( $addergroup )
4920 $groups['add'] = array_unique( $groups['add'] );
4921 $groups['remove'] = array_unique( $groups['remove'] );
4922 $groups['add-self'] = array_unique( $groups['add-self'] );
4923 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4929 * Deferred version of incEditCountImmediate()
4931 public function incEditCount() {
4932 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle( function() {
4933 $this->incEditCountImmediate();
4938 * Increment the user's edit-count field.
4939 * Will have no effect for anonymous users.
4942 public function incEditCountImmediate() {
4943 if ( $this->isAnon() ) {
4947 $dbw = wfGetDB( DB_MASTER
);
4948 // No rows will be "affected" if user_editcount is NULL
4951 [ 'user_editcount=user_editcount+1' ],
4952 [ 'user_id' => $this->getId(), 'user_editcount IS NOT NULL' ],
4955 // Lazy initialization check...
4956 if ( $dbw->affectedRows() == 0 ) {
4957 // Now here's a goddamn hack...
4958 $dbr = wfGetDB( DB_SLAVE
);
4959 if ( $dbr !== $dbw ) {
4960 // If we actually have a slave server, the count is
4961 // at least one behind because the current transaction
4962 // has not been committed and replicated.
4963 $this->initEditCount( 1 );
4965 // But if DB_SLAVE is selecting the master, then the
4966 // count we just read includes the revision that was
4967 // just added in the working transaction.
4968 $this->initEditCount();
4971 // Edit count in user cache too
4972 $this->invalidateCache();
4976 * Initialize user_editcount from data out of the revision table
4978 * @param int $add Edits to add to the count from the revision table
4979 * @return int Number of edits
4981 protected function initEditCount( $add = 0 ) {
4982 // Pull from a slave to be less cruel to servers
4983 // Accuracy isn't the point anyway here
4984 $dbr = wfGetDB( DB_SLAVE
);
4985 $count = (int)$dbr->selectField(
4988 [ 'rev_user' => $this->getId() ],
4991 $count = $count +
$add;
4993 $dbw = wfGetDB( DB_MASTER
);
4996 [ 'user_editcount' => $count ],
4997 [ 'user_id' => $this->getId() ],
5005 * Get the description of a given right
5007 * @param string $right Right to query
5008 * @return string Localized description of the right
5010 public static function getRightDescription( $right ) {
5011 $key = "right-$right";
5012 $msg = wfMessage( $key );
5013 return $msg->isBlank() ?
$right : $msg->text();
5017 * Make a new-style password hash
5019 * @param string $password Plain-text password
5020 * @param bool|string $salt Optional salt, may be random or the user ID.
5021 * If unspecified or false, will generate one automatically
5022 * @return string Password hash
5023 * @deprecated since 1.24, use Password class
5025 public static function crypt( $password, $salt = false ) {
5026 wfDeprecated( __METHOD__
, '1.24' );
5027 $passwordFactory = new PasswordFactory();
5028 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
5029 $hash = $passwordFactory->newFromPlaintext( $password );
5030 return $hash->toString();
5034 * Compare a password hash with a plain-text password. Requires the user
5035 * ID if there's a chance that the hash is an old-style hash.
5037 * @param string $hash Password hash
5038 * @param string $password Plain-text password to compare
5039 * @param string|bool $userId User ID for old-style password salt
5042 * @deprecated since 1.24, use Password class
5044 public static function comparePasswords( $hash, $password, $userId = false ) {
5045 wfDeprecated( __METHOD__
, '1.24' );
5047 // Check for *really* old password hashes that don't even have a type
5048 // The old hash format was just an md5 hex hash, with no type information
5049 if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) {
5050 global $wgPasswordSalt;
5051 if ( $wgPasswordSalt ) {
5052 $password = ":B:{$userId}:{$hash}";
5054 $password = ":A:{$hash}";
5058 $passwordFactory = new PasswordFactory();
5059 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
5060 $hash = $passwordFactory->newFromCiphertext( $hash );
5061 return $hash->equals( $password );
5065 * Add a newuser log entry for this user.
5066 * Before 1.19 the return value was always true.
5068 * @param string|bool $action Account creation type.
5069 * - String, one of the following values:
5070 * - 'create' for an anonymous user creating an account for himself.
5071 * This will force the action's performer to be the created user itself,
5072 * no matter the value of $wgUser
5073 * - 'create2' for a logged in user creating an account for someone else
5074 * - 'byemail' when the created user will receive its password by e-mail
5075 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
5076 * - Boolean means whether the account was created by e-mail (deprecated):
5077 * - true will be converted to 'byemail'
5078 * - false will be converted to 'create' if this object is the same as
5079 * $wgUser and to 'create2' otherwise
5081 * @param string $reason User supplied reason
5083 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
5085 public function addNewUserLogEntry( $action = false, $reason = '' ) {
5086 global $wgUser, $wgNewUserLog;
5087 if ( empty( $wgNewUserLog ) ) {
5088 return true; // disabled
5091 if ( $action === true ) {
5092 $action = 'byemail';
5093 } elseif ( $action === false ) {
5094 if ( $this->equals( $wgUser ) ) {
5097 $action = 'create2';
5101 if ( $action === 'create' ||
$action === 'autocreate' ) {
5104 $performer = $wgUser;
5107 $logEntry = new ManualLogEntry( 'newusers', $action );
5108 $logEntry->setPerformer( $performer );
5109 $logEntry->setTarget( $this->getUserPage() );
5110 $logEntry->setComment( $reason );
5111 $logEntry->setParameters( [
5112 '4::userid' => $this->getId(),
5114 $logid = $logEntry->insert();
5116 if ( $action !== 'autocreate' ) {
5117 $logEntry->publish( $logid );
5124 * Add an autocreate newuser log entry for this user
5125 * Used by things like CentralAuth and perhaps other authplugins.
5126 * Consider calling addNewUserLogEntry() directly instead.
5130 public function addNewUserLogEntryAutoCreate() {
5131 $this->addNewUserLogEntry( 'autocreate' );
5137 * Load the user options either from cache, the database or an array
5139 * @param array $data Rows for the current user out of the user_properties table
5141 protected function loadOptions( $data = null ) {
5146 if ( $this->mOptionsLoaded
) {
5150 $this->mOptions
= self
::getDefaultOptions();
5152 if ( !$this->getId() ) {
5153 // For unlogged-in users, load language/variant options from request.
5154 // There's no need to do it for logged-in users: they can set preferences,
5155 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5156 // so don't override user's choice (especially when the user chooses site default).
5157 $variant = $wgContLang->getDefaultVariant();
5158 $this->mOptions
['variant'] = $variant;
5159 $this->mOptions
['language'] = $variant;
5160 $this->mOptionsLoaded
= true;
5164 // Maybe load from the object
5165 if ( !is_null( $this->mOptionOverrides
) ) {
5166 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5167 foreach ( $this->mOptionOverrides
as $key => $value ) {
5168 $this->mOptions
[$key] = $value;
5171 if ( !is_array( $data ) ) {
5172 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5173 // Load from database
5174 $dbr = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
5175 ?
wfGetDB( DB_MASTER
)
5176 : wfGetDB( DB_SLAVE
);
5178 $res = $dbr->select(
5180 [ 'up_property', 'up_value' ],
5181 [ 'up_user' => $this->getId() ],
5185 $this->mOptionOverrides
= [];
5187 foreach ( $res as $row ) {
5188 $data[$row->up_property
] = $row->up_value
;
5191 foreach ( $data as $property => $value ) {
5192 $this->mOptionOverrides
[$property] = $value;
5193 $this->mOptions
[$property] = $value;
5197 $this->mOptionsLoaded
= true;
5199 Hooks
::run( 'UserLoadOptions', [ $this, &$this->mOptions
] );
5203 * Saves the non-default options for this user, as previously set e.g. via
5204 * setOption(), in the database's "user_properties" (preferences) table.
5205 * Usually used via saveSettings().
5207 protected function saveOptions() {
5208 $this->loadOptions();
5210 // Not using getOptions(), to keep hidden preferences in database
5211 $saveOptions = $this->mOptions
;
5213 // Allow hooks to abort, for instance to save to a global profile.
5214 // Reset options to default state before saving.
5215 if ( !Hooks
::run( 'UserSaveOptions', [ $this, &$saveOptions ] ) ) {
5219 $userId = $this->getId();
5221 $insert_rows = []; // all the new preference rows
5222 foreach ( $saveOptions as $key => $value ) {
5223 // Don't bother storing default values
5224 $defaultOption = self
::getDefaultOption( $key );
5225 if ( ( $defaultOption === null && $value !== false && $value !== null )
5226 ||
$value != $defaultOption
5229 'up_user' => $userId,
5230 'up_property' => $key,
5231 'up_value' => $value,
5236 $dbw = wfGetDB( DB_MASTER
);
5238 $res = $dbw->select( 'user_properties',
5239 [ 'up_property', 'up_value' ], [ 'up_user' => $userId ], __METHOD__
);
5241 // Find prior rows that need to be removed or updated. These rows will
5242 // all be deleted (the later so that INSERT IGNORE applies the new values).
5244 foreach ( $res as $row ) {
5245 if ( !isset( $saveOptions[$row->up_property
] )
5246 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
5248 $keysDelete[] = $row->up_property
;
5252 if ( count( $keysDelete ) ) {
5253 // Do the DELETE by PRIMARY KEY for prior rows.
5254 // In the past a very large portion of calls to this function are for setting
5255 // 'rememberpassword' for new accounts (a preference that has since been removed).
5256 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5257 // caused gap locks on [max user ID,+infinity) which caused high contention since
5258 // updates would pile up on each other as they are for higher (newer) user IDs.
5259 // It might not be necessary these days, but it shouldn't hurt either.
5260 $dbw->delete( 'user_properties',
5261 [ 'up_user' => $userId, 'up_property' => $keysDelete ], __METHOD__
);
5263 // Insert the new preference rows
5264 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, [ 'IGNORE' ] );
5268 * Lazily instantiate and return a factory object for making passwords
5270 * @deprecated since 1.27, create a PasswordFactory directly instead
5271 * @return PasswordFactory
5273 public static function getPasswordFactory() {
5274 wfDeprecated( __METHOD__
, '1.27' );
5275 $ret = new PasswordFactory();
5276 $ret->init( RequestContext
::getMain()->getConfig() );
5281 * Provide an array of HTML5 attributes to put on an input element
5282 * intended for the user to enter a new password. This may include
5283 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
5285 * Do *not* use this when asking the user to enter his current password!
5286 * Regardless of configuration, users may have invalid passwords for whatever
5287 * reason (e.g., they were set before requirements were tightened up).
5288 * Only use it when asking for a new password, like on account creation or
5291 * Obviously, you still need to do server-side checking.
5293 * NOTE: A combination of bugs in various browsers means that this function
5294 * actually just returns array() unconditionally at the moment. May as
5295 * well keep it around for when the browser bugs get fixed, though.
5297 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
5299 * @deprecated since 1.27
5300 * @return array Array of HTML attributes suitable for feeding to
5301 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
5302 * That will get confused by the boolean attribute syntax used.)
5304 public static function passwordChangeInputAttribs() {
5305 global $wgMinimalPasswordLength;
5307 if ( $wgMinimalPasswordLength == 0 ) {
5311 # Note that the pattern requirement will always be satisfied if the
5312 # input is empty, so we need required in all cases.
5314 # @todo FIXME: Bug 23769: This needs to not claim the password is required
5315 # if e-mail confirmation is being used. Since HTML5 input validation
5316 # is b0rked anyway in some browsers, just return nothing. When it's
5317 # re-enabled, fix this code to not output required for e-mail
5319 # $ret = array( 'required' );
5322 # We can't actually do this right now, because Opera 9.6 will print out
5323 # the entered password visibly in its error message! When other
5324 # browsers add support for this attribute, or Opera fixes its support,
5325 # we can add support with a version check to avoid doing this on Opera
5326 # versions where it will be a problem. Reported to Opera as
5327 # DSK-262266, but they don't have a public bug tracker for us to follow.
5329 if ( $wgMinimalPasswordLength > 1 ) {
5330 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
5331 $ret['title'] = wfMessage( 'passwordtooshort' )
5332 ->numParams( $wgMinimalPasswordLength )->text();
5340 * Return the list of user fields that should be selected to create
5341 * a new user object.
5344 public static function selectFields() {
5352 'user_email_authenticated',
5354 'user_email_token_expires',
5355 'user_registration',
5361 * Factory function for fatal permission-denied errors
5364 * @param string $permission User right required
5367 static function newFatalPermissionDeniedStatus( $permission ) {
5370 $groups = array_map(
5371 [ 'User', 'makeGroupLinkWiki' ],
5372 User
::getGroupsWithPermission( $permission )
5376 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5378 return Status
::newFatal( 'badaccess-group0' );
5383 * Get a new instance of this user that was loaded from the master via a locking read
5385 * Use this instead of the main context User when updating that user. This avoids races
5386 * where that user was loaded from a slave or even the master but without proper locks.
5388 * @return User|null Returns null if the user was not found in the DB
5391 public function getInstanceForUpdate() {
5392 if ( !$this->getId() ) {
5393 return null; // anon
5396 $user = self
::newFromId( $this->getId() );
5397 if ( !$user->loadFromId( self
::READ_EXCLUSIVE
) ) {
5405 * Checks if two user objects point to the same user.
5411 public function equals( User
$user ) {
5412 return $this->getName() === $user->getName();