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 $mGlobalBlock;
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 return $this->getGlobalBlock( $ip ) instanceof Block
;
1999 * Check if user is blocked on all wikis.
2000 * Do not use for actual edit permission checks!
2001 * This is intended for quick UI checks.
2003 * @param string $ip IP address, uses current client if none given
2004 * @return Block|null Block object if blocked, null otherwise
2005 * @throws FatalError
2006 * @throws MWException
2008 public function getGlobalBlock( $ip = '' ) {
2009 if ( $this->mGlobalBlock
!== null ) {
2010 return $this->mGlobalBlock ?
: null;
2012 // User is already an IP?
2013 if ( IP
::isIPAddress( $this->getName() ) ) {
2014 $ip = $this->getName();
2016 $ip = $this->getRequest()->getIP();
2020 Hooks
::run( 'UserIsBlockedGlobally', [ &$this, $ip, &$blocked, &$block ] );
2022 if ( $blocked && $block === null ) {
2023 // back-compat: UserIsBlockedGlobally didn't have $block param first
2025 $block->setTarget( $ip );
2028 $this->mGlobalBlock
= $blocked ?
$block : false;
2029 return $this->mGlobalBlock ?
: null;
2033 * Check if user account is locked
2035 * @return bool True if locked, false otherwise
2037 public function isLocked() {
2038 if ( $this->mLocked
!== null ) {
2039 return $this->mLocked
;
2042 $authUser = $wgAuth->getUserInstance( $this );
2043 $this->mLocked
= (bool)$authUser->isLocked();
2044 Hooks
::run( 'UserIsLocked', [ $this, &$this->mLocked
] );
2045 return $this->mLocked
;
2049 * Check if user account is hidden
2051 * @return bool True if hidden, false otherwise
2053 public function isHidden() {
2054 if ( $this->mHideName
!== null ) {
2055 return $this->mHideName
;
2057 $this->getBlockedStatus();
2058 if ( !$this->mHideName
) {
2060 $authUser = $wgAuth->getUserInstance( $this );
2061 $this->mHideName
= (bool)$authUser->isHidden();
2062 Hooks
::run( 'UserIsHidden', [ $this, &$this->mHideName
] );
2064 return $this->mHideName
;
2068 * Get the user's ID.
2069 * @return int The user's ID; 0 if the user is anonymous or nonexistent
2071 public function getId() {
2072 if ( $this->mId
=== null && $this->mName
!== null && User
::isIP( $this->mName
) ) {
2073 // Special case, we know the user is anonymous
2075 } elseif ( !$this->isItemLoaded( 'id' ) ) {
2076 // Don't load if this was initialized from an ID
2080 return (int)$this->mId
;
2084 * Set the user and reload all fields according to a given ID
2085 * @param int $v User ID to reload
2087 public function setId( $v ) {
2089 $this->clearInstanceCache( 'id' );
2093 * Get the user name, or the IP of an anonymous user
2094 * @return string User's name or IP address
2096 public function getName() {
2097 if ( $this->isItemLoaded( 'name', 'only' ) ) {
2098 // Special case optimisation
2099 return $this->mName
;
2102 if ( $this->mName
=== false ) {
2104 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
2106 return $this->mName
;
2111 * Set the user name.
2113 * This does not reload fields from the database according to the given
2114 * name. Rather, it is used to create a temporary "nonexistent user" for
2115 * later addition to the database. It can also be used to set the IP
2116 * address for an anonymous user to something other than the current
2119 * @note User::newFromName() has roughly the same function, when the named user
2121 * @param string $str New user name to set
2123 public function setName( $str ) {
2125 $this->mName
= $str;
2129 * Get the user's name escaped by underscores.
2130 * @return string Username escaped by underscores.
2132 public function getTitleKey() {
2133 return str_replace( ' ', '_', $this->getName() );
2137 * Check if the user has new messages.
2138 * @return bool True if the user has new messages
2140 public function getNewtalk() {
2143 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2144 if ( $this->mNewtalk
=== -1 ) {
2145 $this->mNewtalk
= false; # reset talk page status
2147 // Check memcached separately for anons, who have no
2148 // entire User object stored in there.
2149 if ( !$this->mId
) {
2150 global $wgDisableAnonTalk;
2151 if ( $wgDisableAnonTalk ) {
2152 // Anon newtalk disabled by configuration.
2153 $this->mNewtalk
= false;
2155 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
2158 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2162 return (bool)$this->mNewtalk
;
2166 * Return the data needed to construct links for new talk page message
2167 * alerts. If there are new messages, this will return an associative array
2168 * with the following data:
2169 * wiki: The database name of the wiki
2170 * link: Root-relative link to the user's talk page
2171 * rev: The last talk page revision that the user has seen or null. This
2172 * is useful for building diff links.
2173 * If there are no new messages, it returns an empty array.
2174 * @note This function was designed to accomodate multiple talk pages, but
2175 * currently only returns a single link and revision.
2178 public function getNewMessageLinks() {
2180 if ( !Hooks
::run( 'UserRetrieveNewTalks', [ &$this, &$talks ] ) ) {
2182 } elseif ( !$this->getNewtalk() ) {
2185 $utp = $this->getTalkPage();
2186 $dbr = wfGetDB( DB_SLAVE
);
2187 // Get the "last viewed rev" timestamp from the oldest message notification
2188 $timestamp = $dbr->selectField( 'user_newtalk',
2189 'MIN(user_last_timestamp)',
2190 $this->isAnon() ?
[ 'user_ip' => $this->getName() ] : [ 'user_id' => $this->getId() ],
2192 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2193 return [ [ 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ] ];
2197 * Get the revision ID for the last talk page revision viewed by the talk
2199 * @return int|null Revision ID or null
2201 public function getNewMessageRevisionId() {
2202 $newMessageRevisionId = null;
2203 $newMessageLinks = $this->getNewMessageLinks();
2204 if ( $newMessageLinks ) {
2205 // Note: getNewMessageLinks() never returns more than a single link
2206 // and it is always for the same wiki, but we double-check here in
2207 // case that changes some time in the future.
2208 if ( count( $newMessageLinks ) === 1
2209 && $newMessageLinks[0]['wiki'] === wfWikiID()
2210 && $newMessageLinks[0]['rev']
2212 /** @var Revision $newMessageRevision */
2213 $newMessageRevision = $newMessageLinks[0]['rev'];
2214 $newMessageRevisionId = $newMessageRevision->getId();
2217 return $newMessageRevisionId;
2221 * Internal uncached check for new messages
2224 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2225 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2226 * @return bool True if the user has new messages
2228 protected function checkNewtalk( $field, $id ) {
2229 $dbr = wfGetDB( DB_SLAVE
);
2231 $ok = $dbr->selectField( 'user_newtalk', $field, [ $field => $id ], __METHOD__
);
2233 return $ok !== false;
2237 * Add or update the new messages flag
2238 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2239 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2240 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2241 * @return bool True if successful, false otherwise
2243 protected function updateNewtalk( $field, $id, $curRev = null ) {
2244 // Get timestamp of the talk page revision prior to the current one
2245 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2246 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2247 // Mark the user as having new messages since this revision
2248 $dbw = wfGetDB( DB_MASTER
);
2249 $dbw->insert( 'user_newtalk',
2250 [ $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ],
2253 if ( $dbw->affectedRows() ) {
2254 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2257 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2263 * Clear the new messages flag for the given user
2264 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2265 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2266 * @return bool True if successful, false otherwise
2268 protected function deleteNewtalk( $field, $id ) {
2269 $dbw = wfGetDB( DB_MASTER
);
2270 $dbw->delete( 'user_newtalk',
2273 if ( $dbw->affectedRows() ) {
2274 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2277 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2283 * Update the 'You have new messages!' status.
2284 * @param bool $val Whether the user has new messages
2285 * @param Revision $curRev New, as yet unseen revision of the user talk
2286 * page. Ignored if null or !$val.
2288 public function setNewtalk( $val, $curRev = null ) {
2289 if ( wfReadOnly() ) {
2294 $this->mNewtalk
= $val;
2296 if ( $this->isAnon() ) {
2298 $id = $this->getName();
2301 $id = $this->getId();
2305 $changed = $this->updateNewtalk( $field, $id, $curRev );
2307 $changed = $this->deleteNewtalk( $field, $id );
2311 $this->invalidateCache();
2316 * Generate a current or new-future timestamp to be stored in the
2317 * user_touched field when we update things.
2318 * @return string Timestamp in TS_MW format
2320 private function newTouchedTimestamp() {
2321 global $wgClockSkewFudge;
2323 $time = wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2324 if ( $this->mTouched
&& $time <= $this->mTouched
) {
2325 $time = wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $this->mTouched
) +
1 );
2332 * Clear user data from memcached
2334 * Use after applying updates to the database; caller's
2335 * responsibility to update user_touched if appropriate.
2337 * Called implicitly from invalidateCache() and saveSettings().
2339 * @param string $mode Use 'refresh' to clear now; otherwise before DB commit
2341 public function clearSharedCache( $mode = 'changed' ) {
2342 if ( !$this->getId() ) {
2346 $cache = ObjectCache
::getMainWANInstance();
2347 $processCache = self
::getInProcessCache();
2348 $key = $this->getCacheKey( $cache );
2349 if ( $mode === 'refresh' ) {
2350 $cache->delete( $key, 1 );
2351 $processCache->delete( $key );
2353 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle(
2354 function() use ( $cache, $processCache, $key ) {
2355 $cache->delete( $key );
2356 $processCache->delete( $key );
2363 * Immediately touch the user data cache for this account
2365 * Calls touch() and removes account data from memcached
2367 public function invalidateCache() {
2369 $this->clearSharedCache();
2373 * Update the "touched" timestamp for the user
2375 * This is useful on various login/logout events when making sure that
2376 * a browser or proxy that has multiple tenants does not suffer cache
2377 * pollution where the new user sees the old users content. The value
2378 * of getTouched() is checked when determining 304 vs 200 responses.
2379 * Unlike invalidateCache(), this preserves the User object cache and
2380 * avoids database writes.
2384 public function touch() {
2385 $id = $this->getId();
2387 $key = wfMemcKey( 'user-quicktouched', 'id', $id );
2388 ObjectCache
::getMainWANInstance()->touchCheckKey( $key );
2389 $this->mQuickTouched
= null;
2394 * Validate the cache for this account.
2395 * @param string $timestamp A timestamp in TS_MW format
2398 public function validateCache( $timestamp ) {
2399 return ( $timestamp >= $this->getTouched() );
2403 * Get the user touched timestamp
2405 * Use this value only to validate caches via inequalities
2406 * such as in the case of HTTP If-Modified-Since response logic
2408 * @return string TS_MW Timestamp
2410 public function getTouched() {
2414 if ( $this->mQuickTouched
=== null ) {
2415 $key = wfMemcKey( 'user-quicktouched', 'id', $this->mId
);
2416 $cache = ObjectCache
::getMainWANInstance();
2418 $this->mQuickTouched
= wfTimestamp( TS_MW
, $cache->getCheckKeyTime( $key ) );
2421 return max( $this->mTouched
, $this->mQuickTouched
);
2424 return $this->mTouched
;
2428 * Get the user_touched timestamp field (time of last DB updates)
2429 * @return string TS_MW Timestamp
2432 public function getDBTouched() {
2435 return $this->mTouched
;
2439 * @deprecated Removed in 1.27.
2443 public function getPassword() {
2444 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2448 * @deprecated Removed in 1.27.
2452 public function getTemporaryPassword() {
2453 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2457 * Set the password and reset the random token.
2458 * Calls through to authentication plugin if necessary;
2459 * will have no effect if the auth plugin refuses to
2460 * pass the change through or if the legal password
2463 * As a special case, setting the password to null
2464 * wipes it, so the account cannot be logged in until
2465 * a new password is set, for instance via e-mail.
2467 * @deprecated since 1.27. AuthManager is coming.
2468 * @param string $str New password to set
2469 * @throws PasswordError On failure
2472 public function setPassword( $str ) {
2475 if ( $str !== null ) {
2476 if ( !$wgAuth->allowPasswordChange() ) {
2477 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2480 $status = $this->checkPasswordValidity( $str );
2481 if ( !$status->isGood() ) {
2482 throw new PasswordError( $status->getMessage()->text() );
2486 if ( !$wgAuth->setPassword( $this, $str ) ) {
2487 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2491 $this->setOption( 'watchlisttoken', false );
2492 $this->setPasswordInternal( $str );
2498 * Set the password and reset the random token unconditionally.
2500 * @deprecated since 1.27. AuthManager is coming.
2501 * @param string|null $str New password to set or null to set an invalid
2502 * password hash meaning that the user will not be able to log in
2503 * through the web interface.
2505 public function setInternalPassword( $str ) {
2508 if ( $wgAuth->allowSetLocalPassword() ) {
2510 $this->setOption( 'watchlisttoken', false );
2511 $this->setPasswordInternal( $str );
2516 * Actually set the password and such
2517 * @since 1.27 cannot set a password for a user not in the database
2518 * @param string|null $str New password to set or null to set an invalid
2519 * password hash meaning that the user will not be able to log in
2520 * through the web interface.
2522 private function setPasswordInternal( $str ) {
2523 $id = self
::idFromName( $this->getName(), self
::READ_LATEST
);
2525 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2528 $passwordFactory = new PasswordFactory();
2529 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
2530 $dbw = wfGetDB( DB_MASTER
);
2534 'user_password' => $passwordFactory->newFromPlaintext( $str )->toString(),
2535 'user_newpassword' => PasswordFactory
::newInvalidPassword()->toString(),
2536 'user_newpass_time' => $dbw->timestampOrNull( null ),
2544 // When the main password is changed, invalidate all bot passwords too
2545 BotPassword
::invalidateAllPasswordsForUser( $this->getName() );
2549 * Get the user's current token.
2550 * @param bool $forceCreation Force the generation of a new token if the
2551 * user doesn't have one (default=true for backwards compatibility).
2552 * @return string|null Token
2554 public function getToken( $forceCreation = true ) {
2555 global $wgAuthenticationTokenVersion;
2558 if ( !$this->mToken
&& $forceCreation ) {
2562 if ( !$this->mToken
) {
2563 // The user doesn't have a token, return null to indicate that.
2565 } elseif ( $this->mToken
=== self
::INVALID_TOKEN
) {
2566 // We return a random value here so existing token checks are very
2568 return MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2569 } elseif ( $wgAuthenticationTokenVersion === null ) {
2570 // $wgAuthenticationTokenVersion not in use, so return the raw secret
2571 return $this->mToken
;
2573 // $wgAuthenticationTokenVersion in use, so hmac it.
2574 $ret = MWCryptHash
::hmac( $wgAuthenticationTokenVersion, $this->mToken
, false );
2576 // The raw hash can be overly long. Shorten it up.
2577 $len = max( 32, self
::TOKEN_LENGTH
);
2578 if ( strlen( $ret ) < $len ) {
2579 // Should never happen, even md5 is 128 bits
2580 throw new \
UnexpectedValueException( 'Hmac returned less than 128 bits' );
2582 return substr( $ret, -$len );
2587 * Set the random token (used for persistent authentication)
2588 * Called from loadDefaults() among other places.
2590 * @param string|bool $token If specified, set the token to this value
2592 public function setToken( $token = false ) {
2594 if ( $this->mToken
=== self
::INVALID_TOKEN
) {
2595 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
2596 ->debug( __METHOD__
. ": Ignoring attempt to set token for system user \"$this\"" );
2597 } elseif ( !$token ) {
2598 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2600 $this->mToken
= $token;
2605 * Set the password for a password reminder or new account email
2607 * @deprecated since 1.27, AuthManager is coming
2608 * @param string $str New password to set or null to set an invalid
2609 * password hash meaning that the user will not be able to use it
2610 * @param bool $throttle If true, reset the throttle timestamp to the present
2612 public function setNewpassword( $str, $throttle = true ) {
2613 $id = $this->getId();
2615 throw new LogicException( 'Cannot set new password for a user that is not in the database.' );
2618 $dbw = wfGetDB( DB_MASTER
);
2620 $passwordFactory = new PasswordFactory();
2621 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
2623 'user_newpassword' => $passwordFactory->newFromPlaintext( $str )->toString(),
2626 if ( $str === null ) {
2627 $update['user_newpass_time'] = null;
2628 } elseif ( $throttle ) {
2629 $update['user_newpass_time'] = $dbw->timestamp();
2632 $dbw->update( 'user', $update, [ 'user_id' => $id ], __METHOD__
);
2636 * Has password reminder email been sent within the last
2637 * $wgPasswordReminderResendTime hours?
2640 public function isPasswordReminderThrottled() {
2641 global $wgPasswordReminderResendTime;
2643 if ( !$wgPasswordReminderResendTime ) {
2649 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
2650 ?
wfGetDB( DB_MASTER
)
2651 : wfGetDB( DB_SLAVE
);
2652 $newpassTime = $db->selectField(
2654 'user_newpass_time',
2655 [ 'user_id' => $this->getId() ],
2659 if ( $newpassTime === null ) {
2662 $expiry = wfTimestamp( TS_UNIX
, $newpassTime ) +
$wgPasswordReminderResendTime * 3600;
2663 return time() < $expiry;
2667 * Get the user's e-mail address
2668 * @return string User's email address
2670 public function getEmail() {
2672 Hooks
::run( 'UserGetEmail', [ $this, &$this->mEmail
] );
2673 return $this->mEmail
;
2677 * Get the timestamp of the user's e-mail authentication
2678 * @return string TS_MW timestamp
2680 public function getEmailAuthenticationTimestamp() {
2682 Hooks
::run( 'UserGetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
2683 return $this->mEmailAuthenticated
;
2687 * Set the user's e-mail address
2688 * @param string $str New e-mail address
2690 public function setEmail( $str ) {
2692 if ( $str == $this->mEmail
) {
2695 $this->invalidateEmail();
2696 $this->mEmail
= $str;
2697 Hooks
::run( 'UserSetEmail', [ $this, &$this->mEmail
] );
2701 * Set the user's e-mail address and a confirmation mail if needed.
2704 * @param string $str New e-mail address
2707 public function setEmailWithConfirmation( $str ) {
2708 global $wgEnableEmail, $wgEmailAuthentication;
2710 if ( !$wgEnableEmail ) {
2711 return Status
::newFatal( 'emaildisabled' );
2714 $oldaddr = $this->getEmail();
2715 if ( $str === $oldaddr ) {
2716 return Status
::newGood( true );
2719 $type = $oldaddr != '' ?
'changed' : 'set';
2720 $notificationResult = null;
2722 if ( $wgEmailAuthentication ) {
2723 // Send the user an email notifying the user of the change in registered
2724 // email address on their previous email address
2725 if ( $type == 'changed' ) {
2726 $change = $str != '' ?
'changed' : 'removed';
2727 $notificationResult = $this->sendMail(
2728 wfMessage( 'notificationemail_subject_' . $change )->text(),
2729 wfMessage( 'notificationemail_body_' . $change,
2730 $this->getRequest()->getIP(),
2737 $this->setEmail( $str );
2739 if ( $str !== '' && $wgEmailAuthentication ) {
2740 // Send a confirmation request to the new address if needed
2741 $result = $this->sendConfirmationMail( $type );
2743 if ( $notificationResult !== null ) {
2744 $result->merge( $notificationResult );
2747 if ( $result->isGood() ) {
2748 // Say to the caller that a confirmation and notification mail has been sent
2749 $result->value
= 'eauth';
2752 $result = Status
::newGood( true );
2759 * Get the user's real name
2760 * @return string User's real name
2762 public function getRealName() {
2763 if ( !$this->isItemLoaded( 'realname' ) ) {
2767 return $this->mRealName
;
2771 * Set the user's real name
2772 * @param string $str New real name
2774 public function setRealName( $str ) {
2776 $this->mRealName
= $str;
2780 * Get the user's current setting for a given option.
2782 * @param string $oname The option to check
2783 * @param string $defaultOverride A default value returned if the option does not exist
2784 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2785 * @return string User's current value for the option
2786 * @see getBoolOption()
2787 * @see getIntOption()
2789 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2790 global $wgHiddenPrefs;
2791 $this->loadOptions();
2793 # We want 'disabled' preferences to always behave as the default value for
2794 # users, even if they have set the option explicitly in their settings (ie they
2795 # set it, and then it was disabled removing their ability to change it). But
2796 # we don't want to erase the preferences in the database in case the preference
2797 # is re-enabled again. So don't touch $mOptions, just override the returned value
2798 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2799 return self
::getDefaultOption( $oname );
2802 if ( array_key_exists( $oname, $this->mOptions
) ) {
2803 return $this->mOptions
[$oname];
2805 return $defaultOverride;
2810 * Get all user's options
2812 * @param int $flags Bitwise combination of:
2813 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2814 * to the default value. (Since 1.25)
2817 public function getOptions( $flags = 0 ) {
2818 global $wgHiddenPrefs;
2819 $this->loadOptions();
2820 $options = $this->mOptions
;
2822 # We want 'disabled' preferences to always behave as the default value for
2823 # users, even if they have set the option explicitly in their settings (ie they
2824 # set it, and then it was disabled removing their ability to change it). But
2825 # we don't want to erase the preferences in the database in case the preference
2826 # is re-enabled again. So don't touch $mOptions, just override the returned value
2827 foreach ( $wgHiddenPrefs as $pref ) {
2828 $default = self
::getDefaultOption( $pref );
2829 if ( $default !== null ) {
2830 $options[$pref] = $default;
2834 if ( $flags & self
::GETOPTIONS_EXCLUDE_DEFAULTS
) {
2835 $options = array_diff_assoc( $options, self
::getDefaultOptions() );
2842 * Get the user's current setting for a given option, as a boolean value.
2844 * @param string $oname The option to check
2845 * @return bool User's current value for the option
2848 public function getBoolOption( $oname ) {
2849 return (bool)$this->getOption( $oname );
2853 * Get the user's current setting for a given option, as an integer value.
2855 * @param string $oname The option to check
2856 * @param int $defaultOverride A default value returned if the option does not exist
2857 * @return int User's current value for the option
2860 public function getIntOption( $oname, $defaultOverride = 0 ) {
2861 $val = $this->getOption( $oname );
2863 $val = $defaultOverride;
2865 return intval( $val );
2869 * Set the given option for a user.
2871 * You need to call saveSettings() to actually write to the database.
2873 * @param string $oname The option to set
2874 * @param mixed $val New value to set
2876 public function setOption( $oname, $val ) {
2877 $this->loadOptions();
2879 // Explicitly NULL values should refer to defaults
2880 if ( is_null( $val ) ) {
2881 $val = self
::getDefaultOption( $oname );
2884 $this->mOptions
[$oname] = $val;
2888 * Get a token stored in the preferences (like the watchlist one),
2889 * resetting it if it's empty (and saving changes).
2891 * @param string $oname The option name to retrieve the token from
2892 * @return string|bool User's current value for the option, or false if this option is disabled.
2893 * @see resetTokenFromOption()
2895 * @deprecated 1.26 Applications should use the OAuth extension
2897 public function getTokenFromOption( $oname ) {
2898 global $wgHiddenPrefs;
2900 $id = $this->getId();
2901 if ( !$id ||
in_array( $oname, $wgHiddenPrefs ) ) {
2905 $token = $this->getOption( $oname );
2907 // Default to a value based on the user token to avoid space
2908 // wasted on storing tokens for all users. When this option
2909 // is set manually by the user, only then is it stored.
2910 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
2917 * Reset a token stored in the preferences (like the watchlist one).
2918 * *Does not* save user's preferences (similarly to setOption()).
2920 * @param string $oname The option name to reset the token in
2921 * @return string|bool New token value, or false if this option is disabled.
2922 * @see getTokenFromOption()
2925 public function resetTokenFromOption( $oname ) {
2926 global $wgHiddenPrefs;
2927 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2931 $token = MWCryptRand
::generateHex( 40 );
2932 $this->setOption( $oname, $token );
2937 * Return a list of the types of user options currently returned by
2938 * User::getOptionKinds().
2940 * Currently, the option kinds are:
2941 * - 'registered' - preferences which are registered in core MediaWiki or
2942 * by extensions using the UserGetDefaultOptions hook.
2943 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2944 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2945 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2946 * be used by user scripts.
2947 * - 'special' - "preferences" that are not accessible via User::getOptions
2948 * or User::setOptions.
2949 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2950 * These are usually legacy options, removed in newer versions.
2952 * The API (and possibly others) use this function to determine the possible
2953 * option types for validation purposes, so make sure to update this when a
2954 * new option kind is added.
2956 * @see User::getOptionKinds
2957 * @return array Option kinds
2959 public static function listOptionKinds() {
2962 'registered-multiselect',
2963 'registered-checkmatrix',
2971 * Return an associative array mapping preferences keys to the kind of a preference they're
2972 * used for. Different kinds are handled differently when setting or reading preferences.
2974 * See User::listOptionKinds for the list of valid option types that can be provided.
2976 * @see User::listOptionKinds
2977 * @param IContextSource $context
2978 * @param array $options Assoc. array with options keys to check as keys.
2979 * Defaults to $this->mOptions.
2980 * @return array The key => kind mapping data
2982 public function getOptionKinds( IContextSource
$context, $options = null ) {
2983 $this->loadOptions();
2984 if ( $options === null ) {
2985 $options = $this->mOptions
;
2988 $prefs = Preferences
::getPreferences( $this, $context );
2991 // Pull out the "special" options, so they don't get converted as
2992 // multiselect or checkmatrix.
2993 $specialOptions = array_fill_keys( Preferences
::getSaveBlacklist(), true );
2994 foreach ( $specialOptions as $name => $value ) {
2995 unset( $prefs[$name] );
2998 // Multiselect and checkmatrix options are stored in the database with
2999 // one key per option, each having a boolean value. Extract those keys.
3000 $multiselectOptions = [];
3001 foreach ( $prefs as $name => $info ) {
3002 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
3003 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
3004 $opts = HTMLFormField
::flattenOptions( $info['options'] );
3005 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
3007 foreach ( $opts as $value ) {
3008 $multiselectOptions["$prefix$value"] = true;
3011 unset( $prefs[$name] );
3014 $checkmatrixOptions = [];
3015 foreach ( $prefs as $name => $info ) {
3016 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
3017 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
3018 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
3019 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
3020 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
3022 foreach ( $columns as $column ) {
3023 foreach ( $rows as $row ) {
3024 $checkmatrixOptions["$prefix$column-$row"] = true;
3028 unset( $prefs[$name] );
3032 // $value is ignored
3033 foreach ( $options as $key => $value ) {
3034 if ( isset( $prefs[$key] ) ) {
3035 $mapping[$key] = 'registered';
3036 } elseif ( isset( $multiselectOptions[$key] ) ) {
3037 $mapping[$key] = 'registered-multiselect';
3038 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
3039 $mapping[$key] = 'registered-checkmatrix';
3040 } elseif ( isset( $specialOptions[$key] ) ) {
3041 $mapping[$key] = 'special';
3042 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
3043 $mapping[$key] = 'userjs';
3045 $mapping[$key] = 'unused';
3053 * Reset certain (or all) options to the site defaults
3055 * The optional parameter determines which kinds of preferences will be reset.
3056 * Supported values are everything that can be reported by getOptionKinds()
3057 * and 'all', which forces a reset of *all* preferences and overrides everything else.
3059 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
3060 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
3061 * for backwards-compatibility.
3062 * @param IContextSource|null $context Context source used when $resetKinds
3063 * does not contain 'all', passed to getOptionKinds().
3064 * Defaults to RequestContext::getMain() when null.
3066 public function resetOptions(
3067 $resetKinds = [ 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ],
3068 IContextSource
$context = null
3071 $defaultOptions = self
::getDefaultOptions();
3073 if ( !is_array( $resetKinds ) ) {
3074 $resetKinds = [ $resetKinds ];
3077 if ( in_array( 'all', $resetKinds ) ) {
3078 $newOptions = $defaultOptions;
3080 if ( $context === null ) {
3081 $context = RequestContext
::getMain();
3084 $optionKinds = $this->getOptionKinds( $context );
3085 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
3088 // Use default values for the options that should be deleted, and
3089 // copy old values for the ones that shouldn't.
3090 foreach ( $this->mOptions
as $key => $value ) {
3091 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
3092 if ( array_key_exists( $key, $defaultOptions ) ) {
3093 $newOptions[$key] = $defaultOptions[$key];
3096 $newOptions[$key] = $value;
3101 Hooks
::run( 'UserResetAllOptions', [ $this, &$newOptions, $this->mOptions
, $resetKinds ] );
3103 $this->mOptions
= $newOptions;
3104 $this->mOptionsLoaded
= true;
3108 * Get the user's preferred date format.
3109 * @return string User's preferred date format
3111 public function getDatePreference() {
3112 // Important migration for old data rows
3113 if ( is_null( $this->mDatePreference
) ) {
3115 $value = $this->getOption( 'date' );
3116 $map = $wgLang->getDatePreferenceMigrationMap();
3117 if ( isset( $map[$value] ) ) {
3118 $value = $map[$value];
3120 $this->mDatePreference
= $value;
3122 return $this->mDatePreference
;
3126 * Determine based on the wiki configuration and the user's options,
3127 * whether this user must be over HTTPS no matter what.
3131 public function requiresHTTPS() {
3132 global $wgSecureLogin;
3133 if ( !$wgSecureLogin ) {
3136 $https = $this->getBoolOption( 'prefershttps' );
3137 Hooks
::run( 'UserRequiresHTTPS', [ $this, &$https ] );
3139 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
3146 * Get the user preferred stub threshold
3150 public function getStubThreshold() {
3151 global $wgMaxArticleSize; # Maximum article size, in Kb
3152 $threshold = $this->getIntOption( 'stubthreshold' );
3153 if ( $threshold > $wgMaxArticleSize * 1024 ) {
3154 // If they have set an impossible value, disable the preference
3155 // so we can use the parser cache again.
3162 * Get the permissions this user has.
3163 * @return array Array of String permission names
3165 public function getRights() {
3166 if ( is_null( $this->mRights
) ) {
3167 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
3169 // Deny any rights denied by the user's session, unless this
3170 // endpoint has no sessions.
3171 if ( !defined( 'MW_NO_SESSION' ) ) {
3172 $allowedRights = $this->getRequest()->getSession()->getAllowedUserRights();
3173 if ( $allowedRights !== null ) {
3174 $this->mRights
= array_intersect( $this->mRights
, $allowedRights );
3178 Hooks
::run( 'UserGetRights', [ $this, &$this->mRights
] );
3179 // Force reindexation of rights when a hook has unset one of them
3180 $this->mRights
= array_values( array_unique( $this->mRights
) );
3182 return $this->mRights
;
3186 * Get the list of explicit group memberships this user has.
3187 * The implicit * and user groups are not included.
3188 * @return array Array of String internal group names
3190 public function getGroups() {
3192 $this->loadGroups();
3193 return $this->mGroups
;
3197 * Get the list of implicit group memberships this user has.
3198 * This includes all explicit groups, plus 'user' if logged in,
3199 * '*' for all accounts, and autopromoted groups
3200 * @param bool $recache Whether to avoid the cache
3201 * @return array Array of String internal group names
3203 public function getEffectiveGroups( $recache = false ) {
3204 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
3205 $this->mEffectiveGroups
= array_unique( array_merge(
3206 $this->getGroups(), // explicit groups
3207 $this->getAutomaticGroups( $recache ) // implicit groups
3209 // Hook for additional groups
3210 Hooks
::run( 'UserEffectiveGroups', [ &$this, &$this->mEffectiveGroups
] );
3211 // Force reindexation of groups when a hook has unset one of them
3212 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
3214 return $this->mEffectiveGroups
;
3218 * Get the list of implicit group memberships this user has.
3219 * This includes 'user' if logged in, '*' for all accounts,
3220 * and autopromoted groups
3221 * @param bool $recache Whether to avoid the cache
3222 * @return array Array of String internal group names
3224 public function getAutomaticGroups( $recache = false ) {
3225 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
3226 $this->mImplicitGroups
= [ '*' ];
3227 if ( $this->getId() ) {
3228 $this->mImplicitGroups
[] = 'user';
3230 $this->mImplicitGroups
= array_unique( array_merge(
3231 $this->mImplicitGroups
,
3232 Autopromote
::getAutopromoteGroups( $this )
3236 // Assure data consistency with rights/groups,
3237 // as getEffectiveGroups() depends on this function
3238 $this->mEffectiveGroups
= null;
3241 return $this->mImplicitGroups
;
3245 * Returns the groups the user has belonged to.
3247 * The user may still belong to the returned groups. Compare with getGroups().
3249 * The function will not return groups the user had belonged to before MW 1.17
3251 * @return array Names of the groups the user has belonged to.
3253 public function getFormerGroups() {
3256 if ( is_null( $this->mFormerGroups
) ) {
3257 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3258 ?
wfGetDB( DB_MASTER
)
3259 : wfGetDB( DB_SLAVE
);
3260 $res = $db->select( 'user_former_groups',
3262 [ 'ufg_user' => $this->mId
],
3264 $this->mFormerGroups
= [];
3265 foreach ( $res as $row ) {
3266 $this->mFormerGroups
[] = $row->ufg_group
;
3270 return $this->mFormerGroups
;
3274 * Get the user's edit count.
3275 * @return int|null Null for anonymous users
3277 public function getEditCount() {
3278 if ( !$this->getId() ) {
3282 if ( $this->mEditCount
=== null ) {
3283 /* Populate the count, if it has not been populated yet */
3284 $dbr = wfGetDB( DB_SLAVE
);
3285 // check if the user_editcount field has been initialized
3286 $count = $dbr->selectField(
3287 'user', 'user_editcount',
3288 [ 'user_id' => $this->mId
],
3292 if ( $count === null ) {
3293 // it has not been initialized. do so.
3294 $count = $this->initEditCount();
3296 $this->mEditCount
= $count;
3298 return (int)$this->mEditCount
;
3302 * Add the user to the given group.
3303 * This takes immediate effect.
3304 * @param string $group Name of the group to add
3307 public function addGroup( $group ) {
3310 if ( !Hooks
::run( 'UserAddGroup', [ $this, &$group ] ) ) {
3314 $dbw = wfGetDB( DB_MASTER
);
3315 if ( $this->getId() ) {
3316 $dbw->insert( 'user_groups',
3318 'ug_user' => $this->getId(),
3319 'ug_group' => $group,
3325 $this->loadGroups();
3326 $this->mGroups
[] = $group;
3327 // In case loadGroups was not called before, we now have the right twice.
3328 // Get rid of the duplicate.
3329 $this->mGroups
= array_unique( $this->mGroups
);
3331 // Refresh the groups caches, and clear the rights cache so it will be
3332 // refreshed on the next call to $this->getRights().
3333 $this->getEffectiveGroups( true );
3334 $this->mRights
= null;
3336 $this->invalidateCache();
3342 * Remove the user from the given group.
3343 * This takes immediate effect.
3344 * @param string $group Name of the group to remove
3347 public function removeGroup( $group ) {
3349 if ( !Hooks
::run( 'UserRemoveGroup', [ $this, &$group ] ) ) {
3353 $dbw = wfGetDB( DB_MASTER
);
3354 $dbw->delete( 'user_groups',
3356 'ug_user' => $this->getId(),
3357 'ug_group' => $group,
3360 // Remember that the user was in this group
3361 $dbw->insert( 'user_former_groups',
3363 'ufg_user' => $this->getId(),
3364 'ufg_group' => $group,
3370 $this->loadGroups();
3371 $this->mGroups
= array_diff( $this->mGroups
, [ $group ] );
3373 // Refresh the groups caches, and clear the rights cache so it will be
3374 // refreshed on the next call to $this->getRights().
3375 $this->getEffectiveGroups( true );
3376 $this->mRights
= null;
3378 $this->invalidateCache();
3384 * Get whether the user is logged in
3387 public function isLoggedIn() {
3388 return $this->getId() != 0;
3392 * Get whether the user is anonymous
3395 public function isAnon() {
3396 return !$this->isLoggedIn();
3400 * Check if user is allowed to access a feature / make an action
3402 * @param string ... Permissions to test
3403 * @return bool True if user is allowed to perform *any* of the given actions
3405 public function isAllowedAny() {
3406 $permissions = func_get_args();
3407 foreach ( $permissions as $permission ) {
3408 if ( $this->isAllowed( $permission ) ) {
3417 * @param string ... Permissions to test
3418 * @return bool True if the user is allowed to perform *all* of the given actions
3420 public function isAllowedAll() {
3421 $permissions = func_get_args();
3422 foreach ( $permissions as $permission ) {
3423 if ( !$this->isAllowed( $permission ) ) {
3431 * Internal mechanics of testing a permission
3432 * @param string $action
3435 public function isAllowed( $action = '' ) {
3436 if ( $action === '' ) {
3437 return true; // In the spirit of DWIM
3439 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3440 // by misconfiguration: 0 == 'foo'
3441 return in_array( $action, $this->getRights(), true );
3445 * Check whether to enable recent changes patrol features for this user
3446 * @return bool True or false
3448 public function useRCPatrol() {
3449 global $wgUseRCPatrol;
3450 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3454 * Check whether to enable new pages patrol features for this user
3455 * @return bool True or false
3457 public function useNPPatrol() {
3458 global $wgUseRCPatrol, $wgUseNPPatrol;
3460 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3461 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3466 * Check whether to enable new files patrol features for this user
3467 * @return bool True or false
3469 public function useFilePatrol() {
3470 global $wgUseRCPatrol, $wgUseFilePatrol;
3472 ( $wgUseRCPatrol ||
$wgUseFilePatrol )
3473 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3478 * Get the WebRequest object to use with this object
3480 * @return WebRequest
3482 public function getRequest() {
3483 if ( $this->mRequest
) {
3484 return $this->mRequest
;
3492 * Check the watched status of an article.
3493 * @since 1.22 $checkRights parameter added
3494 * @param Title $title Title of the article to look at
3495 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3496 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3499 public function isWatched( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3500 if ( $title->isWatchable() && ( !$checkRights ||
$this->isAllowed( 'viewmywatchlist' ) ) ) {
3501 return WatchedItemStore
::getDefaultInstance()->isWatched( $this, $title );
3508 * @since 1.22 $checkRights parameter added
3509 * @param Title $title Title of the article to look at
3510 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3511 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3513 public function addWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3514 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3515 WatchedItemStore
::getDefaultInstance()->addWatchBatchForUser(
3517 [ $title->getSubjectPage(), $title->getTalkPage() ]
3520 $this->invalidateCache();
3524 * Stop watching an article.
3525 * @since 1.22 $checkRights parameter added
3526 * @param Title $title Title of the article to look at
3527 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3528 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3530 public function removeWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3531 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3532 WatchedItemStore
::getDefaultInstance()->removeWatch( $this, $title->getSubjectPage() );
3533 WatchedItemStore
::getDefaultInstance()->removeWatch( $this, $title->getTalkPage() );
3535 $this->invalidateCache();
3539 * Clear the user's notification timestamp for the given title.
3540 * If e-notif e-mails are on, they will receive notification mails on
3541 * the next change of the page if it's watched etc.
3542 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3543 * @param Title $title Title of the article to look at
3544 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3546 public function clearNotification( &$title, $oldid = 0 ) {
3547 global $wgUseEnotif, $wgShowUpdatedMarker;
3549 // Do nothing if the database is locked to writes
3550 if ( wfReadOnly() ) {
3554 // Do nothing if not allowed to edit the watchlist
3555 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3559 // If we're working on user's talk page, we should update the talk page message indicator
3560 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3561 if ( !Hooks
::run( 'UserClearNewTalkNotification', [ &$this, $oldid ] ) ) {
3565 // Try to update the DB post-send and only if needed...
3566 DeferredUpdates
::addCallableUpdate( function() use ( $title, $oldid ) {
3567 if ( !$this->getNewtalk() ) {
3568 return; // no notifications to clear
3571 // Delete the last notifications (they stack up)
3572 $this->setNewtalk( false );
3574 // If there is a new, unseen, revision, use its timestamp
3576 ?
$title->getNextRevisionID( $oldid, Title
::GAID_FOR_UPDATE
)
3579 $this->setNewtalk( true, Revision
::newFromId( $nextid ) );
3584 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3588 if ( $this->isAnon() ) {
3589 // Nothing else to do...
3593 // Only update the timestamp if the page is being watched.
3594 // The query to find out if it is watched is cached both in memcached and per-invocation,
3595 // and when it does have to be executed, it can be on a slave
3596 // If this is the user's newtalk page, we always update the timestamp
3598 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3602 WatchedItemStore
::getDefaultInstance()
3603 ->resetNotificationTimestamp( $this, $title, $force, $oldid );
3607 * Resets all of the given user's page-change notification timestamps.
3608 * If e-notif e-mails are on, they will receive notification mails on
3609 * the next change of any watched page.
3610 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3612 public function clearAllNotifications() {
3613 if ( wfReadOnly() ) {
3617 // Do nothing if not allowed to edit the watchlist
3618 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3622 global $wgUseEnotif, $wgShowUpdatedMarker;
3623 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3624 $this->setNewtalk( false );
3627 $id = $this->getId();
3629 $dbw = wfGetDB( DB_MASTER
);
3630 $dbw->update( 'watchlist',
3631 [ /* SET */ 'wl_notificationtimestamp' => null ],
3632 [ /* WHERE */ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ],
3635 // We also need to clear here the "you have new message" notification for the own user_talk page;
3636 // it's cleared one page view later in WikiPage::doViewUpdates().
3641 * Set a cookie on the user's client. Wrapper for
3642 * WebResponse::setCookie
3643 * @deprecated since 1.27
3644 * @param string $name Name of the cookie to set
3645 * @param string $value Value to set
3646 * @param int $exp Expiration time, as a UNIX time value;
3647 * if 0 or not specified, use the default $wgCookieExpiration
3648 * @param bool $secure
3649 * true: Force setting the secure attribute when setting the cookie
3650 * false: Force NOT setting the secure attribute when setting the cookie
3651 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3652 * @param array $params Array of options sent passed to WebResponse::setcookie()
3653 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3656 protected function setCookie(
3657 $name, $value, $exp = 0, $secure = null, $params = [], $request = null
3659 wfDeprecated( __METHOD__
, '1.27' );
3660 if ( $request === null ) {
3661 $request = $this->getRequest();
3663 $params['secure'] = $secure;
3664 $request->response()->setCookie( $name, $value, $exp, $params );
3668 * Clear a cookie on the user's client
3669 * @deprecated since 1.27
3670 * @param string $name Name of the cookie to clear
3671 * @param bool $secure
3672 * true: Force setting the secure attribute when setting the cookie
3673 * false: Force NOT setting the secure attribute when setting the cookie
3674 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3675 * @param array $params Array of options sent passed to WebResponse::setcookie()
3677 protected function clearCookie( $name, $secure = null, $params = [] ) {
3678 wfDeprecated( __METHOD__
, '1.27' );
3679 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3683 * Set an extended login cookie on the user's client. The expiry of the cookie
3684 * is controlled by the $wgExtendedLoginCookieExpiration configuration
3687 * @see User::setCookie
3689 * @deprecated since 1.27
3690 * @param string $name Name of the cookie to set
3691 * @param string $value Value to set
3692 * @param bool $secure
3693 * true: Force setting the secure attribute when setting the cookie
3694 * false: Force NOT setting the secure attribute when setting the cookie
3695 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3697 protected function setExtendedLoginCookie( $name, $value, $secure ) {
3698 global $wgExtendedLoginCookieExpiration, $wgCookieExpiration;
3700 wfDeprecated( __METHOD__
, '1.27' );
3703 $exp +
= $wgExtendedLoginCookieExpiration !== null
3704 ?
$wgExtendedLoginCookieExpiration
3705 : $wgCookieExpiration;
3707 $this->setCookie( $name, $value, $exp, $secure );
3711 * Persist this user's session (e.g. set cookies)
3713 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3715 * @param bool $secure Whether to force secure/insecure cookies or use default
3716 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3718 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3720 if ( 0 == $this->mId
) {
3724 $session = $this->getRequest()->getSession();
3725 if ( $request && $session->getRequest() !== $request ) {
3726 $session = $session->sessionWithRequest( $request );
3728 $delay = $session->delaySave();
3730 if ( !$session->getUser()->equals( $this ) ) {
3731 if ( !$session->canSetUser() ) {
3732 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3733 ->warning( __METHOD__
.
3734 ": Cannot save user \"$this\" to a user \"{$session->getUser()}\"'s immutable session"
3738 $session->setUser( $this );
3741 $session->setRememberUser( $rememberMe );
3742 if ( $secure !== null ) {
3743 $session->setForceHTTPS( $secure );
3746 $session->persist();
3748 ScopedCallback
::consume( $delay );
3752 * Log this user out.
3754 public function logout() {
3755 if ( Hooks
::run( 'UserLogout', [ &$this ] ) ) {
3761 * Clear the user's session, and reset the instance cache.
3764 public function doLogout() {
3765 $session = $this->getRequest()->getSession();
3766 if ( !$session->canSetUser() ) {
3767 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3768 ->warning( __METHOD__
. ": Cannot log out of an immutable session" );
3769 } elseif ( !$session->getUser()->equals( $this ) ) {
3770 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3771 ->warning( __METHOD__
.
3772 ": Cannot log user \"$this\" out of a user \"{$session->getUser()}\"'s session"
3774 // But we still may as well make this user object anon
3775 $this->clearInstanceCache( 'defaults' );
3777 $this->clearInstanceCache( 'defaults' );
3778 $delay = $session->delaySave();
3779 $session->unpersist(); // Clear cookies (T127436)
3780 $session->setLoggedOutTimestamp( time() );
3781 $session->setUser( new User
);
3782 $session->set( 'wsUserID', 0 ); // Other code expects this
3783 ScopedCallback
::consume( $delay );
3788 * Save this user's settings into the database.
3789 * @todo Only rarely do all these fields need to be set!
3791 public function saveSettings() {
3792 if ( wfReadOnly() ) {
3793 // @TODO: caller should deal with this instead!
3794 // This should really just be an exception.
3795 MWExceptionHandler
::logException( new DBExpectedError(
3797 "Could not update user with ID '{$this->mId}'; DB is read-only."
3803 if ( 0 == $this->mId
) {
3807 // Get a new user_touched that is higher than the old one.
3808 // This will be used for a CAS check as a last-resort safety
3809 // check against race conditions and slave lag.
3810 $oldTouched = $this->mTouched
;
3811 $newTouched = $this->newTouchedTimestamp();
3813 $dbw = wfGetDB( DB_MASTER
);
3814 $dbw->update( 'user',
3816 'user_name' => $this->mName
,
3817 'user_real_name' => $this->mRealName
,
3818 'user_email' => $this->mEmail
,
3819 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3820 'user_touched' => $dbw->timestamp( $newTouched ),
3821 'user_token' => strval( $this->mToken
),
3822 'user_email_token' => $this->mEmailToken
,
3823 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
3825 'user_id' => $this->mId
,
3826 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
3830 if ( !$dbw->affectedRows() ) {
3831 // Maybe the problem was a missed cache update; clear it to be safe
3832 $this->clearSharedCache( 'refresh' );
3833 // User was changed in the meantime or loaded with stale data
3834 $from = ( $this->queryFlagsUsed
& self
::READ_LATEST
) ?
'master' : 'slave';
3835 throw new MWException(
3836 "CAS update failed on user_touched for user ID '{$this->mId}' (read from $from);" .
3837 " the version of the user to be saved is older than the current version."
3841 $this->mTouched
= $newTouched;
3842 $this->saveOptions();
3844 Hooks
::run( 'UserSaveSettings', [ $this ] );
3845 $this->clearSharedCache();
3846 $this->getUserPage()->invalidateCache();
3850 * If only this user's username is known, and it exists, return the user ID.
3852 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
3855 public function idForName( $flags = 0 ) {
3856 $s = trim( $this->getName() );
3861 $db = ( ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
)
3862 ?
wfGetDB( DB_MASTER
)
3863 : wfGetDB( DB_SLAVE
);
3865 $options = ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
)
3866 ?
[ 'LOCK IN SHARE MODE' ]
3869 $id = $db->selectField( 'user',
3870 'user_id', [ 'user_name' => $s ], __METHOD__
, $options );
3876 * Add a user to the database, return the user object
3878 * @param string $name Username to add
3879 * @param array $params Array of Strings Non-default parameters to save to
3880 * the database as user_* fields:
3881 * - email: The user's email address.
3882 * - email_authenticated: The email authentication timestamp.
3883 * - real_name: The user's real name.
3884 * - options: An associative array of non-default options.
3885 * - token: Random authentication token. Do not set.
3886 * - registration: Registration timestamp. Do not set.
3888 * @return User|null User object, or null if the username already exists.
3890 public static function createNew( $name, $params = [] ) {
3891 foreach ( [ 'password', 'newpassword', 'newpass_time', 'password_expires' ] as $field ) {
3892 if ( isset( $params[$field] ) ) {
3893 wfDeprecated( __METHOD__
. " with param '$field'", '1.27' );
3894 unset( $params[$field] );
3900 $user->setToken(); // init token
3901 if ( isset( $params['options'] ) ) {
3902 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
3903 unset( $params['options'] );
3905 $dbw = wfGetDB( DB_MASTER
);
3906 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3908 $noPass = PasswordFactory
::newInvalidPassword()->toString();
3911 'user_id' => $seqVal,
3912 'user_name' => $name,
3913 'user_password' => $noPass,
3914 'user_newpassword' => $noPass,
3915 'user_email' => $user->mEmail
,
3916 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
3917 'user_real_name' => $user->mRealName
,
3918 'user_token' => strval( $user->mToken
),
3919 'user_registration' => $dbw->timestamp( $user->mRegistration
),
3920 'user_editcount' => 0,
3921 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
3923 foreach ( $params as $name => $value ) {
3924 $fields["user_$name"] = $value;
3926 $dbw->insert( 'user', $fields, __METHOD__
, [ 'IGNORE' ] );
3927 if ( $dbw->affectedRows() ) {
3928 $newUser = User
::newFromId( $dbw->insertId() );
3936 * Add this existing user object to the database. If the user already
3937 * exists, a fatal status object is returned, and the user object is
3938 * initialised with the data from the database.
3940 * Previously, this function generated a DB error due to a key conflict
3941 * if the user already existed. Many extension callers use this function
3942 * in code along the lines of:
3944 * $user = User::newFromName( $name );
3945 * if ( !$user->isLoggedIn() ) {
3946 * $user->addToDatabase();
3948 * // do something with $user...
3950 * However, this was vulnerable to a race condition (bug 16020). By
3951 * initialising the user object if the user exists, we aim to support this
3952 * calling sequence as far as possible.
3954 * Note that if the user exists, this function will acquire a write lock,
3955 * so it is still advisable to make the call conditional on isLoggedIn(),
3956 * and to commit the transaction after calling.
3958 * @throws MWException
3961 public function addToDatabase() {
3963 if ( !$this->mToken
) {
3964 $this->setToken(); // init token
3967 $this->mTouched
= $this->newTouchedTimestamp();
3969 $noPass = PasswordFactory
::newInvalidPassword()->toString();
3971 $dbw = wfGetDB( DB_MASTER
);
3972 $inWrite = $dbw->writesOrCallbacksPending();
3973 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3974 $dbw->insert( 'user',
3976 'user_id' => $seqVal,
3977 'user_name' => $this->mName
,
3978 'user_password' => $noPass,
3979 'user_newpassword' => $noPass,
3980 'user_email' => $this->mEmail
,
3981 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3982 'user_real_name' => $this->mRealName
,
3983 'user_token' => strval( $this->mToken
),
3984 'user_registration' => $dbw->timestamp( $this->mRegistration
),
3985 'user_editcount' => 0,
3986 'user_touched' => $dbw->timestamp( $this->mTouched
),
3990 if ( !$dbw->affectedRows() ) {
3991 // The queries below cannot happen in the same REPEATABLE-READ snapshot.
3992 // Handle this by COMMIT, if possible, or by LOCK IN SHARE MODE otherwise.
3994 // Can't commit due to pending writes that may need atomicity.
3995 // This may cause some lock contention unlike the case below.
3996 $options = [ 'LOCK IN SHARE MODE' ];
3997 $flags = self
::READ_LOCKING
;
3999 // Often, this case happens early in views before any writes when
4000 // using CentralAuth. It's should be OK to commit and break the snapshot.
4001 $dbw->commit( __METHOD__
, 'flush' );
4003 $flags = self
::READ_LATEST
;
4005 $this->mId
= $dbw->selectField( 'user', 'user_id',
4006 [ 'user_name' => $this->mName
], __METHOD__
, $options );
4009 if ( $this->loadFromDatabase( $flags ) ) {
4014 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
4015 "to insert user '{$this->mName}' row, but it was not present in select!" );
4017 return Status
::newFatal( 'userexists' );
4019 $this->mId
= $dbw->insertId();
4020 self
::$idCacheByName[$this->mName
] = $this->mId
;
4022 // Clear instance cache other than user table data, which is already accurate
4023 $this->clearInstanceCache();
4025 $this->saveOptions();
4026 return Status
::newGood();
4030 * If this user is logged-in and blocked,
4031 * block any IP address they've successfully logged in from.
4032 * @return bool A block was spread
4034 public function spreadAnyEditBlock() {
4035 if ( $this->isLoggedIn() && $this->isBlocked() ) {
4036 return $this->spreadBlock();
4043 * If this (non-anonymous) user is blocked,
4044 * block the IP address they've successfully logged in from.
4045 * @return bool A block was spread
4047 protected function spreadBlock() {
4048 wfDebug( __METHOD__
. "()\n" );
4050 if ( $this->mId
== 0 ) {
4054 $userblock = Block
::newFromTarget( $this->getName() );
4055 if ( !$userblock ) {
4059 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
4063 * Get whether the user is explicitly blocked from account creation.
4064 * @return bool|Block
4066 public function isBlockedFromCreateAccount() {
4067 $this->getBlockedStatus();
4068 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
4069 return $this->mBlock
;
4072 # bug 13611: if the IP address the user is trying to create an account from is
4073 # blocked with createaccount disabled, prevent new account creation there even
4074 # when the user is logged in
4075 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
4076 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
4078 return $this->mBlockedFromCreateAccount
instanceof Block
4079 && $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
4080 ?
$this->mBlockedFromCreateAccount
4085 * Get whether the user is blocked from using Special:Emailuser.
4088 public function isBlockedFromEmailuser() {
4089 $this->getBlockedStatus();
4090 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
4094 * Get whether the user is allowed to create an account.
4097 public function isAllowedToCreateAccount() {
4098 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
4102 * Get this user's personal page title.
4104 * @return Title User's personal page title
4106 public function getUserPage() {
4107 return Title
::makeTitle( NS_USER
, $this->getName() );
4111 * Get this user's talk page title.
4113 * @return Title User's talk page title
4115 public function getTalkPage() {
4116 $title = $this->getUserPage();
4117 return $title->getTalkPage();
4121 * Determine whether the user is a newbie. Newbies are either
4122 * anonymous IPs, or the most recently created accounts.
4125 public function isNewbie() {
4126 return !$this->isAllowed( 'autoconfirmed' );
4130 * Check to see if the given clear-text password is one of the accepted passwords
4131 * @deprecated since 1.27. AuthManager is coming.
4132 * @param string $password User password
4133 * @return bool True if the given password is correct, otherwise False
4135 public function checkPassword( $password ) {
4136 global $wgAuth, $wgLegacyEncoding;
4140 // Some passwords will give a fatal Status, which means there is
4141 // some sort of technical or security reason for this password to
4142 // be completely invalid and should never be checked (e.g., T64685)
4143 if ( !$this->checkPasswordValidity( $password )->isOK() ) {
4147 // Certain authentication plugins do NOT want to save
4148 // domain passwords in a mysql database, so we should
4149 // check this (in case $wgAuth->strict() is false).
4150 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
4152 } elseif ( $wgAuth->strict() ) {
4153 // Auth plugin doesn't allow local authentication
4155 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
4156 // Auth plugin doesn't allow local authentication for this user name
4160 $passwordFactory = new PasswordFactory();
4161 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4162 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
4163 ?
wfGetDB( DB_MASTER
)
4164 : wfGetDB( DB_SLAVE
);
4167 $mPassword = $passwordFactory->newFromCiphertext( $db->selectField(
4168 'user', 'user_password', [ 'user_id' => $this->getId() ], __METHOD__
4170 } catch ( PasswordError
$e ) {
4171 wfDebug( 'Invalid password hash found in database.' );
4172 $mPassword = PasswordFactory
::newInvalidPassword();
4175 if ( !$mPassword->equals( $password ) ) {
4176 if ( $wgLegacyEncoding ) {
4177 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
4178 // Check for this with iconv
4179 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
4180 if ( $cp1252Password === $password ||
!$mPassword->equals( $cp1252Password ) ) {
4188 if ( $passwordFactory->needsUpdate( $mPassword ) && !wfReadOnly() ) {
4189 $this->setPasswordInternal( $password );
4196 * Check if the given clear-text password matches the temporary password
4197 * sent by e-mail for password reset operations.
4199 * @deprecated since 1.27. AuthManager is coming.
4200 * @param string $plaintext
4201 * @return bool True if matches, false otherwise
4203 public function checkTemporaryPassword( $plaintext ) {
4204 global $wgNewPasswordExpiry;
4208 $passwordFactory = new PasswordFactory();
4209 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4210 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
4211 ?
wfGetDB( DB_MASTER
)
4212 : wfGetDB( DB_SLAVE
);
4214 $row = $db->selectRow(
4216 [ 'user_newpassword', 'user_newpass_time' ],
4217 [ 'user_id' => $this->getId() ],
4221 $newPassword = $passwordFactory->newFromCiphertext( $row->user_newpassword
);
4222 } catch ( PasswordError
$e ) {
4223 wfDebug( 'Invalid password hash found in database.' );
4224 $newPassword = PasswordFactory
::newInvalidPassword();
4227 if ( $newPassword->equals( $plaintext ) ) {
4228 if ( is_null( $row->user_newpass_time
) ) {
4231 $expiry = wfTimestamp( TS_UNIX
, $row->user_newpass_time
) +
$wgNewPasswordExpiry;
4232 return ( time() < $expiry );
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 MediaWiki\Session\Token The new edit token
4249 public function getEditTokenObject( $salt = '', $request = null ) {
4250 if ( $this->isAnon() ) {
4251 return new LoggedOutEditToken();
4255 $request = $this->getRequest();
4257 return $request->getSession()->getToken( $salt );
4261 * Initialize (if necessary) and return a session token value
4262 * which can be used in edit forms to show that the user's
4263 * login credentials aren't being hijacked with a foreign form
4267 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4268 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4269 * @return string The new edit token
4271 public function getEditToken( $salt = '', $request = null ) {
4272 return $this->getEditTokenObject( $salt, $request )->toString();
4276 * Get the embedded timestamp from a token.
4277 * @deprecated since 1.27, use \MediaWiki\Session\Token::getTimestamp instead.
4278 * @param string $val Input token
4281 public static function getEditTokenTimestamp( $val ) {
4282 wfDeprecated( __METHOD__
, '1.27' );
4283 return MediaWiki\Session\Token
::getTimestamp( $val );
4287 * Check given value against the token value stored in the session.
4288 * A match should confirm that the form was submitted from the
4289 * user's own login session, not a form submission from a third-party
4292 * @param string $val Input value to compare
4293 * @param string $salt Optional function-specific data for hashing
4294 * @param WebRequest|null $request Object to use or null to use $wgRequest
4295 * @param int $maxage Fail tokens older than this, in seconds
4296 * @return bool Whether the token matches
4298 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4299 return $this->getEditTokenObject( $salt, $request )->match( $val, $maxage );
4303 * Check given value against the token value stored in the session,
4304 * ignoring the suffix.
4306 * @param string $val Input value to compare
4307 * @param string $salt Optional function-specific data for hashing
4308 * @param WebRequest|null $request Object to use or null to use $wgRequest
4309 * @param int $maxage Fail tokens older than this, in seconds
4310 * @return bool Whether the token matches
4312 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4313 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . Token
::SUFFIX
;
4314 return $this->matchEditToken( $val, $salt, $request, $maxage );
4318 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4319 * mail to the user's given address.
4321 * @param string $type Message to send, either "created", "changed" or "set"
4324 public function sendConfirmationMail( $type = 'created' ) {
4326 $expiration = null; // gets passed-by-ref and defined in next line.
4327 $token = $this->confirmationToken( $expiration );
4328 $url = $this->confirmationTokenUrl( $token );
4329 $invalidateURL = $this->invalidationTokenUrl( $token );
4330 $this->saveSettings();
4332 if ( $type == 'created' ||
$type === false ) {
4333 $message = 'confirmemail_body';
4334 } elseif ( $type === true ) {
4335 $message = 'confirmemail_body_changed';
4337 // Messages: confirmemail_body_changed, confirmemail_body_set
4338 $message = 'confirmemail_body_' . $type;
4341 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4342 wfMessage( $message,
4343 $this->getRequest()->getIP(),
4346 $wgLang->userTimeAndDate( $expiration, $this ),
4348 $wgLang->userDate( $expiration, $this ),
4349 $wgLang->userTime( $expiration, $this ) )->text() );
4353 * Send an e-mail to this user's account. Does not check for
4354 * confirmed status or validity.
4356 * @param string $subject Message subject
4357 * @param string $body Message body
4358 * @param User|null $from Optional sending user; if unspecified, default
4359 * $wgPasswordSender will be used.
4360 * @param string $replyto Reply-To address
4363 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4364 global $wgPasswordSender;
4366 if ( $from instanceof User
) {
4367 $sender = MailAddress
::newFromUser( $from );
4369 $sender = new MailAddress( $wgPasswordSender,
4370 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4372 $to = MailAddress
::newFromUser( $this );
4374 return UserMailer
::send( $to, $sender, $subject, $body, [
4375 'replyTo' => $replyto,
4380 * Generate, store, and return a new e-mail confirmation code.
4381 * A hash (unsalted, since it's used as a key) is stored.
4383 * @note Call saveSettings() after calling this function to commit
4384 * this change to the database.
4386 * @param string &$expiration Accepts the expiration time
4387 * @return string New token
4389 protected function confirmationToken( &$expiration ) {
4390 global $wgUserEmailConfirmationTokenExpiry;
4392 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4393 $expiration = wfTimestamp( TS_MW
, $expires );
4395 $token = MWCryptRand
::generateHex( 32 );
4396 $hash = md5( $token );
4397 $this->mEmailToken
= $hash;
4398 $this->mEmailTokenExpires
= $expiration;
4403 * Return a URL the user can use to confirm their email address.
4404 * @param string $token Accepts the email confirmation token
4405 * @return string New token URL
4407 protected function confirmationTokenUrl( $token ) {
4408 return $this->getTokenUrl( 'ConfirmEmail', $token );
4412 * Return a URL the user can use to invalidate their email address.
4413 * @param string $token Accepts the email confirmation token
4414 * @return string New token URL
4416 protected function invalidationTokenUrl( $token ) {
4417 return $this->getTokenUrl( 'InvalidateEmail', $token );
4421 * Internal function to format the e-mail validation/invalidation URLs.
4422 * This uses a quickie hack to use the
4423 * hardcoded English names of the Special: pages, for ASCII safety.
4425 * @note Since these URLs get dropped directly into emails, using the
4426 * short English names avoids insanely long URL-encoded links, which
4427 * also sometimes can get corrupted in some browsers/mailers
4428 * (bug 6957 with Gmail and Internet Explorer).
4430 * @param string $page Special page
4431 * @param string $token Token
4432 * @return string Formatted URL
4434 protected function getTokenUrl( $page, $token ) {
4435 // Hack to bypass localization of 'Special:'
4436 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4437 return $title->getCanonicalURL();
4441 * Mark the e-mail address confirmed.
4443 * @note Call saveSettings() after calling this function to commit the change.
4447 public function confirmEmail() {
4448 // Check if it's already confirmed, so we don't touch the database
4449 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4450 if ( !$this->isEmailConfirmed() ) {
4451 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4452 Hooks
::run( 'ConfirmEmailComplete', [ $this ] );
4458 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4459 * address if it was already confirmed.
4461 * @note Call saveSettings() after calling this function to commit the change.
4462 * @return bool Returns true
4464 public function invalidateEmail() {
4466 $this->mEmailToken
= null;
4467 $this->mEmailTokenExpires
= null;
4468 $this->setEmailAuthenticationTimestamp( null );
4470 Hooks
::run( 'InvalidateEmailComplete', [ $this ] );
4475 * Set the e-mail authentication timestamp.
4476 * @param string $timestamp TS_MW timestamp
4478 public function setEmailAuthenticationTimestamp( $timestamp ) {
4480 $this->mEmailAuthenticated
= $timestamp;
4481 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
4485 * Is this user allowed to send e-mails within limits of current
4486 * site configuration?
4489 public function canSendEmail() {
4490 global $wgEnableEmail, $wgEnableUserEmail;
4491 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4494 $canSend = $this->isEmailConfirmed();
4495 Hooks
::run( 'UserCanSendEmail', [ &$this, &$canSend ] );
4500 * Is this user allowed to receive e-mails within limits of current
4501 * site configuration?
4504 public function canReceiveEmail() {
4505 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4509 * Is this user's e-mail address valid-looking and confirmed within
4510 * limits of the current site configuration?
4512 * @note If $wgEmailAuthentication is on, this may require the user to have
4513 * confirmed their address by returning a code or using a password
4514 * sent to the address from the wiki.
4518 public function isEmailConfirmed() {
4519 global $wgEmailAuthentication;
4522 if ( Hooks
::run( 'EmailConfirmed', [ &$this, &$confirmed ] ) ) {
4523 if ( $this->isAnon() ) {
4526 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4529 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4539 * Check whether there is an outstanding request for e-mail confirmation.
4542 public function isEmailConfirmationPending() {
4543 global $wgEmailAuthentication;
4544 return $wgEmailAuthentication &&
4545 !$this->isEmailConfirmed() &&
4546 $this->mEmailToken
&&
4547 $this->mEmailTokenExpires
> wfTimestamp();
4551 * Get the timestamp of account creation.
4553 * @return string|bool|null Timestamp of account creation, false for
4554 * non-existent/anonymous user accounts, or null if existing account
4555 * but information is not in database.
4557 public function getRegistration() {
4558 if ( $this->isAnon() ) {
4562 return $this->mRegistration
;
4566 * Get the timestamp of the first edit
4568 * @return string|bool Timestamp of first edit, or false for
4569 * non-existent/anonymous user accounts.
4571 public function getFirstEditTimestamp() {
4572 if ( $this->getId() == 0 ) {
4573 return false; // anons
4575 $dbr = wfGetDB( DB_SLAVE
);
4576 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4577 [ 'rev_user' => $this->getId() ],
4579 [ 'ORDER BY' => 'rev_timestamp ASC' ]
4582 return false; // no edits
4584 return wfTimestamp( TS_MW
, $time );
4588 * Get the permissions associated with a given list of groups
4590 * @param array $groups Array of Strings List of internal group names
4591 * @return array Array of Strings List of permission key names for given groups combined
4593 public static function getGroupPermissions( $groups ) {
4594 global $wgGroupPermissions, $wgRevokePermissions;
4596 // grant every granted permission first
4597 foreach ( $groups as $group ) {
4598 if ( isset( $wgGroupPermissions[$group] ) ) {
4599 $rights = array_merge( $rights,
4600 // array_filter removes empty items
4601 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4604 // now revoke the revoked permissions
4605 foreach ( $groups as $group ) {
4606 if ( isset( $wgRevokePermissions[$group] ) ) {
4607 $rights = array_diff( $rights,
4608 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4611 return array_unique( $rights );
4615 * Get all the groups who have a given permission
4617 * @param string $role Role to check
4618 * @return array Array of Strings List of internal group names with the given permission
4620 public static function getGroupsWithPermission( $role ) {
4621 global $wgGroupPermissions;
4622 $allowedGroups = [];
4623 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4624 if ( self
::groupHasPermission( $group, $role ) ) {
4625 $allowedGroups[] = $group;
4628 return $allowedGroups;
4632 * Check, if the given group has the given permission
4634 * If you're wanting to check whether all users have a permission, use
4635 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4639 * @param string $group Group to check
4640 * @param string $role Role to check
4643 public static function groupHasPermission( $group, $role ) {
4644 global $wgGroupPermissions, $wgRevokePermissions;
4645 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4646 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4650 * Check if all users may be assumed to have the given permission
4652 * We generally assume so if the right is granted to '*' and isn't revoked
4653 * on any group. It doesn't attempt to take grants or other extension
4654 * limitations on rights into account in the general case, though, as that
4655 * would require it to always return false and defeat the purpose.
4656 * Specifically, session-based rights restrictions (such as OAuth or bot
4657 * passwords) are applied based on the current session.
4660 * @param string $right Right to check
4663 public static function isEveryoneAllowed( $right ) {
4664 global $wgGroupPermissions, $wgRevokePermissions;
4667 // Use the cached results, except in unit tests which rely on
4668 // being able change the permission mid-request
4669 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4670 return $cache[$right];
4673 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4674 $cache[$right] = false;
4678 // If it's revoked anywhere, then everyone doesn't have it
4679 foreach ( $wgRevokePermissions as $rights ) {
4680 if ( isset( $rights[$right] ) && $rights[$right] ) {
4681 $cache[$right] = false;
4686 // Remove any rights that aren't allowed to the global-session user,
4687 // unless there are no sessions for this endpoint.
4688 if ( !defined( 'MW_NO_SESSION' ) ) {
4689 $allowedRights = SessionManager
::getGlobalSession()->getAllowedUserRights();
4690 if ( $allowedRights !== null && !in_array( $right, $allowedRights, true ) ) {
4691 $cache[$right] = false;
4696 // Allow extensions to say false
4697 if ( !Hooks
::run( 'UserIsEveryoneAllowed', [ $right ] ) ) {
4698 $cache[$right] = false;
4702 $cache[$right] = true;
4707 * Get the localized descriptive name for a group, if it exists
4709 * @param string $group Internal group name
4710 * @return string Localized descriptive group name
4712 public static function getGroupName( $group ) {
4713 $msg = wfMessage( "group-$group" );
4714 return $msg->isBlank() ?
$group : $msg->text();
4718 * Get the localized descriptive name for a member of a group, if it exists
4720 * @param string $group Internal group name
4721 * @param string $username Username for gender (since 1.19)
4722 * @return string Localized name for group member
4724 public static function getGroupMember( $group, $username = '#' ) {
4725 $msg = wfMessage( "group-$group-member", $username );
4726 return $msg->isBlank() ?
$group : $msg->text();
4730 * Return the set of defined explicit groups.
4731 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4732 * are not included, as they are defined automatically, not in the database.
4733 * @return array Array of internal group names
4735 public static function getAllGroups() {
4736 global $wgGroupPermissions, $wgRevokePermissions;
4738 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4739 self
::getImplicitGroups()
4744 * Get a list of all available permissions.
4745 * @return string[] Array of permission names
4747 public static function getAllRights() {
4748 if ( self
::$mAllRights === false ) {
4749 global $wgAvailableRights;
4750 if ( count( $wgAvailableRights ) ) {
4751 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
4753 self
::$mAllRights = self
::$mCoreRights;
4755 Hooks
::run( 'UserGetAllRights', [ &self
::$mAllRights ] );
4757 return self
::$mAllRights;
4761 * Get a list of implicit groups
4762 * @return array Array of Strings Array of internal group names
4764 public static function getImplicitGroups() {
4765 global $wgImplicitGroups;
4767 $groups = $wgImplicitGroups;
4768 # Deprecated, use $wgImplicitGroups instead
4769 Hooks
::run( 'UserGetImplicitGroups', [ &$groups ], '1.25' );
4775 * Get the title of a page describing a particular group
4777 * @param string $group Internal group name
4778 * @return Title|bool Title of the page if it exists, false otherwise
4780 public static function getGroupPage( $group ) {
4781 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4782 if ( $msg->exists() ) {
4783 $title = Title
::newFromText( $msg->text() );
4784 if ( is_object( $title ) ) {
4792 * Create a link to the group in HTML, if available;
4793 * else return the group name.
4795 * @param string $group Internal name of the group
4796 * @param string $text The text of the link
4797 * @return string HTML link to the group
4799 public static function makeGroupLinkHTML( $group, $text = '' ) {
4800 if ( $text == '' ) {
4801 $text = self
::getGroupName( $group );
4803 $title = self
::getGroupPage( $group );
4805 return Linker
::link( $title, htmlspecialchars( $text ) );
4807 return htmlspecialchars( $text );
4812 * Create a link to the group in Wikitext, if available;
4813 * else return the group name.
4815 * @param string $group Internal name of the group
4816 * @param string $text The text of the link
4817 * @return string Wikilink to the group
4819 public static function makeGroupLinkWiki( $group, $text = '' ) {
4820 if ( $text == '' ) {
4821 $text = self
::getGroupName( $group );
4823 $title = self
::getGroupPage( $group );
4825 $page = $title->getFullText();
4826 return "[[$page|$text]]";
4833 * Returns an array of the groups that a particular group can add/remove.
4835 * @param string $group The group to check for whether it can add/remove
4836 * @return array Array( 'add' => array( addablegroups ),
4837 * 'remove' => array( removablegroups ),
4838 * 'add-self' => array( addablegroups to self),
4839 * 'remove-self' => array( removable groups from self) )
4841 public static function changeableByGroup( $group ) {
4842 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4851 if ( empty( $wgAddGroups[$group] ) ) {
4852 // Don't add anything to $groups
4853 } elseif ( $wgAddGroups[$group] === true ) {
4854 // You get everything
4855 $groups['add'] = self
::getAllGroups();
4856 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4857 $groups['add'] = $wgAddGroups[$group];
4860 // Same thing for remove
4861 if ( empty( $wgRemoveGroups[$group] ) ) {
4863 } elseif ( $wgRemoveGroups[$group] === true ) {
4864 $groups['remove'] = self
::getAllGroups();
4865 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4866 $groups['remove'] = $wgRemoveGroups[$group];
4869 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4870 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4871 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4872 if ( is_int( $key ) ) {
4873 $wgGroupsAddToSelf['user'][] = $value;
4878 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
4879 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4880 if ( is_int( $key ) ) {
4881 $wgGroupsRemoveFromSelf['user'][] = $value;
4886 // Now figure out what groups the user can add to him/herself
4887 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4889 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4890 // No idea WHY this would be used, but it's there
4891 $groups['add-self'] = User
::getAllGroups();
4892 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4893 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4896 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4898 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4899 $groups['remove-self'] = User
::getAllGroups();
4900 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4901 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4908 * Returns an array of groups that this user can add and remove
4909 * @return array Array( 'add' => array( addablegroups ),
4910 * 'remove' => array( removablegroups ),
4911 * 'add-self' => array( addablegroups to self),
4912 * 'remove-self' => array( removable groups from self) )
4914 public function changeableGroups() {
4915 if ( $this->isAllowed( 'userrights' ) ) {
4916 // This group gives the right to modify everything (reverse-
4917 // compatibility with old "userrights lets you change
4919 // Using array_merge to make the groups reindexed
4920 $all = array_merge( User
::getAllGroups() );
4929 // Okay, it's not so simple, we will have to go through the arrays
4936 $addergroups = $this->getEffectiveGroups();
4938 foreach ( $addergroups as $addergroup ) {
4939 $groups = array_merge_recursive(
4940 $groups, $this->changeableByGroup( $addergroup )
4942 $groups['add'] = array_unique( $groups['add'] );
4943 $groups['remove'] = array_unique( $groups['remove'] );
4944 $groups['add-self'] = array_unique( $groups['add-self'] );
4945 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4951 * Deferred version of incEditCountImmediate()
4953 public function incEditCount() {
4954 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle( function() {
4955 $this->incEditCountImmediate();
4960 * Increment the user's edit-count field.
4961 * Will have no effect for anonymous users.
4964 public function incEditCountImmediate() {
4965 if ( $this->isAnon() ) {
4969 $dbw = wfGetDB( DB_MASTER
);
4970 // No rows will be "affected" if user_editcount is NULL
4973 [ 'user_editcount=user_editcount+1' ],
4974 [ 'user_id' => $this->getId(), 'user_editcount IS NOT NULL' ],
4977 // Lazy initialization check...
4978 if ( $dbw->affectedRows() == 0 ) {
4979 // Now here's a goddamn hack...
4980 $dbr = wfGetDB( DB_SLAVE
);
4981 if ( $dbr !== $dbw ) {
4982 // If we actually have a slave server, the count is
4983 // at least one behind because the current transaction
4984 // has not been committed and replicated.
4985 $this->initEditCount( 1 );
4987 // But if DB_SLAVE is selecting the master, then the
4988 // count we just read includes the revision that was
4989 // just added in the working transaction.
4990 $this->initEditCount();
4993 // Edit count in user cache too
4994 $this->invalidateCache();
4998 * Initialize user_editcount from data out of the revision table
5000 * @param int $add Edits to add to the count from the revision table
5001 * @return int Number of edits
5003 protected function initEditCount( $add = 0 ) {
5004 // Pull from a slave to be less cruel to servers
5005 // Accuracy isn't the point anyway here
5006 $dbr = wfGetDB( DB_SLAVE
);
5007 $count = (int)$dbr->selectField(
5010 [ 'rev_user' => $this->getId() ],
5013 $count = $count +
$add;
5015 $dbw = wfGetDB( DB_MASTER
);
5018 [ 'user_editcount' => $count ],
5019 [ 'user_id' => $this->getId() ],
5027 * Get the description of a given right
5029 * @param string $right Right to query
5030 * @return string Localized description of the right
5032 public static function getRightDescription( $right ) {
5033 $key = "right-$right";
5034 $msg = wfMessage( $key );
5035 return $msg->isBlank() ?
$right : $msg->text();
5039 * Make a new-style password hash
5041 * @param string $password Plain-text password
5042 * @param bool|string $salt Optional salt, may be random or the user ID.
5043 * If unspecified or false, will generate one automatically
5044 * @return string Password hash
5045 * @deprecated since 1.24, use Password class
5047 public static function crypt( $password, $salt = false ) {
5048 wfDeprecated( __METHOD__
, '1.24' );
5049 $passwordFactory = new PasswordFactory();
5050 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
5051 $hash = $passwordFactory->newFromPlaintext( $password );
5052 return $hash->toString();
5056 * Compare a password hash with a plain-text password. Requires the user
5057 * ID if there's a chance that the hash is an old-style hash.
5059 * @param string $hash Password hash
5060 * @param string $password Plain-text password to compare
5061 * @param string|bool $userId User ID for old-style password salt
5064 * @deprecated since 1.24, use Password class
5066 public static function comparePasswords( $hash, $password, $userId = false ) {
5067 wfDeprecated( __METHOD__
, '1.24' );
5069 // Check for *really* old password hashes that don't even have a type
5070 // The old hash format was just an md5 hex hash, with no type information
5071 if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) {
5072 global $wgPasswordSalt;
5073 if ( $wgPasswordSalt ) {
5074 $password = ":B:{$userId}:{$hash}";
5076 $password = ":A:{$hash}";
5080 $passwordFactory = new PasswordFactory();
5081 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
5082 $hash = $passwordFactory->newFromCiphertext( $hash );
5083 return $hash->equals( $password );
5087 * Add a newuser log entry for this user.
5088 * Before 1.19 the return value was always true.
5090 * @param string|bool $action Account creation type.
5091 * - String, one of the following values:
5092 * - 'create' for an anonymous user creating an account for himself.
5093 * This will force the action's performer to be the created user itself,
5094 * no matter the value of $wgUser
5095 * - 'create2' for a logged in user creating an account for someone else
5096 * - 'byemail' when the created user will receive its password by e-mail
5097 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
5098 * - Boolean means whether the account was created by e-mail (deprecated):
5099 * - true will be converted to 'byemail'
5100 * - false will be converted to 'create' if this object is the same as
5101 * $wgUser and to 'create2' otherwise
5103 * @param string $reason User supplied reason
5105 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
5107 public function addNewUserLogEntry( $action = false, $reason = '' ) {
5108 global $wgUser, $wgNewUserLog;
5109 if ( empty( $wgNewUserLog ) ) {
5110 return true; // disabled
5113 if ( $action === true ) {
5114 $action = 'byemail';
5115 } elseif ( $action === false ) {
5116 if ( $this->equals( $wgUser ) ) {
5119 $action = 'create2';
5123 if ( $action === 'create' ||
$action === 'autocreate' ) {
5126 $performer = $wgUser;
5129 $logEntry = new ManualLogEntry( 'newusers', $action );
5130 $logEntry->setPerformer( $performer );
5131 $logEntry->setTarget( $this->getUserPage() );
5132 $logEntry->setComment( $reason );
5133 $logEntry->setParameters( [
5134 '4::userid' => $this->getId(),
5136 $logid = $logEntry->insert();
5138 if ( $action !== 'autocreate' ) {
5139 $logEntry->publish( $logid );
5146 * Add an autocreate newuser log entry for this user
5147 * Used by things like CentralAuth and perhaps other authplugins.
5148 * Consider calling addNewUserLogEntry() directly instead.
5152 public function addNewUserLogEntryAutoCreate() {
5153 $this->addNewUserLogEntry( 'autocreate' );
5159 * Load the user options either from cache, the database or an array
5161 * @param array $data Rows for the current user out of the user_properties table
5163 protected function loadOptions( $data = null ) {
5168 if ( $this->mOptionsLoaded
) {
5172 $this->mOptions
= self
::getDefaultOptions();
5174 if ( !$this->getId() ) {
5175 // For unlogged-in users, load language/variant options from request.
5176 // There's no need to do it for logged-in users: they can set preferences,
5177 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5178 // so don't override user's choice (especially when the user chooses site default).
5179 $variant = $wgContLang->getDefaultVariant();
5180 $this->mOptions
['variant'] = $variant;
5181 $this->mOptions
['language'] = $variant;
5182 $this->mOptionsLoaded
= true;
5186 // Maybe load from the object
5187 if ( !is_null( $this->mOptionOverrides
) ) {
5188 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5189 foreach ( $this->mOptionOverrides
as $key => $value ) {
5190 $this->mOptions
[$key] = $value;
5193 if ( !is_array( $data ) ) {
5194 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5195 // Load from database
5196 $dbr = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
5197 ?
wfGetDB( DB_MASTER
)
5198 : wfGetDB( DB_SLAVE
);
5200 $res = $dbr->select(
5202 [ 'up_property', 'up_value' ],
5203 [ 'up_user' => $this->getId() ],
5207 $this->mOptionOverrides
= [];
5209 foreach ( $res as $row ) {
5210 $data[$row->up_property
] = $row->up_value
;
5213 foreach ( $data as $property => $value ) {
5214 $this->mOptionOverrides
[$property] = $value;
5215 $this->mOptions
[$property] = $value;
5219 $this->mOptionsLoaded
= true;
5221 Hooks
::run( 'UserLoadOptions', [ $this, &$this->mOptions
] );
5225 * Saves the non-default options for this user, as previously set e.g. via
5226 * setOption(), in the database's "user_properties" (preferences) table.
5227 * Usually used via saveSettings().
5229 protected function saveOptions() {
5230 $this->loadOptions();
5232 // Not using getOptions(), to keep hidden preferences in database
5233 $saveOptions = $this->mOptions
;
5235 // Allow hooks to abort, for instance to save to a global profile.
5236 // Reset options to default state before saving.
5237 if ( !Hooks
::run( 'UserSaveOptions', [ $this, &$saveOptions ] ) ) {
5241 $userId = $this->getId();
5243 $insert_rows = []; // all the new preference rows
5244 foreach ( $saveOptions as $key => $value ) {
5245 // Don't bother storing default values
5246 $defaultOption = self
::getDefaultOption( $key );
5247 if ( ( $defaultOption === null && $value !== false && $value !== null )
5248 ||
$value != $defaultOption
5251 'up_user' => $userId,
5252 'up_property' => $key,
5253 'up_value' => $value,
5258 $dbw = wfGetDB( DB_MASTER
);
5260 $res = $dbw->select( 'user_properties',
5261 [ 'up_property', 'up_value' ], [ 'up_user' => $userId ], __METHOD__
);
5263 // Find prior rows that need to be removed or updated. These rows will
5264 // all be deleted (the later so that INSERT IGNORE applies the new values).
5266 foreach ( $res as $row ) {
5267 if ( !isset( $saveOptions[$row->up_property
] )
5268 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
5270 $keysDelete[] = $row->up_property
;
5274 if ( count( $keysDelete ) ) {
5275 // Do the DELETE by PRIMARY KEY for prior rows.
5276 // In the past a very large portion of calls to this function are for setting
5277 // 'rememberpassword' for new accounts (a preference that has since been removed).
5278 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5279 // caused gap locks on [max user ID,+infinity) which caused high contention since
5280 // updates would pile up on each other as they are for higher (newer) user IDs.
5281 // It might not be necessary these days, but it shouldn't hurt either.
5282 $dbw->delete( 'user_properties',
5283 [ 'up_user' => $userId, 'up_property' => $keysDelete ], __METHOD__
);
5285 // Insert the new preference rows
5286 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, [ 'IGNORE' ] );
5290 * Lazily instantiate and return a factory object for making passwords
5292 * @deprecated since 1.27, create a PasswordFactory directly instead
5293 * @return PasswordFactory
5295 public static function getPasswordFactory() {
5296 wfDeprecated( __METHOD__
, '1.27' );
5297 $ret = new PasswordFactory();
5298 $ret->init( RequestContext
::getMain()->getConfig() );
5303 * Provide an array of HTML5 attributes to put on an input element
5304 * intended for the user to enter a new password. This may include
5305 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
5307 * Do *not* use this when asking the user to enter his current password!
5308 * Regardless of configuration, users may have invalid passwords for whatever
5309 * reason (e.g., they were set before requirements were tightened up).
5310 * Only use it when asking for a new password, like on account creation or
5313 * Obviously, you still need to do server-side checking.
5315 * NOTE: A combination of bugs in various browsers means that this function
5316 * actually just returns array() unconditionally at the moment. May as
5317 * well keep it around for when the browser bugs get fixed, though.
5319 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
5321 * @deprecated since 1.27
5322 * @return array Array of HTML attributes suitable for feeding to
5323 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
5324 * That will get confused by the boolean attribute syntax used.)
5326 public static function passwordChangeInputAttribs() {
5327 global $wgMinimalPasswordLength;
5329 if ( $wgMinimalPasswordLength == 0 ) {
5333 # Note that the pattern requirement will always be satisfied if the
5334 # input is empty, so we need required in all cases.
5336 # @todo FIXME: Bug 23769: This needs to not claim the password is required
5337 # if e-mail confirmation is being used. Since HTML5 input validation
5338 # is b0rked anyway in some browsers, just return nothing. When it's
5339 # re-enabled, fix this code to not output required for e-mail
5341 # $ret = array( 'required' );
5344 # We can't actually do this right now, because Opera 9.6 will print out
5345 # the entered password visibly in its error message! When other
5346 # browsers add support for this attribute, or Opera fixes its support,
5347 # we can add support with a version check to avoid doing this on Opera
5348 # versions where it will be a problem. Reported to Opera as
5349 # DSK-262266, but they don't have a public bug tracker for us to follow.
5351 if ( $wgMinimalPasswordLength > 1 ) {
5352 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
5353 $ret['title'] = wfMessage( 'passwordtooshort' )
5354 ->numParams( $wgMinimalPasswordLength )->text();
5362 * Return the list of user fields that should be selected to create
5363 * a new user object.
5366 public static function selectFields() {
5374 'user_email_authenticated',
5376 'user_email_token_expires',
5377 'user_registration',
5383 * Factory function for fatal permission-denied errors
5386 * @param string $permission User right required
5389 static function newFatalPermissionDeniedStatus( $permission ) {
5392 $groups = array_map(
5393 [ 'User', 'makeGroupLinkWiki' ],
5394 User
::getGroupsWithPermission( $permission )
5398 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5400 return Status
::newFatal( 'badaccess-group0' );
5405 * Get a new instance of this user that was loaded from the master via a locking read
5407 * Use this instead of the main context User when updating that user. This avoids races
5408 * where that user was loaded from a slave or even the master but without proper locks.
5410 * @return User|null Returns null if the user was not found in the DB
5413 public function getInstanceForUpdate() {
5414 if ( !$this->getId() ) {
5415 return null; // anon
5418 $user = self
::newFromId( $this->getId() );
5419 if ( !$user->loadFromId( self
::READ_EXCLUSIVE
) ) {
5427 * Checks if two user objects point to the same user.
5433 public function equals( User
$user ) {
5434 return $this->getName() === $user->getName();