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
;
26 * String Some punctuation to prevent editing from broken text-mangling proxies.
27 * @deprecated since 1.27, use \\MediaWiki\\Session\\Token::SUFFIX
30 define( 'EDIT_TOKEN_SUFFIX', MediaWiki\Session\Token
::SUFFIX
);
33 * The User object encapsulates all of the user-specific settings (user_id,
34 * name, rights, email address, options, last login time). Client
35 * classes use the getXXX() functions to access these fields. These functions
36 * do all the work of determining whether the user is logged in,
37 * whether the requested option can be satisfied from cookies or
38 * whether a database query is needed. Most of the settings needed
39 * for rendering normal pages are set in the cookie to minimize use
42 class User
implements IDBAccessObject
{
44 * @const int Number of characters in user_token field.
46 const TOKEN_LENGTH
= 32;
49 * @const string An invalid value for user_token
51 const INVALID_TOKEN
= '*** INVALID ***';
54 * Global constant made accessible as class constants so that autoloader
56 * @deprecated since 1.27, use \\MediaWiki\\Session\\Token::SUFFIX
58 const EDIT_TOKEN_SUFFIX
= EDIT_TOKEN_SUFFIX
;
61 * @const int Serialized record version.
66 * Maximum items in $mWatchedItems
68 const MAX_WATCHED_ITEMS_CACHE
= 100;
71 * Exclude user options that are set to their default value.
74 const GETOPTIONS_EXCLUDE_DEFAULTS
= 1;
77 * Array of Strings List of member variables which are saved to the
78 * shared cache (memcached). Any operation which changes the
79 * corresponding database fields must call a cache-clearing function.
82 protected static $mCacheVars = [
90 'mEmailAuthenticated',
97 // user_properties table
102 * Array of Strings Core rights.
103 * Each of these should have a corresponding message of the form
107 protected static $mCoreRights = [
137 'editusercssjs', # deprecated
150 'move-categorypages',
151 'move-rootuserpages',
155 'override-export-depth',
178 'userrights-interwiki',
186 * String Cached results of getAllRights()
188 protected static $mAllRights = false;
191 * An in-process cache for user data lookup
194 protected static $inProcessCache;
196 /** Cache variables */
206 /** @var string TS_MW timestamp from the DB */
208 /** @var string TS_MW timestamp from cache */
209 protected $mQuickTouched;
213 public $mEmailAuthenticated;
215 protected $mEmailToken;
217 protected $mEmailTokenExpires;
219 protected $mRegistration;
221 protected $mEditCount;
225 protected $mOptionOverrides;
229 * Bool Whether the cache variables have been loaded.
232 public $mOptionsLoaded;
235 * Array with already loaded items or true if all items have been loaded.
237 protected $mLoadedItems = [];
241 * String Initialization data source if mLoadedItems!==true. May be one of:
242 * - 'defaults' anonymous user initialised from class defaults
243 * - 'name' initialise from mName
244 * - 'id' initialise from mId
245 * - 'session' log in from session if possible
247 * Use the User::newFrom*() family of functions to set this.
252 * Lazy-initialized variables, invalidated with clearInstanceCache
256 protected $mDatePreference;
264 protected $mBlockreason;
266 protected $mEffectiveGroups;
268 protected $mImplicitGroups;
270 protected $mFormerGroups;
272 protected $mBlockedGlobally;
289 protected $mAllowUsertalk;
292 private $mBlockedFromCreateAccount = false;
295 private $mWatchedItems = [];
297 /** @var integer User::READ_* constant bitfield used to load data */
298 protected $queryFlagsUsed = self
::READ_NORMAL
;
300 public static $idCacheByName = [];
303 * Lightweight constructor for an anonymous user.
304 * Use the User::newFrom* factory functions for other kinds of users.
308 * @see newFromConfirmationCode()
309 * @see newFromSession()
312 public function __construct() {
313 $this->clearInstanceCache( 'defaults' );
319 public function __toString() {
320 return $this->getName();
324 * Test if it's safe to load this User object.
326 * You should typically check this before using $wgUser or
327 * RequestContext::getUser in a method that might be called before the
328 * system has been fully initialized. If the object is unsafe, you should
329 * use an anonymous user:
331 * $user = $wgUser->isSafeToLoad() ? $wgUser : new User;
337 public function isSafeToLoad() {
338 global $wgFullyInitialised;
340 // The user is safe to load if:
341 // * MW_NO_SESSION is undefined AND $wgFullyInitialised is true (safe to use session data)
342 // * mLoadedItems === true (already loaded)
343 // * mFrom !== 'session' (sessions not involved at all)
345 return ( !defined( 'MW_NO_SESSION' ) && $wgFullyInitialised ) ||
346 $this->mLoadedItems
=== true ||
$this->mFrom
!== 'session';
350 * Load the user table data for this object from the source given by mFrom.
352 * @param integer $flags User::READ_* constant bitfield
354 public function load( $flags = self
::READ_NORMAL
) {
355 global $wgFullyInitialised;
357 if ( $this->mLoadedItems
=== true ) {
361 // Set it now to avoid infinite recursion in accessors
362 $oldLoadedItems = $this->mLoadedItems
;
363 $this->mLoadedItems
= true;
364 $this->queryFlagsUsed
= $flags;
366 // If this is called too early, things are likely to break.
367 if ( !$wgFullyInitialised && $this->mFrom
=== 'session' ) {
368 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
369 ->warning( 'User::loadFromSession called before the end of Setup.php', [
370 'exception' => new Exception( 'User::loadFromSession called before the end of Setup.php' ),
372 $this->loadDefaults();
373 $this->mLoadedItems
= $oldLoadedItems;
377 switch ( $this->mFrom
) {
379 $this->loadDefaults();
382 // Make sure this thread sees its own changes
383 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
384 $flags |
= self
::READ_LATEST
;
385 $this->queryFlagsUsed
= $flags;
388 $this->mId
= self
::idFromName( $this->mName
, $flags );
390 // Nonexistent user placeholder object
391 $this->loadDefaults( $this->mName
);
393 $this->loadFromId( $flags );
397 $this->loadFromId( $flags );
400 if ( !$this->loadFromSession() ) {
401 // Loading from session failed. Load defaults.
402 $this->loadDefaults();
404 Hooks
::run( 'UserLoadAfterLoadFromSession', [ $this ] );
407 throw new UnexpectedValueException(
408 "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
413 * Load user table data, given mId has already been set.
414 * @param integer $flags User::READ_* constant bitfield
415 * @return bool False if the ID does not exist, true otherwise
417 public function loadFromId( $flags = self
::READ_NORMAL
) {
418 if ( $this->mId
== 0 ) {
419 $this->loadDefaults();
423 // Try cache (unless this needs data from the master DB).
424 // NOTE: if this thread called saveSettings(), the cache was cleared.
425 $latest = DBAccessObjectUtils
::hasFlags( $flags, self
::READ_LATEST
);
426 if ( $latest ||
!$this->loadFromCache() ) {
427 wfDebug( "User: cache miss for user {$this->mId}\n" );
428 // Load from DB (make sure this thread sees its own changes)
429 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
430 $flags |
= self
::READ_LATEST
;
432 if ( !$this->loadFromDatabase( $flags ) ) {
433 // Can't load from ID, user is anonymous
436 $this->saveToCache();
439 $this->mLoadedItems
= true;
440 $this->queryFlagsUsed
= $flags;
447 * @param string $wikiId
448 * @param integer $userId
450 public static function purge( $wikiId, $userId ) {
451 $cache = ObjectCache
::getMainWANInstance();
452 $processCache = self
::getInProcessCache();
453 $key = $cache->makeGlobalKey( 'user', 'id', $wikiId, $userId );
454 $cache->delete( $key );
455 $processCache->delete( $key );
460 * @param WANObjectCache $cache
463 protected function getCacheKey( WANObjectCache
$cache ) {
464 return $cache->makeGlobalKey( 'user', 'id', wfWikiID(), $this->mId
);
469 * @return HashBagOStuff
471 protected static function getInProcessCache() {
472 if ( !self
::$inProcessCache ) {
473 self
::$inProcessCache = new HashBagOStuff( ['maxKeys' => 10] );
475 return self
::$inProcessCache;
479 * Load user data from shared cache, given mId has already been set.
481 * @return bool false if the ID does not exist or data is invalid, true otherwise
484 protected function loadFromCache() {
485 if ( $this->mId
== 0 ) {
486 $this->loadDefaults();
490 $cache = ObjectCache
::getMainWANInstance();
491 $processCache = self
::getInProcessCache();
492 $key = $this->getCacheKey( $cache );
493 $data = $processCache->get( $key );
494 if ( !is_array( $data ) ) {
495 $data = $cache->get( $key );
496 if ( !is_array( $data ) ||
$data['mVersion'] < self
::VERSION
) {
500 $processCache->set( $key, $data );
502 wfDebug( "User: got user {$this->mId} from cache\n" );
504 // Restore from cache
505 foreach ( self
::$mCacheVars as $name ) {
506 $this->$name = $data[$name];
513 * Save user data to the shared cache
515 * This method should not be called outside the User class
517 public function saveToCache() {
520 $this->loadOptions();
522 if ( $this->isAnon() ) {
523 // Anonymous users are uncached
528 foreach ( self
::$mCacheVars as $name ) {
529 $data[$name] = $this->$name;
531 $data['mVersion'] = self
::VERSION
;
532 $opts = Database
::getCacheSetOptions( wfGetDB( DB_SLAVE
) );
534 $cache = ObjectCache
::getMainWANInstance();
535 $processCache = self
::getInProcessCache();
536 $key = $this->getCacheKey( $cache );
537 $cache->set( $key, $data, $cache::TTL_HOUR
, $opts );
538 $processCache->set( $key, $data );
541 /** @name newFrom*() static factory methods */
545 * Static factory method for creation from username.
547 * This is slightly less efficient than newFromId(), so use newFromId() if
548 * you have both an ID and a name handy.
550 * @param string $name Username, validated by Title::newFromText()
551 * @param string|bool $validate Validate username. Takes the same parameters as
552 * User::getCanonicalName(), except that true is accepted as an alias
553 * for 'valid', for BC.
555 * @return User|bool User object, or false if the username is invalid
556 * (e.g. if it contains illegal characters or is an IP address). If the
557 * username is not present in the database, the result will be a user object
558 * with a name, zero user ID and default settings.
560 public static function newFromName( $name, $validate = 'valid' ) {
561 if ( $validate === true ) {
564 $name = self
::getCanonicalName( $name, $validate );
565 if ( $name === false ) {
568 // Create unloaded user object
572 $u->setItemLoaded( 'name' );
578 * Static factory method for creation from a given user ID.
580 * @param int $id Valid user ID
581 * @return User The corresponding User object
583 public static function newFromId( $id ) {
587 $u->setItemLoaded( 'id' );
592 * Factory method to fetch whichever user has a given email confirmation code.
593 * This code is generated when an account is created or its e-mail address
596 * If the code is invalid or has expired, returns NULL.
598 * @param string $code Confirmation code
599 * @param int $flags User::READ_* bitfield
602 public static function newFromConfirmationCode( $code, $flags = 0 ) {
603 $db = ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
604 ?
wfGetDB( DB_MASTER
)
605 : wfGetDB( DB_SLAVE
);
607 $id = $db->selectField(
611 'user_email_token' => md5( $code ),
612 'user_email_token_expires > ' . $db->addQuotes( $db->timestamp() ),
616 return $id ? User
::newFromId( $id ) : null;
620 * Create a new user object using data from session. If the login
621 * credentials are invalid, the result is an anonymous user.
623 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
626 public static function newFromSession( WebRequest
$request = null ) {
628 $user->mFrom
= 'session';
629 $user->mRequest
= $request;
634 * Create a new user object from a user row.
635 * The row should have the following fields from the user table in it:
636 * - either user_name or user_id to load further data if needed (or both)
638 * - all other fields (email, etc.)
639 * It is useless to provide the remaining fields if either user_id,
640 * user_name and user_real_name are not provided because the whole row
641 * will be loaded once more from the database when accessing them.
643 * @param stdClass $row A row from the user table
644 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
647 public static function newFromRow( $row, $data = null ) {
649 $user->loadFromRow( $row, $data );
654 * Static factory method for creation of a "system" user from username.
656 * A "system" user is an account that's used to attribute logged actions
657 * taken by MediaWiki itself, as opposed to a bot or human user. Examples
658 * might include the 'Maintenance script' or 'Conversion script' accounts
659 * used by various scripts in the maintenance/ directory or accounts such
660 * as 'MediaWiki message delivery' used by the MassMessage extension.
662 * This can optionally create the user if it doesn't exist, and "steal" the
663 * account if it does exist.
665 * @param string $name Username
666 * @param array $options Options are:
667 * - validate: As for User::getCanonicalName(), default 'valid'
668 * - create: Whether to create the user if it doesn't already exist, default true
669 * - steal: Whether to reset the account's password and email if it
670 * already exists, default false
673 public static function newSystemUser( $name, $options = [] ) {
675 'validate' => 'valid',
680 $name = self
::getCanonicalName( $name, $options['validate'] );
681 if ( $name === false ) {
685 $dbw = wfGetDB( DB_MASTER
);
686 $row = $dbw->selectRow(
689 self
::selectFields(),
690 [ 'user_password', 'user_newpassword' ]
692 [ 'user_name' => $name ],
696 // No user. Create it?
697 return $options['create'] ? self
::createNew( $name ) : null;
699 $user = self
::newFromRow( $row );
701 // A user is considered to exist as a non-system user if it has a
702 // password set, or a temporary password set, or an email set, or a
703 // non-invalid token.
704 $passwordFactory = new PasswordFactory();
705 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
707 $password = $passwordFactory->newFromCiphertext( $row->user_password
);
708 } catch ( PasswordError
$e ) {
709 wfDebug( 'Invalid password hash found in database.' );
710 $password = PasswordFactory
::newInvalidPassword();
713 $newpassword = $passwordFactory->newFromCiphertext( $row->user_newpassword
);
714 } catch ( PasswordError
$e ) {
715 wfDebug( 'Invalid password hash found in database.' );
716 $newpassword = PasswordFactory
::newInvalidPassword();
718 if ( !$password instanceof InvalidPassword ||
!$newpassword instanceof InvalidPassword
719 ||
$user->mEmail ||
$user->mToken
!== self
::INVALID_TOKEN
721 // User exists. Steal it?
722 if ( !$options['steal'] ) {
726 $nopass = PasswordFactory
::newInvalidPassword()->toString();
731 'user_password' => $nopass,
732 'user_newpassword' => $nopass,
733 'user_newpass_time' => null,
735 [ 'user_id' => $user->getId() ],
738 $user->invalidateEmail();
739 $user->mToken
= self
::INVALID_TOKEN
;
740 $user->saveSettings();
741 SessionManager
::singleton()->preventSessionsForUser( $user->getName() );
750 * Get the username corresponding to a given user ID
751 * @param int $id User ID
752 * @return string|bool The corresponding username
754 public static function whoIs( $id ) {
755 return UserCache
::singleton()->getProp( $id, 'name' );
759 * Get the real name of a user given their user ID
761 * @param int $id User ID
762 * @return string|bool The corresponding user's real name
764 public static function whoIsReal( $id ) {
765 return UserCache
::singleton()->getProp( $id, 'real_name' );
769 * Get database id given a user name
770 * @param string $name Username
771 * @param integer $flags User::READ_* constant bitfield
772 * @return int|null The corresponding user's ID, or null if user is nonexistent
774 public static function idFromName( $name, $flags = self
::READ_NORMAL
) {
775 $nt = Title
::makeTitleSafe( NS_USER
, $name );
776 if ( is_null( $nt ) ) {
781 if ( !( $flags & self
::READ_LATEST
) && isset( self
::$idCacheByName[$name] ) ) {
782 return self
::$idCacheByName[$name];
785 $db = ( $flags & self
::READ_LATEST
)
786 ?
wfGetDB( DB_MASTER
)
787 : wfGetDB( DB_SLAVE
);
792 [ 'user_name' => $nt->getText() ],
796 if ( $s === false ) {
799 $result = $s->user_id
;
802 self
::$idCacheByName[$name] = $result;
804 if ( count( self
::$idCacheByName ) > 1000 ) {
805 self
::$idCacheByName = [];
812 * Reset the cache used in idFromName(). For use in tests.
814 public static function resetIdByNameCache() {
815 self
::$idCacheByName = [];
819 * Does the string match an anonymous IPv4 address?
821 * This function exists for username validation, in order to reject
822 * usernames which are similar in form to IP addresses. Strings such
823 * as 300.300.300.300 will return true because it looks like an IP
824 * address, despite not being strictly valid.
826 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
827 * address because the usemod software would "cloak" anonymous IP
828 * addresses like this, if we allowed accounts like this to be created
829 * new users could get the old edits of these anonymous users.
831 * @param string $name Name to match
834 public static function isIP( $name ) {
835 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
836 || IP
::isIPv6( $name );
840 * Is the input a valid username?
842 * Checks if the input is a valid username, we don't want an empty string,
843 * an IP address, anything that contains slashes (would mess up subpages),
844 * is longer than the maximum allowed username size or doesn't begin with
847 * @param string $name Name to match
850 public static function isValidUserName( $name ) {
851 global $wgContLang, $wgMaxNameChars;
854 || User
::isIP( $name )
855 ||
strpos( $name, '/' ) !== false
856 ||
strlen( $name ) > $wgMaxNameChars
857 ||
$name != $wgContLang->ucfirst( $name )
862 // Ensure that the name can't be misresolved as a different title,
863 // such as with extra namespace keys at the start.
864 $parsed = Title
::newFromText( $name );
865 if ( is_null( $parsed )
866 ||
$parsed->getNamespace()
867 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
871 // Check an additional blacklist of troublemaker characters.
872 // Should these be merged into the title char list?
873 $unicodeBlacklist = '/[' .
874 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
875 '\x{00a0}' . # non-breaking space
876 '\x{2000}-\x{200f}' . # various whitespace
877 '\x{2028}-\x{202f}' . # breaks and control chars
878 '\x{3000}' . # ideographic space
879 '\x{e000}-\x{f8ff}' . # private use
881 if ( preg_match( $unicodeBlacklist, $name ) ) {
889 * Usernames which fail to pass this function will be blocked
890 * from user login and new account registrations, but may be used
891 * internally by batch processes.
893 * If an account already exists in this form, login will be blocked
894 * by a failure to pass this function.
896 * @param string $name Name to match
899 public static function isUsableName( $name ) {
900 global $wgReservedUsernames;
901 // Must be a valid username, obviously ;)
902 if ( !self
::isValidUserName( $name ) ) {
906 static $reservedUsernames = false;
907 if ( !$reservedUsernames ) {
908 $reservedUsernames = $wgReservedUsernames;
909 Hooks
::run( 'UserGetReservedNames', [ &$reservedUsernames ] );
912 // Certain names may be reserved for batch processes.
913 foreach ( $reservedUsernames as $reserved ) {
914 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
915 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
917 if ( $reserved == $name ) {
925 * Usernames which fail to pass this function will be blocked
926 * from new account registrations, but may be used internally
927 * either by batch processes or by user accounts which have
928 * already been created.
930 * Additional blacklisting may be added here rather than in
931 * isValidUserName() to avoid disrupting existing accounts.
933 * @param string $name String to match
936 public static function isCreatableName( $name ) {
937 global $wgInvalidUsernameCharacters;
939 // Ensure that the username isn't longer than 235 bytes, so that
940 // (at least for the builtin skins) user javascript and css files
941 // will work. (bug 23080)
942 if ( strlen( $name ) > 235 ) {
943 wfDebugLog( 'username', __METHOD__
.
944 ": '$name' invalid due to length" );
948 // Preg yells if you try to give it an empty string
949 if ( $wgInvalidUsernameCharacters !== '' ) {
950 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
951 wfDebugLog( 'username', __METHOD__
.
952 ": '$name' invalid due to wgInvalidUsernameCharacters" );
957 return self
::isUsableName( $name );
961 * Is the input a valid password for this user?
963 * @param string $password Desired password
966 public function isValidPassword( $password ) {
967 // simple boolean wrapper for getPasswordValidity
968 return $this->getPasswordValidity( $password ) === true;
972 * Given unvalidated password input, return error message on failure.
974 * @param string $password Desired password
975 * @return bool|string|array True on success, string or array of error message on failure
977 public function getPasswordValidity( $password ) {
978 $result = $this->checkPasswordValidity( $password );
979 if ( $result->isGood() ) {
983 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
984 $messages[] = $error['message'];
986 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
987 $messages[] = $warning['message'];
989 if ( count( $messages ) === 1 ) {
997 * Check if this is a valid password for this user
999 * Create a Status object based on the password's validity.
1000 * The Status should be set to fatal if the user should not
1001 * be allowed to log in, and should have any errors that
1002 * would block changing the password.
1004 * If the return value of this is not OK, the password
1005 * should not be checked. If the return value is not Good,
1006 * the password can be checked, but the user should not be
1007 * able to set their password to this.
1009 * @param string $password Desired password
1010 * @param string $purpose one of 'login', 'create', 'reset'
1014 public function checkPasswordValidity( $password, $purpose = 'login' ) {
1015 global $wgPasswordPolicy;
1017 $upp = new UserPasswordPolicy(
1018 $wgPasswordPolicy['policies'],
1019 $wgPasswordPolicy['checks']
1022 $status = Status
::newGood();
1023 $result = false; // init $result to false for the internal checks
1025 if ( !Hooks
::run( 'isValidPassword', [ $password, &$result, $this ] ) ) {
1026 $status->error( $result );
1030 if ( $result === false ) {
1031 $status->merge( $upp->checkUserPassword( $this, $password, $purpose ) );
1033 } elseif ( $result === true ) {
1036 $status->error( $result );
1037 return $status; // the isValidPassword hook set a string $result and returned true
1042 * Given unvalidated user input, return a canonical username, or false if
1043 * the username is invalid.
1044 * @param string $name User input
1045 * @param string|bool $validate Type of validation to use:
1046 * - false No validation
1047 * - 'valid' Valid for batch processes
1048 * - 'usable' Valid for batch processes and login
1049 * - 'creatable' Valid for batch processes, login and account creation
1051 * @throws InvalidArgumentException
1052 * @return bool|string
1054 public static function getCanonicalName( $name, $validate = 'valid' ) {
1055 // Force usernames to capital
1057 $name = $wgContLang->ucfirst( $name );
1059 # Reject names containing '#'; these will be cleaned up
1060 # with title normalisation, but then it's too late to
1062 if ( strpos( $name, '#' ) !== false ) {
1066 // Clean up name according to title rules,
1067 // but only when validation is requested (bug 12654)
1068 $t = ( $validate !== false ) ?
1069 Title
::newFromText( $name ) : Title
::makeTitle( NS_USER
, $name );
1070 // Check for invalid titles
1071 if ( is_null( $t ) ) {
1075 // Reject various classes of invalid names
1077 $name = $wgAuth->getCanonicalName( $t->getText() );
1079 switch ( $validate ) {
1083 if ( !User
::isValidUserName( $name ) ) {
1088 if ( !User
::isUsableName( $name ) ) {
1093 if ( !User
::isCreatableName( $name ) ) {
1098 throw new InvalidArgumentException(
1099 'Invalid parameter value for $validate in ' . __METHOD__
);
1105 * Count the number of edits of a user
1107 * @param int $uid User ID to check
1108 * @return int The user's edit count
1110 * @deprecated since 1.21 in favour of User::getEditCount
1112 public static function edits( $uid ) {
1113 wfDeprecated( __METHOD__
, '1.21' );
1114 $user = self
::newFromId( $uid );
1115 return $user->getEditCount();
1119 * Return a random password.
1121 * @deprecated since 1.27, use PasswordFactory::generateRandomPasswordString()
1122 * @return string New random password
1124 public static function randomPassword() {
1125 global $wgMinimalPasswordLength;
1126 return PasswordFactory
::generateRandomPasswordString( $wgMinimalPasswordLength );
1130 * Set cached properties to default.
1132 * @note This no longer clears uncached lazy-initialised properties;
1133 * the constructor does that instead.
1135 * @param string|bool $name
1137 public function loadDefaults( $name = false ) {
1139 $this->mName
= $name;
1140 $this->mRealName
= '';
1142 $this->mOptionOverrides
= null;
1143 $this->mOptionsLoaded
= false;
1145 $loggedOut = $this->mRequest
&& !defined( 'MW_NO_SESSION' )
1146 ?
$this->mRequest
->getSession()->getLoggedOutTimestamp() : 0;
1147 if ( $loggedOut !== 0 ) {
1148 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1150 $this->mTouched
= '1'; # Allow any pages to be cached
1153 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1154 $this->mEmailAuthenticated
= null;
1155 $this->mEmailToken
= '';
1156 $this->mEmailTokenExpires
= null;
1157 $this->mRegistration
= wfTimestamp( TS_MW
);
1158 $this->mGroups
= [];
1160 Hooks
::run( 'UserLoadDefaults', [ $this, $name ] );
1164 * Return whether an item has been loaded.
1166 * @param string $item Item to check. Current possibilities:
1170 * @param string $all 'all' to check if the whole object has been loaded
1171 * or any other string to check if only the item is available (e.g.
1175 public function isItemLoaded( $item, $all = 'all' ) {
1176 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1177 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1181 * Set that an item has been loaded
1183 * @param string $item
1185 protected function setItemLoaded( $item ) {
1186 if ( is_array( $this->mLoadedItems
) ) {
1187 $this->mLoadedItems
[$item] = true;
1192 * Load user data from the session.
1194 * @return bool True if the user is logged in, false otherwise.
1196 private function loadFromSession() {
1199 Hooks
::run( 'UserLoadFromSession', [ $this, &$result ], '1.27' );
1200 if ( $result !== null ) {
1204 // MediaWiki\Session\Session already did the necessary authentication of the user
1205 // returned here, so just use it if applicable.
1206 $session = $this->getRequest()->getSession();
1207 $user = $session->getUser();
1208 if ( $user->isLoggedIn() ) {
1209 $this->loadFromUserObject( $user );
1210 // Other code expects these to be set in the session, so set them.
1211 $session->set( 'wsUserID', $this->getId() );
1212 $session->set( 'wsUserName', $this->getName() );
1213 $session->set( 'wsToken', $this->getToken() );
1221 * Load user and user_group data from the database.
1222 * $this->mId must be set, this is how the user is identified.
1224 * @param integer $flags User::READ_* constant bitfield
1225 * @return bool True if the user exists, false if the user is anonymous
1227 public function loadFromDatabase( $flags = self
::READ_LATEST
) {
1229 $this->mId
= intval( $this->mId
);
1232 if ( !$this->mId
) {
1233 $this->loadDefaults();
1237 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
1238 $db = wfGetDB( $index );
1240 $s = $db->selectRow(
1242 self
::selectFields(),
1243 [ 'user_id' => $this->mId
],
1248 $this->queryFlagsUsed
= $flags;
1249 Hooks
::run( 'UserLoadFromDatabase', [ $this, &$s ] );
1251 if ( $s !== false ) {
1252 // Initialise user table data
1253 $this->loadFromRow( $s );
1254 $this->mGroups
= null; // deferred
1255 $this->getEditCount(); // revalidation for nulls
1260 $this->loadDefaults();
1266 * Initialize this object from a row from the user table.
1268 * @param stdClass $row Row from the user table to load.
1269 * @param array $data Further user data to load into the object
1271 * user_groups Array with groups out of the user_groups table
1272 * user_properties Array with properties out of the user_properties table
1274 protected function loadFromRow( $row, $data = null ) {
1277 $this->mGroups
= null; // deferred
1279 if ( isset( $row->user_name
) ) {
1280 $this->mName
= $row->user_name
;
1281 $this->mFrom
= 'name';
1282 $this->setItemLoaded( 'name' );
1287 if ( isset( $row->user_real_name
) ) {
1288 $this->mRealName
= $row->user_real_name
;
1289 $this->setItemLoaded( 'realname' );
1294 if ( isset( $row->user_id
) ) {
1295 $this->mId
= intval( $row->user_id
);
1296 $this->mFrom
= 'id';
1297 $this->setItemLoaded( 'id' );
1302 if ( isset( $row->user_id
) && isset( $row->user_name
) ) {
1303 self
::$idCacheByName[$row->user_name
] = $row->user_id
;
1306 if ( isset( $row->user_editcount
) ) {
1307 $this->mEditCount
= $row->user_editcount
;
1312 if ( isset( $row->user_touched
) ) {
1313 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1318 if ( isset( $row->user_token
) ) {
1319 // The definition for the column is binary(32), so trim the NULs
1320 // that appends. The previous definition was char(32), so trim
1322 $this->mToken
= rtrim( $row->user_token
, " \0" );
1323 if ( $this->mToken
=== '' ) {
1324 $this->mToken
= null;
1330 if ( isset( $row->user_email
) ) {
1331 $this->mEmail
= $row->user_email
;
1332 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1333 $this->mEmailToken
= $row->user_email_token
;
1334 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1335 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1341 $this->mLoadedItems
= true;
1344 if ( is_array( $data ) ) {
1345 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1346 $this->mGroups
= $data['user_groups'];
1348 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1349 $this->loadOptions( $data['user_properties'] );
1355 * Load the data for this user object from another user object.
1359 protected function loadFromUserObject( $user ) {
1361 $user->loadGroups();
1362 $user->loadOptions();
1363 foreach ( self
::$mCacheVars as $var ) {
1364 $this->$var = $user->$var;
1369 * Load the groups from the database if they aren't already loaded.
1371 private function loadGroups() {
1372 if ( is_null( $this->mGroups
) ) {
1373 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
1374 ?
wfGetDB( DB_MASTER
)
1375 : wfGetDB( DB_SLAVE
);
1376 $res = $db->select( 'user_groups',
1378 [ 'ug_user' => $this->mId
],
1380 $this->mGroups
= [];
1381 foreach ( $res as $row ) {
1382 $this->mGroups
[] = $row->ug_group
;
1388 * Add the user to the group if he/she meets given criteria.
1390 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1391 * possible to remove manually via Special:UserRights. In such case it
1392 * will not be re-added automatically. The user will also not lose the
1393 * group if they no longer meet the criteria.
1395 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1397 * @return array Array of groups the user has been promoted to.
1399 * @see $wgAutopromoteOnce
1401 public function addAutopromoteOnceGroups( $event ) {
1402 global $wgAutopromoteOnceLogInRC, $wgAuth;
1404 if ( wfReadOnly() ||
!$this->getId() ) {
1408 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1409 if ( !count( $toPromote ) ) {
1413 if ( !$this->checkAndSetTouched() ) {
1414 return []; // raced out (bug T48834)
1417 $oldGroups = $this->getGroups(); // previous groups
1418 foreach ( $toPromote as $group ) {
1419 $this->addGroup( $group );
1421 // update groups in external authentication database
1422 Hooks
::run( 'UserGroupsChanged', [ $this, $toPromote, [], false, false ] );
1423 $wgAuth->updateExternalDBGroups( $this, $toPromote );
1425 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1427 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1428 $logEntry->setPerformer( $this );
1429 $logEntry->setTarget( $this->getUserPage() );
1430 $logEntry->setParameters( [
1431 '4::oldgroups' => $oldGroups,
1432 '5::newgroups' => $newGroups,
1434 $logid = $logEntry->insert();
1435 if ( $wgAutopromoteOnceLogInRC ) {
1436 $logEntry->publish( $logid );
1443 * Bump user_touched if it didn't change since this object was loaded
1445 * On success, the mTouched field is updated.
1446 * The user serialization cache is always cleared.
1448 * @return bool Whether user_touched was actually updated
1451 protected function checkAndSetTouched() {
1454 if ( !$this->mId
) {
1455 return false; // anon
1458 // Get a new user_touched that is higher than the old one
1459 $oldTouched = $this->mTouched
;
1460 $newTouched = $this->newTouchedTimestamp();
1462 $dbw = wfGetDB( DB_MASTER
);
1463 $dbw->update( 'user',
1464 [ 'user_touched' => $dbw->timestamp( $newTouched ) ],
1466 'user_id' => $this->mId
,
1467 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
1471 $success = ( $dbw->affectedRows() > 0 );
1474 $this->mTouched
= $newTouched;
1475 $this->clearSharedCache();
1477 // Clears on failure too since that is desired if the cache is stale
1478 $this->clearSharedCache( 'refresh' );
1485 * Clear various cached data stored in this object. The cache of the user table
1486 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1488 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1489 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1491 public function clearInstanceCache( $reloadFrom = false ) {
1492 $this->mNewtalk
= -1;
1493 $this->mDatePreference
= null;
1494 $this->mBlockedby
= -1; # Unset
1495 $this->mHash
= false;
1496 $this->mRights
= null;
1497 $this->mEffectiveGroups
= null;
1498 $this->mImplicitGroups
= null;
1499 $this->mGroups
= null;
1500 $this->mOptions
= null;
1501 $this->mOptionsLoaded
= false;
1502 $this->mEditCount
= null;
1504 if ( $reloadFrom ) {
1505 $this->mLoadedItems
= [];
1506 $this->mFrom
= $reloadFrom;
1511 * Combine the language default options with any site-specific options
1512 * and add the default language variants.
1514 * @return array Array of String options
1516 public static function getDefaultOptions() {
1517 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1519 static $defOpt = null;
1520 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1521 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1522 // mid-request and see that change reflected in the return value of this function.
1523 // Which is insane and would never happen during normal MW operation
1527 $defOpt = $wgDefaultUserOptions;
1528 // Default language setting
1529 $defOpt['language'] = $wgContLang->getCode();
1530 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1531 $defOpt[$langCode == $wgContLang->getCode() ?
'variant' : "variant-$langCode"] = $langCode;
1533 foreach ( SearchEngine
::searchableNamespaces() as $nsnum => $nsname ) {
1534 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1536 $defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1538 Hooks
::run( 'UserGetDefaultOptions', [ &$defOpt ] );
1544 * Get a given default option value.
1546 * @param string $opt Name of option to retrieve
1547 * @return string Default option value
1549 public static function getDefaultOption( $opt ) {
1550 $defOpts = self
::getDefaultOptions();
1551 if ( isset( $defOpts[$opt] ) ) {
1552 return $defOpts[$opt];
1559 * Get blocking information
1560 * @param bool $bFromSlave Whether to check the slave database first.
1561 * To improve performance, non-critical checks are done against slaves.
1562 * Check when actually saving should be done against master.
1564 private function getBlockedStatus( $bFromSlave = true ) {
1565 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1567 if ( -1 != $this->mBlockedby
) {
1571 wfDebug( __METHOD__
. ": checking...\n" );
1573 // Initialize data...
1574 // Otherwise something ends up stomping on $this->mBlockedby when
1575 // things get lazy-loaded later, causing false positive block hits
1576 // due to -1 !== 0. Probably session-related... Nothing should be
1577 // overwriting mBlockedby, surely?
1580 # We only need to worry about passing the IP address to the Block generator if the
1581 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1582 # know which IP address they're actually coming from
1584 if ( !$this->isAllowed( 'ipblock-exempt' ) ) {
1585 // $wgUser->getName() only works after the end of Setup.php. Until
1586 // then, assume it's a logged-out user.
1587 $globalUserName = $wgUser->isSafeToLoad()
1588 ?
$wgUser->getName()
1589 : IP
::sanitizeIP( $wgUser->getRequest()->getIP() );
1590 if ( $this->getName() === $globalUserName ) {
1591 $ip = $this->getRequest()->getIP();
1596 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1599 if ( !$block instanceof Block
&& $ip !== null && !in_array( $ip, $wgProxyWhitelist ) ) {
1601 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1603 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1604 $block->mReason
= wfMessage( 'proxyblockreason' )->text();
1605 $block->setTarget( $ip );
1606 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1608 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1609 $block->mReason
= wfMessage( 'sorbsreason' )->text();
1610 $block->setTarget( $ip );
1614 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1615 if ( !$block instanceof Block
1616 && $wgApplyIpBlocksToXff
1618 && !in_array( $ip, $wgProxyWhitelist )
1620 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1621 $xff = array_map( 'trim', explode( ',', $xff ) );
1622 $xff = array_diff( $xff, [ $ip ] );
1623 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1624 $block = Block
::chooseBlock( $xffblocks, $xff );
1625 if ( $block instanceof Block
) {
1626 # Mangle the reason to alert the user that the block
1627 # originated from matching the X-Forwarded-For header.
1628 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->text();
1632 if ( $block instanceof Block
) {
1633 wfDebug( __METHOD__
. ": Found block.\n" );
1634 $this->mBlock
= $block;
1635 $this->mBlockedby
= $block->getByName();
1636 $this->mBlockreason
= $block->mReason
;
1637 $this->mHideName
= $block->mHideName
;
1638 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1640 $this->mBlockedby
= '';
1641 $this->mHideName
= 0;
1642 $this->mAllowUsertalk
= false;
1646 Hooks
::run( 'GetBlockedStatus', [ &$this ] );
1651 * Whether the given IP is in a DNS blacklist.
1653 * @param string $ip IP to check
1654 * @param bool $checkWhitelist Whether to check the whitelist first
1655 * @return bool True if blacklisted.
1657 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1658 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1660 if ( !$wgEnableDnsBlacklist ) {
1664 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1668 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1672 * Whether the given IP is in a given DNS blacklist.
1674 * @param string $ip IP to check
1675 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1676 * @return bool True if blacklisted.
1678 public function inDnsBlacklist( $ip, $bases ) {
1681 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1682 if ( IP
::isIPv4( $ip ) ) {
1683 // Reverse IP, bug 21255
1684 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1686 foreach ( (array)$bases as $base ) {
1688 // If we have an access key, use that too (ProjectHoneypot, etc.)
1690 if ( is_array( $base ) ) {
1691 if ( count( $base ) >= 2 ) {
1692 // Access key is 1, base URL is 0
1693 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1695 $host = "$ipReversed.{$base[0]}";
1697 $basename = $base[0];
1699 $host = "$ipReversed.$base";
1703 $ipList = gethostbynamel( $host );
1706 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
1710 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
1719 * Check if an IP address is in the local proxy list
1725 public static function isLocallyBlockedProxy( $ip ) {
1726 global $wgProxyList;
1728 if ( !$wgProxyList ) {
1732 if ( !is_array( $wgProxyList ) ) {
1733 // Load from the specified file
1734 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1737 if ( !is_array( $wgProxyList ) ) {
1739 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1741 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1742 // Old-style flipped proxy list
1751 * Is this user subject to rate limiting?
1753 * @return bool True if rate limited
1755 public function isPingLimitable() {
1756 global $wgRateLimitsExcludedIPs;
1757 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1758 // No other good way currently to disable rate limits
1759 // for specific IPs. :P
1760 // But this is a crappy hack and should die.
1763 return !$this->isAllowed( 'noratelimit' );
1767 * Primitive rate limits: enforce maximum actions per time period
1768 * to put a brake on flooding.
1770 * The method generates both a generic profiling point and a per action one
1771 * (suffix being "-$action".
1773 * @note When using a shared cache like memcached, IP-address
1774 * last-hit counters will be shared across wikis.
1776 * @param string $action Action to enforce; 'edit' if unspecified
1777 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1778 * @return bool True if a rate limiter was tripped
1780 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1781 // Call the 'PingLimiter' hook
1783 if ( !Hooks
::run( 'PingLimiter', [ &$this, $action, &$result, $incrBy ] ) ) {
1787 global $wgRateLimits;
1788 if ( !isset( $wgRateLimits[$action] ) ) {
1792 // Some groups shouldn't trigger the ping limiter, ever
1793 if ( !$this->isPingLimitable() ) {
1797 $limits = $wgRateLimits[$action];
1799 $id = $this->getId();
1801 $isNewbie = $this->isNewbie();
1805 if ( isset( $limits['anon'] ) ) {
1806 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1809 // limits for logged-in users
1810 if ( isset( $limits['user'] ) ) {
1811 $userLimit = $limits['user'];
1813 // limits for newbie logged-in users
1814 if ( $isNewbie && isset( $limits['newbie'] ) ) {
1815 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1819 // limits for anons and for newbie logged-in users
1822 if ( isset( $limits['ip'] ) ) {
1823 $ip = $this->getRequest()->getIP();
1824 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1826 // subnet-based limits
1827 if ( isset( $limits['subnet'] ) ) {
1828 $ip = $this->getRequest()->getIP();
1829 $subnet = IP
::getSubnet( $ip );
1830 if ( $subnet !== false ) {
1831 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1836 // Check for group-specific permissions
1837 // If more than one group applies, use the group with the highest limit ratio (max/period)
1838 foreach ( $this->getGroups() as $group ) {
1839 if ( isset( $limits[$group] ) ) {
1840 if ( $userLimit === false
1841 ||
$limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1843 $userLimit = $limits[$group];
1848 // Set the user limit key
1849 if ( $userLimit !== false ) {
1850 list( $max, $period ) = $userLimit;
1851 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
1852 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1855 // ip-based limits for all ping-limitable users
1856 if ( isset( $limits['ip-all'] ) ) {
1857 $ip = $this->getRequest()->getIP();
1858 // ignore if user limit is more permissive
1859 if ( $isNewbie ||
$userLimit === false
1860 ||
$limits['ip-all'][0] / $limits['ip-all'][1] > $userLimit[0] / $userLimit[1] ) {
1861 $keys["mediawiki:limiter:$action:ip-all:$ip"] = $limits['ip-all'];
1865 // subnet-based limits for all ping-limitable users
1866 if ( isset( $limits['subnet-all'] ) ) {
1867 $ip = $this->getRequest()->getIP();
1868 $subnet = IP
::getSubnet( $ip );
1869 if ( $subnet !== false ) {
1870 // ignore if user limit is more permissive
1871 if ( $isNewbie ||
$userLimit === false
1872 ||
$limits['ip-all'][0] / $limits['ip-all'][1]
1873 > $userLimit[0] / $userLimit[1] ) {
1874 $keys["mediawiki:limiter:$action:subnet-all:$subnet"] = $limits['subnet-all'];
1879 $cache = ObjectCache
::getLocalClusterInstance();
1882 foreach ( $keys as $key => $limit ) {
1883 list( $max, $period ) = $limit;
1884 $summary = "(limit $max in {$period}s)";
1885 $count = $cache->get( $key );
1888 if ( $count >= $max ) {
1889 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1890 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1893 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1896 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1897 if ( $incrBy > 0 ) {
1898 $cache->add( $key, 0, intval( $period ) ); // first ping
1901 if ( $incrBy > 0 ) {
1902 $cache->incr( $key, $incrBy );
1910 * Check if user is blocked
1912 * @param bool $bFromSlave Whether to check the slave database instead of
1913 * the master. Hacked from false due to horrible probs on site.
1914 * @return bool True if blocked, false otherwise
1916 public function isBlocked( $bFromSlave = true ) {
1917 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
1921 * Get the block affecting the user, or null if the user is not blocked
1923 * @param bool $bFromSlave Whether to check the slave database instead of the master
1924 * @return Block|null
1926 public function getBlock( $bFromSlave = true ) {
1927 $this->getBlockedStatus( $bFromSlave );
1928 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
1932 * Check if user is blocked from editing a particular article
1934 * @param Title $title Title to check
1935 * @param bool $bFromSlave Whether to check the slave database instead of the master
1938 public function isBlockedFrom( $title, $bFromSlave = false ) {
1939 global $wgBlockAllowsUTEdit;
1941 $blocked = $this->isBlocked( $bFromSlave );
1942 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
1943 // If a user's name is suppressed, they cannot make edits anywhere
1944 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName()
1945 && $title->getNamespace() == NS_USER_TALK
) {
1947 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
1950 Hooks
::run( 'UserIsBlockedFrom', [ $this, $title, &$blocked, &$allowUsertalk ] );
1956 * If user is blocked, return the name of the user who placed the block
1957 * @return string Name of blocker
1959 public function blockedBy() {
1960 $this->getBlockedStatus();
1961 return $this->mBlockedby
;
1965 * If user is blocked, return the specified reason for the block
1966 * @return string Blocking reason
1968 public function blockedFor() {
1969 $this->getBlockedStatus();
1970 return $this->mBlockreason
;
1974 * If user is blocked, return the ID for the block
1975 * @return int Block ID
1977 public function getBlockId() {
1978 $this->getBlockedStatus();
1979 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
1983 * Check if user is blocked on all wikis.
1984 * Do not use for actual edit permission checks!
1985 * This is intended for quick UI checks.
1987 * @param string $ip IP address, uses current client if none given
1988 * @return bool True if blocked, false otherwise
1990 public function isBlockedGlobally( $ip = '' ) {
1991 if ( $this->mBlockedGlobally
!== null ) {
1992 return $this->mBlockedGlobally
;
1994 // User is already an IP?
1995 if ( IP
::isIPAddress( $this->getName() ) ) {
1996 $ip = $this->getName();
1998 $ip = $this->getRequest()->getIP();
2001 Hooks
::run( 'UserIsBlockedGlobally', [ &$this, $ip, &$blocked ] );
2002 $this->mBlockedGlobally
= (bool)$blocked;
2003 return $this->mBlockedGlobally
;
2007 * Check if user account is locked
2009 * @return bool True if locked, false otherwise
2011 public function isLocked() {
2012 if ( $this->mLocked
!== null ) {
2013 return $this->mLocked
;
2016 $authUser = $wgAuth->getUserInstance( $this );
2017 $this->mLocked
= (bool)$authUser->isLocked();
2018 Hooks
::run( 'UserIsLocked', [ $this, &$this->mLocked
] );
2019 return $this->mLocked
;
2023 * Check if user account is hidden
2025 * @return bool True if hidden, false otherwise
2027 public function isHidden() {
2028 if ( $this->mHideName
!== null ) {
2029 return $this->mHideName
;
2031 $this->getBlockedStatus();
2032 if ( !$this->mHideName
) {
2034 $authUser = $wgAuth->getUserInstance( $this );
2035 $this->mHideName
= (bool)$authUser->isHidden();
2036 Hooks
::run( 'UserIsHidden', [ $this, &$this->mHideName
] );
2038 return $this->mHideName
;
2042 * Get the user's ID.
2043 * @return int The user's ID; 0 if the user is anonymous or nonexistent
2045 public function getId() {
2046 if ( $this->mId
=== null && $this->mName
!== null && User
::isIP( $this->mName
) ) {
2047 // Special case, we know the user is anonymous
2049 } elseif ( !$this->isItemLoaded( 'id' ) ) {
2050 // Don't load if this was initialized from an ID
2057 * Set the user and reload all fields according to a given ID
2058 * @param int $v User ID to reload
2060 public function setId( $v ) {
2062 $this->clearInstanceCache( 'id' );
2066 * Get the user name, or the IP of an anonymous user
2067 * @return string User's name or IP address
2069 public function getName() {
2070 if ( $this->isItemLoaded( 'name', 'only' ) ) {
2071 // Special case optimisation
2072 return $this->mName
;
2075 if ( $this->mName
=== false ) {
2077 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
2079 return $this->mName
;
2084 * Set the user name.
2086 * This does not reload fields from the database according to the given
2087 * name. Rather, it is used to create a temporary "nonexistent user" for
2088 * later addition to the database. It can also be used to set the IP
2089 * address for an anonymous user to something other than the current
2092 * @note User::newFromName() has roughly the same function, when the named user
2094 * @param string $str New user name to set
2096 public function setName( $str ) {
2098 $this->mName
= $str;
2102 * Get the user's name escaped by underscores.
2103 * @return string Username escaped by underscores.
2105 public function getTitleKey() {
2106 return str_replace( ' ', '_', $this->getName() );
2110 * Check if the user has new messages.
2111 * @return bool True if the user has new messages
2113 public function getNewtalk() {
2116 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2117 if ( $this->mNewtalk
=== -1 ) {
2118 $this->mNewtalk
= false; # reset talk page status
2120 // Check memcached separately for anons, who have no
2121 // entire User object stored in there.
2122 if ( !$this->mId
) {
2123 global $wgDisableAnonTalk;
2124 if ( $wgDisableAnonTalk ) {
2125 // Anon newtalk disabled by configuration.
2126 $this->mNewtalk
= false;
2128 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
2131 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2135 return (bool)$this->mNewtalk
;
2139 * Return the data needed to construct links for new talk page message
2140 * alerts. If there are new messages, this will return an associative array
2141 * with the following data:
2142 * wiki: The database name of the wiki
2143 * link: Root-relative link to the user's talk page
2144 * rev: The last talk page revision that the user has seen or null. This
2145 * is useful for building diff links.
2146 * If there are no new messages, it returns an empty array.
2147 * @note This function was designed to accomodate multiple talk pages, but
2148 * currently only returns a single link and revision.
2151 public function getNewMessageLinks() {
2153 if ( !Hooks
::run( 'UserRetrieveNewTalks', [ &$this, &$talks ] ) ) {
2155 } elseif ( !$this->getNewtalk() ) {
2158 $utp = $this->getTalkPage();
2159 $dbr = wfGetDB( DB_SLAVE
);
2160 // Get the "last viewed rev" timestamp from the oldest message notification
2161 $timestamp = $dbr->selectField( 'user_newtalk',
2162 'MIN(user_last_timestamp)',
2163 $this->isAnon() ?
[ 'user_ip' => $this->getName() ] : [ 'user_id' => $this->getID() ],
2165 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2166 return [ [ 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ] ];
2170 * Get the revision ID for the last talk page revision viewed by the talk
2172 * @return int|null Revision ID or null
2174 public function getNewMessageRevisionId() {
2175 $newMessageRevisionId = null;
2176 $newMessageLinks = $this->getNewMessageLinks();
2177 if ( $newMessageLinks ) {
2178 // Note: getNewMessageLinks() never returns more than a single link
2179 // and it is always for the same wiki, but we double-check here in
2180 // case that changes some time in the future.
2181 if ( count( $newMessageLinks ) === 1
2182 && $newMessageLinks[0]['wiki'] === wfWikiID()
2183 && $newMessageLinks[0]['rev']
2185 /** @var Revision $newMessageRevision */
2186 $newMessageRevision = $newMessageLinks[0]['rev'];
2187 $newMessageRevisionId = $newMessageRevision->getId();
2190 return $newMessageRevisionId;
2194 * Internal uncached check for new messages
2197 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2198 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2199 * @return bool True if the user has new messages
2201 protected function checkNewtalk( $field, $id ) {
2202 $dbr = wfGetDB( DB_SLAVE
);
2204 $ok = $dbr->selectField( 'user_newtalk', $field, [ $field => $id ], __METHOD__
);
2206 return $ok !== false;
2210 * Add or update the new messages flag
2211 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2212 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2213 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2214 * @return bool True if successful, false otherwise
2216 protected function updateNewtalk( $field, $id, $curRev = null ) {
2217 // Get timestamp of the talk page revision prior to the current one
2218 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2219 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2220 // Mark the user as having new messages since this revision
2221 $dbw = wfGetDB( DB_MASTER
);
2222 $dbw->insert( 'user_newtalk',
2223 [ $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ],
2226 if ( $dbw->affectedRows() ) {
2227 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2230 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2236 * Clear the new messages flag for the given user
2237 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2238 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2239 * @return bool True if successful, false otherwise
2241 protected function deleteNewtalk( $field, $id ) {
2242 $dbw = wfGetDB( DB_MASTER
);
2243 $dbw->delete( 'user_newtalk',
2246 if ( $dbw->affectedRows() ) {
2247 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2250 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2256 * Update the 'You have new messages!' status.
2257 * @param bool $val Whether the user has new messages
2258 * @param Revision $curRev New, as yet unseen revision of the user talk
2259 * page. Ignored if null or !$val.
2261 public function setNewtalk( $val, $curRev = null ) {
2262 if ( wfReadOnly() ) {
2267 $this->mNewtalk
= $val;
2269 if ( $this->isAnon() ) {
2271 $id = $this->getName();
2274 $id = $this->getId();
2278 $changed = $this->updateNewtalk( $field, $id, $curRev );
2280 $changed = $this->deleteNewtalk( $field, $id );
2284 $this->invalidateCache();
2289 * Generate a current or new-future timestamp to be stored in the
2290 * user_touched field when we update things.
2291 * @return string Timestamp in TS_MW format
2293 private function newTouchedTimestamp() {
2294 global $wgClockSkewFudge;
2296 $time = wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2297 if ( $this->mTouched
&& $time <= $this->mTouched
) {
2298 $time = wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $this->mTouched
) +
1 );
2305 * Clear user data from memcached
2307 * Use after applying updates to the database; caller's
2308 * responsibility to update user_touched if appropriate.
2310 * Called implicitly from invalidateCache() and saveSettings().
2312 * @param string $mode Use 'refresh' to clear now; otherwise before DB commit
2314 public function clearSharedCache( $mode = 'changed' ) {
2315 if ( !$this->getId() ) {
2319 $cache = ObjectCache
::getMainWANInstance();
2320 $processCache = self
::getInProcessCache();
2321 $key = $this->getCacheKey( $cache );
2322 if ( $mode === 'refresh' ) {
2323 $cache->delete( $key, 1 );
2324 $processCache->delete( $key );
2326 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle(
2327 function() use ( $cache, $processCache, $key ) {
2328 $cache->delete( $key );
2329 $processCache->delete( $key );
2336 * Immediately touch the user data cache for this account
2338 * Calls touch() and removes account data from memcached
2340 public function invalidateCache() {
2342 $this->clearSharedCache();
2346 * Update the "touched" timestamp for the user
2348 * This is useful on various login/logout events when making sure that
2349 * a browser or proxy that has multiple tenants does not suffer cache
2350 * pollution where the new user sees the old users content. The value
2351 * of getTouched() is checked when determining 304 vs 200 responses.
2352 * Unlike invalidateCache(), this preserves the User object cache and
2353 * avoids database writes.
2357 public function touch() {
2358 $id = $this->getId();
2360 $key = wfMemcKey( 'user-quicktouched', 'id', $id );
2361 ObjectCache
::getMainWANInstance()->touchCheckKey( $key );
2362 $this->mQuickTouched
= null;
2367 * Validate the cache for this account.
2368 * @param string $timestamp A timestamp in TS_MW format
2371 public function validateCache( $timestamp ) {
2372 return ( $timestamp >= $this->getTouched() );
2376 * Get the user touched timestamp
2378 * Use this value only to validate caches via inequalities
2379 * such as in the case of HTTP If-Modified-Since response logic
2381 * @return string TS_MW Timestamp
2383 public function getTouched() {
2387 if ( $this->mQuickTouched
=== null ) {
2388 $key = wfMemcKey( 'user-quicktouched', 'id', $this->mId
);
2389 $cache = ObjectCache
::getMainWANInstance();
2391 $this->mQuickTouched
= wfTimestamp( TS_MW
, $cache->getCheckKeyTime( $key ) );
2394 return max( $this->mTouched
, $this->mQuickTouched
);
2397 return $this->mTouched
;
2401 * Get the user_touched timestamp field (time of last DB updates)
2402 * @return string TS_MW Timestamp
2405 public function getDBTouched() {
2408 return $this->mTouched
;
2412 * @deprecated Removed in 1.27.
2416 public function getPassword() {
2417 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2421 * @deprecated Removed in 1.27.
2425 public function getTemporaryPassword() {
2426 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2430 * Set the password and reset the random token.
2431 * Calls through to authentication plugin if necessary;
2432 * will have no effect if the auth plugin refuses to
2433 * pass the change through or if the legal password
2436 * As a special case, setting the password to null
2437 * wipes it, so the account cannot be logged in until
2438 * a new password is set, for instance via e-mail.
2440 * @deprecated since 1.27. AuthManager is coming.
2441 * @param string $str New password to set
2442 * @throws PasswordError On failure
2445 public function setPassword( $str ) {
2448 if ( $str !== null ) {
2449 if ( !$wgAuth->allowPasswordChange() ) {
2450 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2453 $status = $this->checkPasswordValidity( $str );
2454 if ( !$status->isGood() ) {
2455 throw new PasswordError( $status->getMessage()->text() );
2459 if ( !$wgAuth->setPassword( $this, $str ) ) {
2460 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2464 $this->setOption( 'watchlisttoken', false );
2465 $this->setPasswordInternal( $str );
2471 * Set the password and reset the random token unconditionally.
2473 * @deprecated since 1.27. AuthManager is coming.
2474 * @param string|null $str New password to set or null to set an invalid
2475 * password hash meaning that the user will not be able to log in
2476 * through the web interface.
2478 public function setInternalPassword( $str ) {
2481 if ( $wgAuth->allowSetLocalPassword() ) {
2483 $this->setOption( 'watchlisttoken', false );
2484 $this->setPasswordInternal( $str );
2489 * Actually set the password and such
2490 * @since 1.27 cannot set a password for a user not in the database
2491 * @param string|null $str New password to set or null to set an invalid
2492 * password hash meaning that the user will not be able to log in
2493 * through the web interface.
2495 private function setPasswordInternal( $str ) {
2496 $id = self
::idFromName( $this->getName(), self
::READ_LATEST
);
2498 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2501 $passwordFactory = new PasswordFactory();
2502 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
2503 $dbw = wfGetDB( DB_MASTER
);
2507 'user_password' => $passwordFactory->newFromPlaintext( $str )->toString(),
2508 'user_newpassword' => PasswordFactory
::newInvalidPassword()->toString(),
2509 'user_newpass_time' => $dbw->timestampOrNull( null ),
2517 // When the main password is changed, invalidate all bot passwords too
2518 BotPassword
::invalidateAllPasswordsForUser( $this->getName() );
2522 * Get the user's current token.
2523 * @param bool $forceCreation Force the generation of a new token if the
2524 * user doesn't have one (default=true for backwards compatibility).
2525 * @return string|null Token
2527 public function getToken( $forceCreation = true ) {
2528 global $wgAuthenticationTokenVersion;
2531 if ( !$this->mToken
&& $forceCreation ) {
2535 if ( !$this->mToken
) {
2536 // The user doesn't have a token, return null to indicate that.
2538 } elseif ( $this->mToken
=== self
::INVALID_TOKEN
) {
2539 // We return a random value here so existing token checks are very
2541 return MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2542 } elseif ( $wgAuthenticationTokenVersion === null ) {
2543 // $wgAuthenticationTokenVersion not in use, so return the raw secret
2544 return $this->mToken
;
2546 // $wgAuthenticationTokenVersion in use, so hmac it.
2547 $ret = MWCryptHash
::hmac( $wgAuthenticationTokenVersion, $this->mToken
, false );
2549 // The raw hash can be overly long. Shorten it up.
2550 $len = max( 32, self
::TOKEN_LENGTH
);
2551 if ( strlen( $ret ) < $len ) {
2552 // Should never happen, even md5 is 128 bits
2553 throw new \
UnexpectedValueException( 'Hmac returned less than 128 bits' );
2555 return substr( $ret, -$len );
2560 * Set the random token (used for persistent authentication)
2561 * Called from loadDefaults() among other places.
2563 * @param string|bool $token If specified, set the token to this value
2565 public function setToken( $token = false ) {
2567 if ( $this->mToken
=== self
::INVALID_TOKEN
) {
2568 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
2569 ->debug( __METHOD__
. ": Ignoring attempt to set token for system user \"$this\"" );
2570 } elseif ( !$token ) {
2571 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2573 $this->mToken
= $token;
2578 * Set the password for a password reminder or new account email
2580 * @deprecated since 1.27, AuthManager is coming
2581 * @param string $str New password to set or null to set an invalid
2582 * password hash meaning that the user will not be able to use it
2583 * @param bool $throttle If true, reset the throttle timestamp to the present
2585 public function setNewpassword( $str, $throttle = true ) {
2586 $id = $this->getId();
2588 throw new LogicException( 'Cannot set new password for a user that is not in the database.' );
2591 $dbw = wfGetDB( DB_MASTER
);
2593 $passwordFactory = new PasswordFactory();
2594 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
2596 'user_newpassword' => $passwordFactory->newFromPlaintext( $str )->toString(),
2599 if ( $str === null ) {
2600 $update['user_newpass_time'] = null;
2601 } elseif ( $throttle ) {
2602 $update['user_newpass_time'] = $dbw->timestamp();
2605 $dbw->update( 'user', $update, [ 'user_id' => $id ], __METHOD__
);
2609 * Has password reminder email been sent within the last
2610 * $wgPasswordReminderResendTime hours?
2613 public function isPasswordReminderThrottled() {
2614 global $wgPasswordReminderResendTime;
2616 if ( !$wgPasswordReminderResendTime ) {
2622 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
2623 ?
wfGetDB( DB_MASTER
)
2624 : wfGetDB( DB_SLAVE
);
2625 $newpassTime = $db->selectField(
2627 'user_newpass_time',
2628 [ 'user_id' => $this->getId() ],
2632 if ( $newpassTime === null ) {
2635 $expiry = wfTimestamp( TS_UNIX
, $newpassTime ) +
$wgPasswordReminderResendTime * 3600;
2636 return time() < $expiry;
2640 * Get the user's e-mail address
2641 * @return string User's email address
2643 public function getEmail() {
2645 Hooks
::run( 'UserGetEmail', [ $this, &$this->mEmail
] );
2646 return $this->mEmail
;
2650 * Get the timestamp of the user's e-mail authentication
2651 * @return string TS_MW timestamp
2653 public function getEmailAuthenticationTimestamp() {
2655 Hooks
::run( 'UserGetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
2656 return $this->mEmailAuthenticated
;
2660 * Set the user's e-mail address
2661 * @param string $str New e-mail address
2663 public function setEmail( $str ) {
2665 if ( $str == $this->mEmail
) {
2668 $this->invalidateEmail();
2669 $this->mEmail
= $str;
2670 Hooks
::run( 'UserSetEmail', [ $this, &$this->mEmail
] );
2674 * Set the user's e-mail address and a confirmation mail if needed.
2677 * @param string $str New e-mail address
2680 public function setEmailWithConfirmation( $str ) {
2681 global $wgEnableEmail, $wgEmailAuthentication;
2683 if ( !$wgEnableEmail ) {
2684 return Status
::newFatal( 'emaildisabled' );
2687 $oldaddr = $this->getEmail();
2688 if ( $str === $oldaddr ) {
2689 return Status
::newGood( true );
2692 $this->setEmail( $str );
2694 if ( $str !== '' && $wgEmailAuthentication ) {
2695 // Send a confirmation request to the new address if needed
2696 $type = $oldaddr != '' ?
'changed' : 'set';
2697 $result = $this->sendConfirmationMail( $type );
2698 if ( $result->isGood() ) {
2699 // Say to the caller that a confirmation mail has been sent
2700 $result->value
= 'eauth';
2703 $result = Status
::newGood( true );
2710 * Get the user's real name
2711 * @return string User's real name
2713 public function getRealName() {
2714 if ( !$this->isItemLoaded( 'realname' ) ) {
2718 return $this->mRealName
;
2722 * Set the user's real name
2723 * @param string $str New real name
2725 public function setRealName( $str ) {
2727 $this->mRealName
= $str;
2731 * Get the user's current setting for a given option.
2733 * @param string $oname The option to check
2734 * @param string $defaultOverride A default value returned if the option does not exist
2735 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2736 * @return string User's current value for the option
2737 * @see getBoolOption()
2738 * @see getIntOption()
2740 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2741 global $wgHiddenPrefs;
2742 $this->loadOptions();
2744 # We want 'disabled' preferences to always behave as the default value for
2745 # users, even if they have set the option explicitly in their settings (ie they
2746 # set it, and then it was disabled removing their ability to change it). But
2747 # we don't want to erase the preferences in the database in case the preference
2748 # is re-enabled again. So don't touch $mOptions, just override the returned value
2749 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2750 return self
::getDefaultOption( $oname );
2753 if ( array_key_exists( $oname, $this->mOptions
) ) {
2754 return $this->mOptions
[$oname];
2756 return $defaultOverride;
2761 * Get all user's options
2763 * @param int $flags Bitwise combination of:
2764 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2765 * to the default value. (Since 1.25)
2768 public function getOptions( $flags = 0 ) {
2769 global $wgHiddenPrefs;
2770 $this->loadOptions();
2771 $options = $this->mOptions
;
2773 # We want 'disabled' preferences to always behave as the default value for
2774 # users, even if they have set the option explicitly in their settings (ie they
2775 # set it, and then it was disabled removing their ability to change it). But
2776 # we don't want to erase the preferences in the database in case the preference
2777 # is re-enabled again. So don't touch $mOptions, just override the returned value
2778 foreach ( $wgHiddenPrefs as $pref ) {
2779 $default = self
::getDefaultOption( $pref );
2780 if ( $default !== null ) {
2781 $options[$pref] = $default;
2785 if ( $flags & self
::GETOPTIONS_EXCLUDE_DEFAULTS
) {
2786 $options = array_diff_assoc( $options, self
::getDefaultOptions() );
2793 * Get the user's current setting for a given option, as a boolean value.
2795 * @param string $oname The option to check
2796 * @return bool User's current value for the option
2799 public function getBoolOption( $oname ) {
2800 return (bool)$this->getOption( $oname );
2804 * Get the user's current setting for a given option, as an integer value.
2806 * @param string $oname The option to check
2807 * @param int $defaultOverride A default value returned if the option does not exist
2808 * @return int User's current value for the option
2811 public function getIntOption( $oname, $defaultOverride = 0 ) {
2812 $val = $this->getOption( $oname );
2814 $val = $defaultOverride;
2816 return intval( $val );
2820 * Set the given option for a user.
2822 * You need to call saveSettings() to actually write to the database.
2824 * @param string $oname The option to set
2825 * @param mixed $val New value to set
2827 public function setOption( $oname, $val ) {
2828 $this->loadOptions();
2830 // Explicitly NULL values should refer to defaults
2831 if ( is_null( $val ) ) {
2832 $val = self
::getDefaultOption( $oname );
2835 $this->mOptions
[$oname] = $val;
2839 * Get a token stored in the preferences (like the watchlist one),
2840 * resetting it if it's empty (and saving changes).
2842 * @param string $oname The option name to retrieve the token from
2843 * @return string|bool User's current value for the option, or false if this option is disabled.
2844 * @see resetTokenFromOption()
2846 * @deprecated 1.26 Applications should use the OAuth extension
2848 public function getTokenFromOption( $oname ) {
2849 global $wgHiddenPrefs;
2851 $id = $this->getId();
2852 if ( !$id ||
in_array( $oname, $wgHiddenPrefs ) ) {
2856 $token = $this->getOption( $oname );
2858 // Default to a value based on the user token to avoid space
2859 // wasted on storing tokens for all users. When this option
2860 // is set manually by the user, only then is it stored.
2861 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
2868 * Reset a token stored in the preferences (like the watchlist one).
2869 * *Does not* save user's preferences (similarly to setOption()).
2871 * @param string $oname The option name to reset the token in
2872 * @return string|bool New token value, or false if this option is disabled.
2873 * @see getTokenFromOption()
2876 public function resetTokenFromOption( $oname ) {
2877 global $wgHiddenPrefs;
2878 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2882 $token = MWCryptRand
::generateHex( 40 );
2883 $this->setOption( $oname, $token );
2888 * Return a list of the types of user options currently returned by
2889 * User::getOptionKinds().
2891 * Currently, the option kinds are:
2892 * - 'registered' - preferences which are registered in core MediaWiki or
2893 * by extensions using the UserGetDefaultOptions hook.
2894 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2895 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2896 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2897 * be used by user scripts.
2898 * - 'special' - "preferences" that are not accessible via User::getOptions
2899 * or User::setOptions.
2900 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2901 * These are usually legacy options, removed in newer versions.
2903 * The API (and possibly others) use this function to determine the possible
2904 * option types for validation purposes, so make sure to update this when a
2905 * new option kind is added.
2907 * @see User::getOptionKinds
2908 * @return array Option kinds
2910 public static function listOptionKinds() {
2913 'registered-multiselect',
2914 'registered-checkmatrix',
2922 * Return an associative array mapping preferences keys to the kind of a preference they're
2923 * used for. Different kinds are handled differently when setting or reading preferences.
2925 * See User::listOptionKinds for the list of valid option types that can be provided.
2927 * @see User::listOptionKinds
2928 * @param IContextSource $context
2929 * @param array $options Assoc. array with options keys to check as keys.
2930 * Defaults to $this->mOptions.
2931 * @return array The key => kind mapping data
2933 public function getOptionKinds( IContextSource
$context, $options = null ) {
2934 $this->loadOptions();
2935 if ( $options === null ) {
2936 $options = $this->mOptions
;
2939 $prefs = Preferences
::getPreferences( $this, $context );
2942 // Pull out the "special" options, so they don't get converted as
2943 // multiselect or checkmatrix.
2944 $specialOptions = array_fill_keys( Preferences
::getSaveBlacklist(), true );
2945 foreach ( $specialOptions as $name => $value ) {
2946 unset( $prefs[$name] );
2949 // Multiselect and checkmatrix options are stored in the database with
2950 // one key per option, each having a boolean value. Extract those keys.
2951 $multiselectOptions = [];
2952 foreach ( $prefs as $name => $info ) {
2953 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2954 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2955 $opts = HTMLFormField
::flattenOptions( $info['options'] );
2956 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2958 foreach ( $opts as $value ) {
2959 $multiselectOptions["$prefix$value"] = true;
2962 unset( $prefs[$name] );
2965 $checkmatrixOptions = [];
2966 foreach ( $prefs as $name => $info ) {
2967 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2968 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2969 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
2970 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
2971 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2973 foreach ( $columns as $column ) {
2974 foreach ( $rows as $row ) {
2975 $checkmatrixOptions["$prefix$column-$row"] = true;
2979 unset( $prefs[$name] );
2983 // $value is ignored
2984 foreach ( $options as $key => $value ) {
2985 if ( isset( $prefs[$key] ) ) {
2986 $mapping[$key] = 'registered';
2987 } elseif ( isset( $multiselectOptions[$key] ) ) {
2988 $mapping[$key] = 'registered-multiselect';
2989 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2990 $mapping[$key] = 'registered-checkmatrix';
2991 } elseif ( isset( $specialOptions[$key] ) ) {
2992 $mapping[$key] = 'special';
2993 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2994 $mapping[$key] = 'userjs';
2996 $mapping[$key] = 'unused';
3004 * Reset certain (or all) options to the site defaults
3006 * The optional parameter determines which kinds of preferences will be reset.
3007 * Supported values are everything that can be reported by getOptionKinds()
3008 * and 'all', which forces a reset of *all* preferences and overrides everything else.
3010 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
3011 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
3012 * for backwards-compatibility.
3013 * @param IContextSource|null $context Context source used when $resetKinds
3014 * does not contain 'all', passed to getOptionKinds().
3015 * Defaults to RequestContext::getMain() when null.
3017 public function resetOptions(
3018 $resetKinds = [ 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ],
3019 IContextSource
$context = null
3022 $defaultOptions = self
::getDefaultOptions();
3024 if ( !is_array( $resetKinds ) ) {
3025 $resetKinds = [ $resetKinds ];
3028 if ( in_array( 'all', $resetKinds ) ) {
3029 $newOptions = $defaultOptions;
3031 if ( $context === null ) {
3032 $context = RequestContext
::getMain();
3035 $optionKinds = $this->getOptionKinds( $context );
3036 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
3039 // Use default values for the options that should be deleted, and
3040 // copy old values for the ones that shouldn't.
3041 foreach ( $this->mOptions
as $key => $value ) {
3042 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
3043 if ( array_key_exists( $key, $defaultOptions ) ) {
3044 $newOptions[$key] = $defaultOptions[$key];
3047 $newOptions[$key] = $value;
3052 Hooks
::run( 'UserResetAllOptions', [ $this, &$newOptions, $this->mOptions
, $resetKinds ] );
3054 $this->mOptions
= $newOptions;
3055 $this->mOptionsLoaded
= true;
3059 * Get the user's preferred date format.
3060 * @return string User's preferred date format
3062 public function getDatePreference() {
3063 // Important migration for old data rows
3064 if ( is_null( $this->mDatePreference
) ) {
3066 $value = $this->getOption( 'date' );
3067 $map = $wgLang->getDatePreferenceMigrationMap();
3068 if ( isset( $map[$value] ) ) {
3069 $value = $map[$value];
3071 $this->mDatePreference
= $value;
3073 return $this->mDatePreference
;
3077 * Determine based on the wiki configuration and the user's options,
3078 * whether this user must be over HTTPS no matter what.
3082 public function requiresHTTPS() {
3083 global $wgSecureLogin;
3084 if ( !$wgSecureLogin ) {
3087 $https = $this->getBoolOption( 'prefershttps' );
3088 Hooks
::run( 'UserRequiresHTTPS', [ $this, &$https ] );
3090 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
3097 * Get the user preferred stub threshold
3101 public function getStubThreshold() {
3102 global $wgMaxArticleSize; # Maximum article size, in Kb
3103 $threshold = $this->getIntOption( 'stubthreshold' );
3104 if ( $threshold > $wgMaxArticleSize * 1024 ) {
3105 // If they have set an impossible value, disable the preference
3106 // so we can use the parser cache again.
3113 * Get the permissions this user has.
3114 * @return array Array of String permission names
3116 public function getRights() {
3117 if ( is_null( $this->mRights
) ) {
3118 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
3120 // Deny any rights denied by the user's session, unless this
3121 // endpoint has no sessions.
3122 if ( !defined( 'MW_NO_SESSION' ) ) {
3123 $allowedRights = $this->getRequest()->getSession()->getAllowedUserRights();
3124 if ( $allowedRights !== null ) {
3125 $this->mRights
= array_intersect( $this->mRights
, $allowedRights );
3129 Hooks
::run( 'UserGetRights', [ $this, &$this->mRights
] );
3130 // Force reindexation of rights when a hook has unset one of them
3131 $this->mRights
= array_values( array_unique( $this->mRights
) );
3133 return $this->mRights
;
3137 * Get the list of explicit group memberships this user has.
3138 * The implicit * and user groups are not included.
3139 * @return array Array of String internal group names
3141 public function getGroups() {
3143 $this->loadGroups();
3144 return $this->mGroups
;
3148 * Get the list of implicit group memberships this user has.
3149 * This includes all explicit groups, plus 'user' if logged in,
3150 * '*' for all accounts, and autopromoted groups
3151 * @param bool $recache Whether to avoid the cache
3152 * @return array Array of String internal group names
3154 public function getEffectiveGroups( $recache = false ) {
3155 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
3156 $this->mEffectiveGroups
= array_unique( array_merge(
3157 $this->getGroups(), // explicit groups
3158 $this->getAutomaticGroups( $recache ) // implicit groups
3160 // Hook for additional groups
3161 Hooks
::run( 'UserEffectiveGroups', [ &$this, &$this->mEffectiveGroups
] );
3162 // Force reindexation of groups when a hook has unset one of them
3163 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
3165 return $this->mEffectiveGroups
;
3169 * Get the list of implicit group memberships this user has.
3170 * This includes 'user' if logged in, '*' for all accounts,
3171 * and autopromoted groups
3172 * @param bool $recache Whether to avoid the cache
3173 * @return array Array of String internal group names
3175 public function getAutomaticGroups( $recache = false ) {
3176 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
3177 $this->mImplicitGroups
= [ '*' ];
3178 if ( $this->getId() ) {
3179 $this->mImplicitGroups
[] = 'user';
3181 $this->mImplicitGroups
= array_unique( array_merge(
3182 $this->mImplicitGroups
,
3183 Autopromote
::getAutopromoteGroups( $this )
3187 // Assure data consistency with rights/groups,
3188 // as getEffectiveGroups() depends on this function
3189 $this->mEffectiveGroups
= null;
3192 return $this->mImplicitGroups
;
3196 * Returns the groups the user has belonged to.
3198 * The user may still belong to the returned groups. Compare with getGroups().
3200 * The function will not return groups the user had belonged to before MW 1.17
3202 * @return array Names of the groups the user has belonged to.
3204 public function getFormerGroups() {
3207 if ( is_null( $this->mFormerGroups
) ) {
3208 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3209 ?
wfGetDB( DB_MASTER
)
3210 : wfGetDB( DB_SLAVE
);
3211 $res = $db->select( 'user_former_groups',
3213 [ 'ufg_user' => $this->mId
],
3215 $this->mFormerGroups
= [];
3216 foreach ( $res as $row ) {
3217 $this->mFormerGroups
[] = $row->ufg_group
;
3221 return $this->mFormerGroups
;
3225 * Get the user's edit count.
3226 * @return int|null Null for anonymous users
3228 public function getEditCount() {
3229 if ( !$this->getId() ) {
3233 if ( $this->mEditCount
=== null ) {
3234 /* Populate the count, if it has not been populated yet */
3235 $dbr = wfGetDB( DB_SLAVE
);
3236 // check if the user_editcount field has been initialized
3237 $count = $dbr->selectField(
3238 'user', 'user_editcount',
3239 [ 'user_id' => $this->mId
],
3243 if ( $count === null ) {
3244 // it has not been initialized. do so.
3245 $count = $this->initEditCount();
3247 $this->mEditCount
= $count;
3249 return (int)$this->mEditCount
;
3253 * Add the user to the given group.
3254 * This takes immediate effect.
3255 * @param string $group Name of the group to add
3258 public function addGroup( $group ) {
3261 if ( !Hooks
::run( 'UserAddGroup', [ $this, &$group ] ) ) {
3265 $dbw = wfGetDB( DB_MASTER
);
3266 if ( $this->getId() ) {
3267 $dbw->insert( 'user_groups',
3269 'ug_user' => $this->getID(),
3270 'ug_group' => $group,
3276 $this->loadGroups();
3277 $this->mGroups
[] = $group;
3278 // In case loadGroups was not called before, we now have the right twice.
3279 // Get rid of the duplicate.
3280 $this->mGroups
= array_unique( $this->mGroups
);
3282 // Refresh the groups caches, and clear the rights cache so it will be
3283 // refreshed on the next call to $this->getRights().
3284 $this->getEffectiveGroups( true );
3285 $this->mRights
= null;
3287 $this->invalidateCache();
3293 * Remove the user from the given group.
3294 * This takes immediate effect.
3295 * @param string $group Name of the group to remove
3298 public function removeGroup( $group ) {
3300 if ( !Hooks
::run( 'UserRemoveGroup', [ $this, &$group ] ) ) {
3304 $dbw = wfGetDB( DB_MASTER
);
3305 $dbw->delete( 'user_groups',
3307 'ug_user' => $this->getID(),
3308 'ug_group' => $group,
3311 // Remember that the user was in this group
3312 $dbw->insert( 'user_former_groups',
3314 'ufg_user' => $this->getID(),
3315 'ufg_group' => $group,
3321 $this->loadGroups();
3322 $this->mGroups
= array_diff( $this->mGroups
, [ $group ] );
3324 // Refresh the groups caches, and clear the rights cache so it will be
3325 // refreshed on the next call to $this->getRights().
3326 $this->getEffectiveGroups( true );
3327 $this->mRights
= null;
3329 $this->invalidateCache();
3335 * Get whether the user is logged in
3338 public function isLoggedIn() {
3339 return $this->getID() != 0;
3343 * Get whether the user is anonymous
3346 public function isAnon() {
3347 return !$this->isLoggedIn();
3351 * Check if user is allowed to access a feature / make an action
3353 * @param string ... Permissions to test
3354 * @return bool True if user is allowed to perform *any* of the given actions
3356 public function isAllowedAny() {
3357 $permissions = func_get_args();
3358 foreach ( $permissions as $permission ) {
3359 if ( $this->isAllowed( $permission ) ) {
3368 * @param string ... Permissions to test
3369 * @return bool True if the user is allowed to perform *all* of the given actions
3371 public function isAllowedAll() {
3372 $permissions = func_get_args();
3373 foreach ( $permissions as $permission ) {
3374 if ( !$this->isAllowed( $permission ) ) {
3382 * Internal mechanics of testing a permission
3383 * @param string $action
3386 public function isAllowed( $action = '' ) {
3387 if ( $action === '' ) {
3388 return true; // In the spirit of DWIM
3390 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3391 // by misconfiguration: 0 == 'foo'
3392 return in_array( $action, $this->getRights(), true );
3396 * Check whether to enable recent changes patrol features for this user
3397 * @return bool True or false
3399 public function useRCPatrol() {
3400 global $wgUseRCPatrol;
3401 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3405 * Check whether to enable new pages patrol features for this user
3406 * @return bool True or false
3408 public function useNPPatrol() {
3409 global $wgUseRCPatrol, $wgUseNPPatrol;
3411 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3412 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3417 * Check whether to enable new files patrol features for this user
3418 * @return bool True or false
3420 public function useFilePatrol() {
3421 global $wgUseRCPatrol, $wgUseFilePatrol;
3423 ( $wgUseRCPatrol ||
$wgUseFilePatrol )
3424 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3429 * Get the WebRequest object to use with this object
3431 * @return WebRequest
3433 public function getRequest() {
3434 if ( $this->mRequest
) {
3435 return $this->mRequest
;
3443 * Get a WatchedItem for this user and $title.
3445 * @since 1.22 $checkRights parameter added
3446 * @param Title $title
3447 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3448 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3449 * @return WatchedItem
3451 public function getWatchedItem( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3452 $key = $checkRights . ':' . $title->getNamespace() . ':' . $title->getDBkey();
3454 if ( isset( $this->mWatchedItems
[$key] ) ) {
3455 return $this->mWatchedItems
[$key];
3458 if ( count( $this->mWatchedItems
) >= self
::MAX_WATCHED_ITEMS_CACHE
) {
3459 $this->mWatchedItems
= [];
3462 $this->mWatchedItems
[$key] = WatchedItem
::fromUserTitle( $this, $title, $checkRights );
3463 return $this->mWatchedItems
[$key];
3467 * Check the watched status of an article.
3468 * @since 1.22 $checkRights parameter added
3469 * @param Title $title Title of the article to look at
3470 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3471 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3474 public function isWatched( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3475 return $this->getWatchedItem( $title, $checkRights )->isWatched();
3480 * @since 1.22 $checkRights parameter added
3481 * @param Title $title Title of the article to look at
3482 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3483 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3485 public function addWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3486 $this->getWatchedItem( $title, $checkRights )->addWatch();
3487 $this->invalidateCache();
3491 * Stop watching an article.
3492 * @since 1.22 $checkRights parameter added
3493 * @param Title $title Title of the article to look at
3494 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3495 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3497 public function removeWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3498 $this->getWatchedItem( $title, $checkRights )->removeWatch();
3499 $this->invalidateCache();
3503 * Clear the user's notification timestamp for the given title.
3504 * If e-notif e-mails are on, they will receive notification mails on
3505 * the next change of the page if it's watched etc.
3506 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3507 * @param Title $title Title of the article to look at
3508 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3510 public function clearNotification( &$title, $oldid = 0 ) {
3511 global $wgUseEnotif, $wgShowUpdatedMarker;
3513 // Do nothing if the database is locked to writes
3514 if ( wfReadOnly() ) {
3518 // Do nothing if not allowed to edit the watchlist
3519 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3523 // If we're working on user's talk page, we should update the talk page message indicator
3524 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3525 if ( !Hooks
::run( 'UserClearNewTalkNotification', [ &$this, $oldid ] ) ) {
3529 // Try to update the DB post-send and only if needed...
3530 DeferredUpdates
::addCallableUpdate( function() use ( $title, $oldid ) {
3531 if ( !$this->getNewtalk() ) {
3532 return; // no notifications to clear
3535 // Delete the last notifications (they stack up)
3536 $this->setNewtalk( false );
3538 // If there is a new, unseen, revision, use its timestamp
3540 ?
$title->getNextRevisionID( $oldid, Title
::GAID_FOR_UPDATE
)
3543 $this->setNewtalk( true, Revision
::newFromId( $nextid ) );
3548 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3552 if ( $this->isAnon() ) {
3553 // Nothing else to do...
3557 // Only update the timestamp if the page is being watched.
3558 // The query to find out if it is watched is cached both in memcached and per-invocation,
3559 // and when it does have to be executed, it can be on a slave
3560 // If this is the user's newtalk page, we always update the timestamp
3562 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3566 $this->getWatchedItem( $title )->resetNotificationTimestamp(
3572 * Resets all of the given user's page-change notification timestamps.
3573 * If e-notif e-mails are on, they will receive notification mails on
3574 * the next change of any watched page.
3575 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3577 public function clearAllNotifications() {
3578 if ( wfReadOnly() ) {
3582 // Do nothing if not allowed to edit the watchlist
3583 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3587 global $wgUseEnotif, $wgShowUpdatedMarker;
3588 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3589 $this->setNewtalk( false );
3592 $id = $this->getId();
3594 $dbw = wfGetDB( DB_MASTER
);
3595 $dbw->update( 'watchlist',
3596 [ /* SET */ 'wl_notificationtimestamp' => null ],
3597 [ /* WHERE */ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ],
3600 // We also need to clear here the "you have new message" notification for the own user_talk page;
3601 // it's cleared one page view later in WikiPage::doViewUpdates().
3606 * Set a cookie on the user's client. Wrapper for
3607 * WebResponse::setCookie
3608 * @deprecated since 1.27
3609 * @param string $name Name of the cookie to set
3610 * @param string $value Value to set
3611 * @param int $exp Expiration time, as a UNIX time value;
3612 * if 0 or not specified, use the default $wgCookieExpiration
3613 * @param bool $secure
3614 * true: Force setting the secure attribute when setting the cookie
3615 * false: Force NOT setting the secure attribute when setting the cookie
3616 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3617 * @param array $params Array of options sent passed to WebResponse::setcookie()
3618 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3621 protected function setCookie(
3622 $name, $value, $exp = 0, $secure = null, $params = [], $request = null
3624 wfDeprecated( __METHOD__
, '1.27' );
3625 if ( $request === null ) {
3626 $request = $this->getRequest();
3628 $params['secure'] = $secure;
3629 $request->response()->setCookie( $name, $value, $exp, $params );
3633 * Clear a cookie on the user's client
3634 * @deprecated since 1.27
3635 * @param string $name Name of the cookie to clear
3636 * @param bool $secure
3637 * true: Force setting the secure attribute when setting the cookie
3638 * false: Force NOT setting the secure attribute when setting the cookie
3639 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3640 * @param array $params Array of options sent passed to WebResponse::setcookie()
3642 protected function clearCookie( $name, $secure = null, $params = [] ) {
3643 wfDeprecated( __METHOD__
, '1.27' );
3644 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3648 * Set an extended login cookie on the user's client. The expiry of the cookie
3649 * is controlled by the $wgExtendedLoginCookieExpiration configuration
3652 * @see User::setCookie
3654 * @deprecated since 1.27
3655 * @param string $name Name of the cookie to set
3656 * @param string $value Value to set
3657 * @param bool $secure
3658 * true: Force setting the secure attribute when setting the cookie
3659 * false: Force NOT setting the secure attribute when setting the cookie
3660 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3662 protected function setExtendedLoginCookie( $name, $value, $secure ) {
3663 global $wgExtendedLoginCookieExpiration, $wgCookieExpiration;
3665 wfDeprecated( __METHOD__
, '1.27' );
3668 $exp +
= $wgExtendedLoginCookieExpiration !== null
3669 ?
$wgExtendedLoginCookieExpiration
3670 : $wgCookieExpiration;
3672 $this->setCookie( $name, $value, $exp, $secure );
3676 * Persist this user's session (e.g. set cookies)
3678 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3680 * @param bool $secure Whether to force secure/insecure cookies or use default
3681 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3683 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3685 if ( 0 == $this->mId
) {
3689 $session = $this->getRequest()->getSession();
3690 if ( $request && $session->getRequest() !== $request ) {
3691 $session = $session->sessionWithRequest( $request );
3693 $delay = $session->delaySave();
3695 if ( !$session->getUser()->equals( $this ) ) {
3696 if ( !$session->canSetUser() ) {
3697 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3698 ->warning( __METHOD__
.
3699 ": Cannot save user \"$this\" to a user \"{$session->getUser()}\"'s immutable session"
3703 $session->setUser( $this );
3706 $session->setRememberUser( $rememberMe );
3707 if ( $secure !== null ) {
3708 $session->setForceHTTPS( $secure );
3711 $session->persist();
3713 ScopedCallback
::consume( $delay );
3717 * Log this user out.
3719 public function logout() {
3720 if ( Hooks
::run( 'UserLogout', [ &$this ] ) ) {
3726 * Clear the user's session, and reset the instance cache.
3729 public function doLogout() {
3730 $session = $this->getRequest()->getSession();
3731 if ( !$session->canSetUser() ) {
3732 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3733 ->warning( __METHOD__
. ": Cannot log out of an immutable session" );
3734 } elseif ( !$session->getUser()->equals( $this ) ) {
3735 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3736 ->warning( __METHOD__
.
3737 ": Cannot log user \"$this\" out of a user \"{$session->getUser()}\"'s session"
3739 // But we still may as well make this user object anon
3740 $this->clearInstanceCache( 'defaults' );
3742 $this->clearInstanceCache( 'defaults' );
3743 $delay = $session->delaySave();
3744 $session->unpersist(); // Clear cookies (T127436)
3745 $session->setLoggedOutTimestamp( time() );
3746 $session->setUser( new User
);
3747 $session->set( 'wsUserID', 0 ); // Other code expects this
3748 ScopedCallback
::consume( $delay );
3753 * Save this user's settings into the database.
3754 * @todo Only rarely do all these fields need to be set!
3756 public function saveSettings() {
3757 if ( wfReadOnly() ) {
3758 // @TODO: caller should deal with this instead!
3759 // This should really just be an exception.
3760 MWExceptionHandler
::logException( new DBExpectedError(
3762 "Could not update user with ID '{$this->mId}'; DB is read-only."
3768 if ( 0 == $this->mId
) {
3772 // Get a new user_touched that is higher than the old one.
3773 // This will be used for a CAS check as a last-resort safety
3774 // check against race conditions and slave lag.
3775 $oldTouched = $this->mTouched
;
3776 $newTouched = $this->newTouchedTimestamp();
3778 $dbw = wfGetDB( DB_MASTER
);
3779 $dbw->update( 'user',
3781 'user_name' => $this->mName
,
3782 'user_real_name' => $this->mRealName
,
3783 'user_email' => $this->mEmail
,
3784 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3785 'user_touched' => $dbw->timestamp( $newTouched ),
3786 'user_token' => strval( $this->mToken
),
3787 'user_email_token' => $this->mEmailToken
,
3788 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
3790 'user_id' => $this->mId
,
3791 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
3795 if ( !$dbw->affectedRows() ) {
3796 // Maybe the problem was a missed cache update; clear it to be safe
3797 $this->clearSharedCache( 'refresh' );
3798 // User was changed in the meantime or loaded with stale data
3799 $from = ( $this->queryFlagsUsed
& self
::READ_LATEST
) ?
'master' : 'slave';
3800 throw new MWException(
3801 "CAS update failed on user_touched for user ID '{$this->mId}' (read from $from);" .
3802 " the version of the user to be saved is older than the current version."
3806 $this->mTouched
= $newTouched;
3807 $this->saveOptions();
3809 Hooks
::run( 'UserSaveSettings', [ $this ] );
3810 $this->clearSharedCache();
3811 $this->getUserPage()->invalidateCache();
3815 * If only this user's username is known, and it exists, return the user ID.
3817 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
3820 public function idForName( $flags = 0 ) {
3821 $s = trim( $this->getName() );
3826 $db = ( ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
)
3827 ?
wfGetDB( DB_MASTER
)
3828 : wfGetDB( DB_SLAVE
);
3830 $options = ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
)
3831 ?
[ 'LOCK IN SHARE MODE' ]
3834 $id = $db->selectField( 'user',
3835 'user_id', [ 'user_name' => $s ], __METHOD__
, $options );
3841 * Add a user to the database, return the user object
3843 * @param string $name Username to add
3844 * @param array $params Array of Strings Non-default parameters to save to
3845 * the database as user_* fields:
3846 * - email: The user's email address.
3847 * - email_authenticated: The email authentication timestamp.
3848 * - real_name: The user's real name.
3849 * - options: An associative array of non-default options.
3850 * - token: Random authentication token. Do not set.
3851 * - registration: Registration timestamp. Do not set.
3853 * @return User|null User object, or null if the username already exists.
3855 public static function createNew( $name, $params = [] ) {
3856 foreach ( [ 'password', 'newpassword', 'newpass_time', 'password_expires' ] as $field ) {
3857 if ( isset( $params[$field] ) ) {
3858 wfDeprecated( __METHOD__
. " with param '$field'", '1.27' );
3859 unset( $params[$field] );
3865 $user->setToken(); // init token
3866 if ( isset( $params['options'] ) ) {
3867 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
3868 unset( $params['options'] );
3870 $dbw = wfGetDB( DB_MASTER
);
3871 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3873 $noPass = PasswordFactory
::newInvalidPassword()->toString();
3876 'user_id' => $seqVal,
3877 'user_name' => $name,
3878 'user_password' => $noPass,
3879 'user_newpassword' => $noPass,
3880 'user_email' => $user->mEmail
,
3881 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
3882 'user_real_name' => $user->mRealName
,
3883 'user_token' => strval( $user->mToken
),
3884 'user_registration' => $dbw->timestamp( $user->mRegistration
),
3885 'user_editcount' => 0,
3886 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
3888 foreach ( $params as $name => $value ) {
3889 $fields["user_$name"] = $value;
3891 $dbw->insert( 'user', $fields, __METHOD__
, [ 'IGNORE' ] );
3892 if ( $dbw->affectedRows() ) {
3893 $newUser = User
::newFromId( $dbw->insertId() );
3901 * Add this existing user object to the database. If the user already
3902 * exists, a fatal status object is returned, and the user object is
3903 * initialised with the data from the database.
3905 * Previously, this function generated a DB error due to a key conflict
3906 * if the user already existed. Many extension callers use this function
3907 * in code along the lines of:
3909 * $user = User::newFromName( $name );
3910 * if ( !$user->isLoggedIn() ) {
3911 * $user->addToDatabase();
3913 * // do something with $user...
3915 * However, this was vulnerable to a race condition (bug 16020). By
3916 * initialising the user object if the user exists, we aim to support this
3917 * calling sequence as far as possible.
3919 * Note that if the user exists, this function will acquire a write lock,
3920 * so it is still advisable to make the call conditional on isLoggedIn(),
3921 * and to commit the transaction after calling.
3923 * @throws MWException
3926 public function addToDatabase() {
3928 if ( !$this->mToken
) {
3929 $this->setToken(); // init token
3932 $this->mTouched
= $this->newTouchedTimestamp();
3934 $noPass = PasswordFactory
::newInvalidPassword()->toString();
3936 $dbw = wfGetDB( DB_MASTER
);
3937 $inWrite = $dbw->writesOrCallbacksPending();
3938 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3939 $dbw->insert( 'user',
3941 'user_id' => $seqVal,
3942 'user_name' => $this->mName
,
3943 'user_password' => $noPass,
3944 'user_newpassword' => $noPass,
3945 'user_email' => $this->mEmail
,
3946 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3947 'user_real_name' => $this->mRealName
,
3948 'user_token' => strval( $this->mToken
),
3949 'user_registration' => $dbw->timestamp( $this->mRegistration
),
3950 'user_editcount' => 0,
3951 'user_touched' => $dbw->timestamp( $this->mTouched
),
3955 if ( !$dbw->affectedRows() ) {
3956 // The queries below cannot happen in the same REPEATABLE-READ snapshot.
3957 // Handle this by COMMIT, if possible, or by LOCK IN SHARE MODE otherwise.
3959 // Can't commit due to pending writes that may need atomicity.
3960 // This may cause some lock contention unlike the case below.
3961 $options = [ 'LOCK IN SHARE MODE' ];
3962 $flags = self
::READ_LOCKING
;
3964 // Often, this case happens early in views before any writes when
3965 // using CentralAuth. It's should be OK to commit and break the snapshot.
3966 $dbw->commit( __METHOD__
, 'flush' );
3968 $flags = self
::READ_LATEST
;
3970 $this->mId
= $dbw->selectField( 'user', 'user_id',
3971 [ 'user_name' => $this->mName
], __METHOD__
, $options );
3974 if ( $this->loadFromDatabase( $flags ) ) {
3979 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
3980 "to insert user '{$this->mName}' row, but it was not present in select!" );
3982 return Status
::newFatal( 'userexists' );
3984 $this->mId
= $dbw->insertId();
3985 self
::$idCacheByName[$this->mName
] = $this->mId
;
3987 // Clear instance cache other than user table data, which is already accurate
3988 $this->clearInstanceCache();
3990 $this->saveOptions();
3991 return Status
::newGood();
3995 * If this user is logged-in and blocked,
3996 * block any IP address they've successfully logged in from.
3997 * @return bool A block was spread
3999 public function spreadAnyEditBlock() {
4000 if ( $this->isLoggedIn() && $this->isBlocked() ) {
4001 return $this->spreadBlock();
4007 * If this (non-anonymous) user is blocked,
4008 * block the IP address they've successfully logged in from.
4009 * @return bool A block was spread
4011 protected function spreadBlock() {
4012 wfDebug( __METHOD__
. "()\n" );
4014 if ( $this->mId
== 0 ) {
4018 $userblock = Block
::newFromTarget( $this->getName() );
4019 if ( !$userblock ) {
4023 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
4027 * Get whether the user is explicitly blocked from account creation.
4028 * @return bool|Block
4030 public function isBlockedFromCreateAccount() {
4031 $this->getBlockedStatus();
4032 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
4033 return $this->mBlock
;
4036 # bug 13611: if the IP address the user is trying to create an account from is
4037 # blocked with createaccount disabled, prevent new account creation there even
4038 # when the user is logged in
4039 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
4040 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
4042 return $this->mBlockedFromCreateAccount
instanceof Block
4043 && $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
4044 ?
$this->mBlockedFromCreateAccount
4049 * Get whether the user is blocked from using Special:Emailuser.
4052 public function isBlockedFromEmailuser() {
4053 $this->getBlockedStatus();
4054 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
4058 * Get whether the user is allowed to create an account.
4061 public function isAllowedToCreateAccount() {
4062 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
4066 * Get this user's personal page title.
4068 * @return Title User's personal page title
4070 public function getUserPage() {
4071 return Title
::makeTitle( NS_USER
, $this->getName() );
4075 * Get this user's talk page title.
4077 * @return Title User's talk page title
4079 public function getTalkPage() {
4080 $title = $this->getUserPage();
4081 return $title->getTalkPage();
4085 * Determine whether the user is a newbie. Newbies are either
4086 * anonymous IPs, or the most recently created accounts.
4089 public function isNewbie() {
4090 return !$this->isAllowed( 'autoconfirmed' );
4094 * Check to see if the given clear-text password is one of the accepted passwords
4095 * @deprecated since 1.27. AuthManager is coming.
4096 * @param string $password User password
4097 * @return bool True if the given password is correct, otherwise False
4099 public function checkPassword( $password ) {
4100 global $wgAuth, $wgLegacyEncoding;
4104 // Some passwords will give a fatal Status, which means there is
4105 // some sort of technical or security reason for this password to
4106 // be completely invalid and should never be checked (e.g., T64685)
4107 if ( !$this->checkPasswordValidity( $password )->isOK() ) {
4111 // Certain authentication plugins do NOT want to save
4112 // domain passwords in a mysql database, so we should
4113 // check this (in case $wgAuth->strict() is false).
4114 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
4116 } elseif ( $wgAuth->strict() ) {
4117 // Auth plugin doesn't allow local authentication
4119 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
4120 // Auth plugin doesn't allow local authentication for this user name
4124 $passwordFactory = new PasswordFactory();
4125 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4126 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
4127 ?
wfGetDB( DB_MASTER
)
4128 : wfGetDB( DB_SLAVE
);
4131 $mPassword = $passwordFactory->newFromCiphertext( $db->selectField(
4132 'user', 'user_password', [ 'user_id' => $this->getId() ], __METHOD__
4134 } catch ( PasswordError
$e ) {
4135 wfDebug( 'Invalid password hash found in database.' );
4136 $mPassword = PasswordFactory
::newInvalidPassword();
4139 if ( !$mPassword->equals( $password ) ) {
4140 if ( $wgLegacyEncoding ) {
4141 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
4142 // Check for this with iconv
4143 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
4144 if ( $cp1252Password === $password ||
!$mPassword->equals( $cp1252Password ) ) {
4152 if ( $passwordFactory->needsUpdate( $mPassword ) && !wfReadOnly() ) {
4153 $this->setPasswordInternal( $password );
4160 * Check if the given clear-text password matches the temporary password
4161 * sent by e-mail for password reset operations.
4163 * @deprecated since 1.27. AuthManager is coming.
4164 * @param string $plaintext
4165 * @return bool True if matches, false otherwise
4167 public function checkTemporaryPassword( $plaintext ) {
4168 global $wgNewPasswordExpiry;
4172 $passwordFactory = new PasswordFactory();
4173 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4174 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
4175 ?
wfGetDB( DB_MASTER
)
4176 : wfGetDB( DB_SLAVE
);
4178 $row = $db->selectRow(
4180 [ 'user_newpassword', 'user_newpass_time' ],
4181 [ 'user_id' => $this->getId() ],
4185 $newPassword = $passwordFactory->newFromCiphertext( $row->user_newpassword
);
4186 } catch ( PasswordError
$e ) {
4187 wfDebug( 'Invalid password hash found in database.' );
4188 $newPassword = PasswordFactory
::newInvalidPassword();
4191 if ( $newPassword->equals( $plaintext ) ) {
4192 if ( is_null( $row->user_newpass_time
) ) {
4195 $expiry = wfTimestamp( TS_UNIX
, $row->user_newpass_time
) +
$wgNewPasswordExpiry;
4196 return ( time() < $expiry );
4203 * Initialize (if necessary) and return a session token value
4204 * which can be used in edit forms to show that the user's
4205 * login credentials aren't being hijacked with a foreign form
4209 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4210 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4211 * @return MediaWiki\\Session\\Token The new edit token
4213 public function getEditTokenObject( $salt = '', $request = null ) {
4214 if ( $this->isAnon() ) {
4215 return new LoggedOutEditToken();
4219 $request = $this->getRequest();
4221 return $request->getSession()->getToken( $salt );
4225 * Initialize (if necessary) and return a session token value
4226 * which can be used in edit forms to show that the user's
4227 * login credentials aren't being hijacked with a foreign form
4231 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4232 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4233 * @return string The new edit token
4235 public function getEditToken( $salt = '', $request = null ) {
4236 return $this->getEditTokenObject( $salt, $request )->toString();
4240 * Get the embedded timestamp from a token.
4241 * @deprecated since 1.27, use \\MediaWiki\\Session\\Token::getTimestamp instead.
4242 * @param string $val Input token
4245 public static function getEditTokenTimestamp( $val ) {
4246 wfDeprecated( __METHOD__
, '1.27' );
4247 return MediaWiki\Session\Token
::getTimestamp( $val );
4251 * Check given value against the token value stored in the session.
4252 * A match should confirm that the form was submitted from the
4253 * user's own login session, not a form submission from a third-party
4256 * @param string $val Input value to compare
4257 * @param string $salt Optional function-specific data for hashing
4258 * @param WebRequest|null $request Object to use or null to use $wgRequest
4259 * @param int $maxage Fail tokens older than this, in seconds
4260 * @return bool Whether the token matches
4262 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4263 return $this->getEditTokenObject( $salt, $request )->match( $val, $maxage );
4267 * Check given value against the token value stored in the session,
4268 * ignoring the suffix.
4270 * @param string $val Input value to compare
4271 * @param string $salt Optional function-specific data for hashing
4272 * @param WebRequest|null $request Object to use or null to use $wgRequest
4273 * @param int $maxage Fail tokens older than this, in seconds
4274 * @return bool Whether the token matches
4276 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4277 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . self
::EDIT_TOKEN_SUFFIX
;
4278 return $this->matchEditToken( $val, $salt, $request, $maxage );
4282 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4283 * mail to the user's given address.
4285 * @param string $type Message to send, either "created", "changed" or "set"
4288 public function sendConfirmationMail( $type = 'created' ) {
4290 $expiration = null; // gets passed-by-ref and defined in next line.
4291 $token = $this->confirmationToken( $expiration );
4292 $url = $this->confirmationTokenUrl( $token );
4293 $invalidateURL = $this->invalidationTokenUrl( $token );
4294 $this->saveSettings();
4296 if ( $type == 'created' ||
$type === false ) {
4297 $message = 'confirmemail_body';
4298 } elseif ( $type === true ) {
4299 $message = 'confirmemail_body_changed';
4301 // Messages: confirmemail_body_changed, confirmemail_body_set
4302 $message = 'confirmemail_body_' . $type;
4305 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4306 wfMessage( $message,
4307 $this->getRequest()->getIP(),
4310 $wgLang->userTimeAndDate( $expiration, $this ),
4312 $wgLang->userDate( $expiration, $this ),
4313 $wgLang->userTime( $expiration, $this ) )->text() );
4317 * Send an e-mail to this user's account. Does not check for
4318 * confirmed status or validity.
4320 * @param string $subject Message subject
4321 * @param string $body Message body
4322 * @param User|null $from Optional sending user; if unspecified, default
4323 * $wgPasswordSender will be used.
4324 * @param string $replyto Reply-To address
4327 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4328 global $wgPasswordSender;
4330 if ( $from instanceof User
) {
4331 $sender = MailAddress
::newFromUser( $from );
4333 $sender = new MailAddress( $wgPasswordSender,
4334 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4336 $to = MailAddress
::newFromUser( $this );
4338 return UserMailer
::send( $to, $sender, $subject, $body, [
4339 'replyTo' => $replyto,
4344 * Generate, store, and return a new e-mail confirmation code.
4345 * A hash (unsalted, since it's used as a key) is stored.
4347 * @note Call saveSettings() after calling this function to commit
4348 * this change to the database.
4350 * @param string &$expiration Accepts the expiration time
4351 * @return string New token
4353 protected function confirmationToken( &$expiration ) {
4354 global $wgUserEmailConfirmationTokenExpiry;
4356 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4357 $expiration = wfTimestamp( TS_MW
, $expires );
4359 $token = MWCryptRand
::generateHex( 32 );
4360 $hash = md5( $token );
4361 $this->mEmailToken
= $hash;
4362 $this->mEmailTokenExpires
= $expiration;
4367 * Return a URL the user can use to confirm their email address.
4368 * @param string $token Accepts the email confirmation token
4369 * @return string New token URL
4371 protected function confirmationTokenUrl( $token ) {
4372 return $this->getTokenUrl( 'ConfirmEmail', $token );
4376 * Return a URL the user can use to invalidate their email address.
4377 * @param string $token Accepts the email confirmation token
4378 * @return string New token URL
4380 protected function invalidationTokenUrl( $token ) {
4381 return $this->getTokenUrl( 'InvalidateEmail', $token );
4385 * Internal function to format the e-mail validation/invalidation URLs.
4386 * This uses a quickie hack to use the
4387 * hardcoded English names of the Special: pages, for ASCII safety.
4389 * @note Since these URLs get dropped directly into emails, using the
4390 * short English names avoids insanely long URL-encoded links, which
4391 * also sometimes can get corrupted in some browsers/mailers
4392 * (bug 6957 with Gmail and Internet Explorer).
4394 * @param string $page Special page
4395 * @param string $token Token
4396 * @return string Formatted URL
4398 protected function getTokenUrl( $page, $token ) {
4399 // Hack to bypass localization of 'Special:'
4400 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4401 return $title->getCanonicalURL();
4405 * Mark the e-mail address confirmed.
4407 * @note Call saveSettings() after calling this function to commit the change.
4411 public function confirmEmail() {
4412 // Check if it's already confirmed, so we don't touch the database
4413 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4414 if ( !$this->isEmailConfirmed() ) {
4415 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4416 Hooks
::run( 'ConfirmEmailComplete', [ $this ] );
4422 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4423 * address if it was already confirmed.
4425 * @note Call saveSettings() after calling this function to commit the change.
4426 * @return bool Returns true
4428 public function invalidateEmail() {
4430 $this->mEmailToken
= null;
4431 $this->mEmailTokenExpires
= null;
4432 $this->setEmailAuthenticationTimestamp( null );
4434 Hooks
::run( 'InvalidateEmailComplete', [ $this ] );
4439 * Set the e-mail authentication timestamp.
4440 * @param string $timestamp TS_MW timestamp
4442 public function setEmailAuthenticationTimestamp( $timestamp ) {
4444 $this->mEmailAuthenticated
= $timestamp;
4445 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
4449 * Is this user allowed to send e-mails within limits of current
4450 * site configuration?
4453 public function canSendEmail() {
4454 global $wgEnableEmail, $wgEnableUserEmail;
4455 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4458 $canSend = $this->isEmailConfirmed();
4459 Hooks
::run( 'UserCanSendEmail', [ &$this, &$canSend ] );
4464 * Is this user allowed to receive e-mails within limits of current
4465 * site configuration?
4468 public function canReceiveEmail() {
4469 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4473 * Is this user's e-mail address valid-looking and confirmed within
4474 * limits of the current site configuration?
4476 * @note If $wgEmailAuthentication is on, this may require the user to have
4477 * confirmed their address by returning a code or using a password
4478 * sent to the address from the wiki.
4482 public function isEmailConfirmed() {
4483 global $wgEmailAuthentication;
4486 if ( Hooks
::run( 'EmailConfirmed', [ &$this, &$confirmed ] ) ) {
4487 if ( $this->isAnon() ) {
4490 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4493 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4503 * Check whether there is an outstanding request for e-mail confirmation.
4506 public function isEmailConfirmationPending() {
4507 global $wgEmailAuthentication;
4508 return $wgEmailAuthentication &&
4509 !$this->isEmailConfirmed() &&
4510 $this->mEmailToken
&&
4511 $this->mEmailTokenExpires
> wfTimestamp();
4515 * Get the timestamp of account creation.
4517 * @return string|bool|null Timestamp of account creation, false for
4518 * non-existent/anonymous user accounts, or null if existing account
4519 * but information is not in database.
4521 public function getRegistration() {
4522 if ( $this->isAnon() ) {
4526 return $this->mRegistration
;
4530 * Get the timestamp of the first edit
4532 * @return string|bool Timestamp of first edit, or false for
4533 * non-existent/anonymous user accounts.
4535 public function getFirstEditTimestamp() {
4536 if ( $this->getId() == 0 ) {
4537 return false; // anons
4539 $dbr = wfGetDB( DB_SLAVE
);
4540 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4541 [ 'rev_user' => $this->getId() ],
4543 [ 'ORDER BY' => 'rev_timestamp ASC' ]
4546 return false; // no edits
4548 return wfTimestamp( TS_MW
, $time );
4552 * Get the permissions associated with a given list of groups
4554 * @param array $groups Array of Strings List of internal group names
4555 * @return array Array of Strings List of permission key names for given groups combined
4557 public static function getGroupPermissions( $groups ) {
4558 global $wgGroupPermissions, $wgRevokePermissions;
4560 // grant every granted permission first
4561 foreach ( $groups as $group ) {
4562 if ( isset( $wgGroupPermissions[$group] ) ) {
4563 $rights = array_merge( $rights,
4564 // array_filter removes empty items
4565 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4568 // now revoke the revoked permissions
4569 foreach ( $groups as $group ) {
4570 if ( isset( $wgRevokePermissions[$group] ) ) {
4571 $rights = array_diff( $rights,
4572 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4575 return array_unique( $rights );
4579 * Get all the groups who have a given permission
4581 * @param string $role Role to check
4582 * @return array Array of Strings List of internal group names with the given permission
4584 public static function getGroupsWithPermission( $role ) {
4585 global $wgGroupPermissions;
4586 $allowedGroups = [];
4587 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4588 if ( self
::groupHasPermission( $group, $role ) ) {
4589 $allowedGroups[] = $group;
4592 return $allowedGroups;
4596 * Check, if the given group has the given permission
4598 * If you're wanting to check whether all users have a permission, use
4599 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4603 * @param string $group Group to check
4604 * @param string $role Role to check
4607 public static function groupHasPermission( $group, $role ) {
4608 global $wgGroupPermissions, $wgRevokePermissions;
4609 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4610 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4614 * Check if all users may be assumed to have the given permission
4616 * We generally assume so if the right is granted to '*' and isn't revoked
4617 * on any group. It doesn't attempt to take grants or other extension
4618 * limitations on rights into account in the general case, though, as that
4619 * would require it to always return false and defeat the purpose.
4620 * Specifically, session-based rights restrictions (such as OAuth or bot
4621 * passwords) are applied based on the current session.
4624 * @param string $right Right to check
4627 public static function isEveryoneAllowed( $right ) {
4628 global $wgGroupPermissions, $wgRevokePermissions;
4631 // Use the cached results, except in unit tests which rely on
4632 // being able change the permission mid-request
4633 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4634 return $cache[$right];
4637 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4638 $cache[$right] = false;
4642 // If it's revoked anywhere, then everyone doesn't have it
4643 foreach ( $wgRevokePermissions as $rights ) {
4644 if ( isset( $rights[$right] ) && $rights[$right] ) {
4645 $cache[$right] = false;
4650 // Remove any rights that aren't allowed to the global-session user,
4651 // unless there are no sessions for this endpoint.
4652 if ( !defined( 'MW_NO_SESSION' ) ) {
4653 $allowedRights = SessionManager
::getGlobalSession()->getAllowedUserRights();
4654 if ( $allowedRights !== null && !in_array( $right, $allowedRights, true ) ) {
4655 $cache[$right] = false;
4660 // Allow extensions to say false
4661 if ( !Hooks
::run( 'UserIsEveryoneAllowed', [ $right ] ) ) {
4662 $cache[$right] = false;
4666 $cache[$right] = true;
4671 * Get the localized descriptive name for a group, if it exists
4673 * @param string $group Internal group name
4674 * @return string Localized descriptive group name
4676 public static function getGroupName( $group ) {
4677 $msg = wfMessage( "group-$group" );
4678 return $msg->isBlank() ?
$group : $msg->text();
4682 * Get the localized descriptive name for a member of a group, if it exists
4684 * @param string $group Internal group name
4685 * @param string $username Username for gender (since 1.19)
4686 * @return string Localized name for group member
4688 public static function getGroupMember( $group, $username = '#' ) {
4689 $msg = wfMessage( "group-$group-member", $username );
4690 return $msg->isBlank() ?
$group : $msg->text();
4694 * Return the set of defined explicit groups.
4695 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4696 * are not included, as they are defined automatically, not in the database.
4697 * @return array Array of internal group names
4699 public static function getAllGroups() {
4700 global $wgGroupPermissions, $wgRevokePermissions;
4702 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4703 self
::getImplicitGroups()
4708 * Get a list of all available permissions.
4709 * @return string[] Array of permission names
4711 public static function getAllRights() {
4712 if ( self
::$mAllRights === false ) {
4713 global $wgAvailableRights;
4714 if ( count( $wgAvailableRights ) ) {
4715 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
4717 self
::$mAllRights = self
::$mCoreRights;
4719 Hooks
::run( 'UserGetAllRights', [ &self
::$mAllRights ] );
4721 return self
::$mAllRights;
4725 * Get a list of implicit groups
4726 * @return array Array of Strings Array of internal group names
4728 public static function getImplicitGroups() {
4729 global $wgImplicitGroups;
4731 $groups = $wgImplicitGroups;
4732 # Deprecated, use $wgImplicitGroups instead
4733 Hooks
::run( 'UserGetImplicitGroups', [ &$groups ], '1.25' );
4739 * Get the title of a page describing a particular group
4741 * @param string $group Internal group name
4742 * @return Title|bool Title of the page if it exists, false otherwise
4744 public static function getGroupPage( $group ) {
4745 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4746 if ( $msg->exists() ) {
4747 $title = Title
::newFromText( $msg->text() );
4748 if ( is_object( $title ) ) {
4756 * Create a link to the group in HTML, if available;
4757 * else return the group name.
4759 * @param string $group Internal name of the group
4760 * @param string $text The text of the link
4761 * @return string HTML link to the group
4763 public static function makeGroupLinkHTML( $group, $text = '' ) {
4764 if ( $text == '' ) {
4765 $text = self
::getGroupName( $group );
4767 $title = self
::getGroupPage( $group );
4769 return Linker
::link( $title, htmlspecialchars( $text ) );
4771 return htmlspecialchars( $text );
4776 * Create a link to the group in Wikitext, if available;
4777 * else return the group name.
4779 * @param string $group Internal name of the group
4780 * @param string $text The text of the link
4781 * @return string Wikilink to the group
4783 public static function makeGroupLinkWiki( $group, $text = '' ) {
4784 if ( $text == '' ) {
4785 $text = self
::getGroupName( $group );
4787 $title = self
::getGroupPage( $group );
4789 $page = $title->getFullText();
4790 return "[[$page|$text]]";
4797 * Returns an array of the groups that a particular group can add/remove.
4799 * @param string $group The group to check for whether it can add/remove
4800 * @return array Array( 'add' => array( addablegroups ),
4801 * 'remove' => array( removablegroups ),
4802 * 'add-self' => array( addablegroups to self),
4803 * 'remove-self' => array( removable groups from self) )
4805 public static function changeableByGroup( $group ) {
4806 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4815 if ( empty( $wgAddGroups[$group] ) ) {
4816 // Don't add anything to $groups
4817 } elseif ( $wgAddGroups[$group] === true ) {
4818 // You get everything
4819 $groups['add'] = self
::getAllGroups();
4820 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4821 $groups['add'] = $wgAddGroups[$group];
4824 // Same thing for remove
4825 if ( empty( $wgRemoveGroups[$group] ) ) {
4827 } elseif ( $wgRemoveGroups[$group] === true ) {
4828 $groups['remove'] = self
::getAllGroups();
4829 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4830 $groups['remove'] = $wgRemoveGroups[$group];
4833 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4834 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4835 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4836 if ( is_int( $key ) ) {
4837 $wgGroupsAddToSelf['user'][] = $value;
4842 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
4843 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4844 if ( is_int( $key ) ) {
4845 $wgGroupsRemoveFromSelf['user'][] = $value;
4850 // Now figure out what groups the user can add to him/herself
4851 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4853 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4854 // No idea WHY this would be used, but it's there
4855 $groups['add-self'] = User
::getAllGroups();
4856 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4857 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4860 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4862 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4863 $groups['remove-self'] = User
::getAllGroups();
4864 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4865 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4872 * Returns an array of groups that this user can add and remove
4873 * @return array Array( 'add' => array( addablegroups ),
4874 * 'remove' => array( removablegroups ),
4875 * 'add-self' => array( addablegroups to self),
4876 * 'remove-self' => array( removable groups from self) )
4878 public function changeableGroups() {
4879 if ( $this->isAllowed( 'userrights' ) ) {
4880 // This group gives the right to modify everything (reverse-
4881 // compatibility with old "userrights lets you change
4883 // Using array_merge to make the groups reindexed
4884 $all = array_merge( User
::getAllGroups() );
4893 // Okay, it's not so simple, we will have to go through the arrays
4900 $addergroups = $this->getEffectiveGroups();
4902 foreach ( $addergroups as $addergroup ) {
4903 $groups = array_merge_recursive(
4904 $groups, $this->changeableByGroup( $addergroup )
4906 $groups['add'] = array_unique( $groups['add'] );
4907 $groups['remove'] = array_unique( $groups['remove'] );
4908 $groups['add-self'] = array_unique( $groups['add-self'] );
4909 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4915 * Deferred version of incEditCountImmediate()
4917 public function incEditCount() {
4918 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle( function() {
4919 $this->incEditCountImmediate();
4924 * Increment the user's edit-count field.
4925 * Will have no effect for anonymous users.
4928 public function incEditCountImmediate() {
4929 if ( $this->isAnon() ) {
4933 $dbw = wfGetDB( DB_MASTER
);
4934 // No rows will be "affected" if user_editcount is NULL
4937 [ 'user_editcount=user_editcount+1' ],
4938 [ 'user_id' => $this->getId(), 'user_editcount IS NOT NULL' ],
4941 // Lazy initialization check...
4942 if ( $dbw->affectedRows() == 0 ) {
4943 // Now here's a goddamn hack...
4944 $dbr = wfGetDB( DB_SLAVE
);
4945 if ( $dbr !== $dbw ) {
4946 // If we actually have a slave server, the count is
4947 // at least one behind because the current transaction
4948 // has not been committed and replicated.
4949 $this->initEditCount( 1 );
4951 // But if DB_SLAVE is selecting the master, then the
4952 // count we just read includes the revision that was
4953 // just added in the working transaction.
4954 $this->initEditCount();
4957 // Edit count in user cache too
4958 $this->invalidateCache();
4962 * Initialize user_editcount from data out of the revision table
4964 * @param int $add Edits to add to the count from the revision table
4965 * @return int Number of edits
4967 protected function initEditCount( $add = 0 ) {
4968 // Pull from a slave to be less cruel to servers
4969 // Accuracy isn't the point anyway here
4970 $dbr = wfGetDB( DB_SLAVE
);
4971 $count = (int)$dbr->selectField(
4974 [ 'rev_user' => $this->getId() ],
4977 $count = $count +
$add;
4979 $dbw = wfGetDB( DB_MASTER
);
4982 [ 'user_editcount' => $count ],
4983 [ 'user_id' => $this->getId() ],
4991 * Get the description of a given right
4993 * @param string $right Right to query
4994 * @return string Localized description of the right
4996 public static function getRightDescription( $right ) {
4997 $key = "right-$right";
4998 $msg = wfMessage( $key );
4999 return $msg->isBlank() ?
$right : $msg->text();
5003 * Make a new-style password hash
5005 * @param string $password Plain-text password
5006 * @param bool|string $salt Optional salt, may be random or the user ID.
5007 * If unspecified or false, will generate one automatically
5008 * @return string Password hash
5009 * @deprecated since 1.24, use Password class
5011 public static function crypt( $password, $salt = false ) {
5012 wfDeprecated( __METHOD__
, '1.24' );
5013 $passwordFactory = new PasswordFactory();
5014 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
5015 $hash = $passwordFactory->newFromPlaintext( $password );
5016 return $hash->toString();
5020 * Compare a password hash with a plain-text password. Requires the user
5021 * ID if there's a chance that the hash is an old-style hash.
5023 * @param string $hash Password hash
5024 * @param string $password Plain-text password to compare
5025 * @param string|bool $userId User ID for old-style password salt
5028 * @deprecated since 1.24, use Password class
5030 public static function comparePasswords( $hash, $password, $userId = false ) {
5031 wfDeprecated( __METHOD__
, '1.24' );
5033 // Check for *really* old password hashes that don't even have a type
5034 // The old hash format was just an md5 hex hash, with no type information
5035 if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) {
5036 global $wgPasswordSalt;
5037 if ( $wgPasswordSalt ) {
5038 $password = ":B:{$userId}:{$hash}";
5040 $password = ":A:{$hash}";
5044 $passwordFactory = new PasswordFactory();
5045 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
5046 $hash = $passwordFactory->newFromCiphertext( $hash );
5047 return $hash->equals( $password );
5051 * Add a newuser log entry for this user.
5052 * Before 1.19 the return value was always true.
5054 * @param string|bool $action Account creation type.
5055 * - String, one of the following values:
5056 * - 'create' for an anonymous user creating an account for himself.
5057 * This will force the action's performer to be the created user itself,
5058 * no matter the value of $wgUser
5059 * - 'create2' for a logged in user creating an account for someone else
5060 * - 'byemail' when the created user will receive its password by e-mail
5061 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
5062 * - Boolean means whether the account was created by e-mail (deprecated):
5063 * - true will be converted to 'byemail'
5064 * - false will be converted to 'create' if this object is the same as
5065 * $wgUser and to 'create2' otherwise
5067 * @param string $reason User supplied reason
5069 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
5071 public function addNewUserLogEntry( $action = false, $reason = '' ) {
5072 global $wgUser, $wgNewUserLog;
5073 if ( empty( $wgNewUserLog ) ) {
5074 return true; // disabled
5077 if ( $action === true ) {
5078 $action = 'byemail';
5079 } elseif ( $action === false ) {
5080 if ( $this->equals( $wgUser ) ) {
5083 $action = 'create2';
5087 if ( $action === 'create' ||
$action === 'autocreate' ) {
5090 $performer = $wgUser;
5093 $logEntry = new ManualLogEntry( 'newusers', $action );
5094 $logEntry->setPerformer( $performer );
5095 $logEntry->setTarget( $this->getUserPage() );
5096 $logEntry->setComment( $reason );
5097 $logEntry->setParameters( [
5098 '4::userid' => $this->getId(),
5100 $logid = $logEntry->insert();
5102 if ( $action !== 'autocreate' ) {
5103 $logEntry->publish( $logid );
5110 * Add an autocreate newuser log entry for this user
5111 * Used by things like CentralAuth and perhaps other authplugins.
5112 * Consider calling addNewUserLogEntry() directly instead.
5116 public function addNewUserLogEntryAutoCreate() {
5117 $this->addNewUserLogEntry( 'autocreate' );
5123 * Load the user options either from cache, the database or an array
5125 * @param array $data Rows for the current user out of the user_properties table
5127 protected function loadOptions( $data = null ) {
5132 if ( $this->mOptionsLoaded
) {
5136 $this->mOptions
= self
::getDefaultOptions();
5138 if ( !$this->getId() ) {
5139 // For unlogged-in users, load language/variant options from request.
5140 // There's no need to do it for logged-in users: they can set preferences,
5141 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5142 // so don't override user's choice (especially when the user chooses site default).
5143 $variant = $wgContLang->getDefaultVariant();
5144 $this->mOptions
['variant'] = $variant;
5145 $this->mOptions
['language'] = $variant;
5146 $this->mOptionsLoaded
= true;
5150 // Maybe load from the object
5151 if ( !is_null( $this->mOptionOverrides
) ) {
5152 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5153 foreach ( $this->mOptionOverrides
as $key => $value ) {
5154 $this->mOptions
[$key] = $value;
5157 if ( !is_array( $data ) ) {
5158 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5159 // Load from database
5160 $dbr = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
5161 ?
wfGetDB( DB_MASTER
)
5162 : wfGetDB( DB_SLAVE
);
5164 $res = $dbr->select(
5166 [ 'up_property', 'up_value' ],
5167 [ 'up_user' => $this->getId() ],
5171 $this->mOptionOverrides
= [];
5173 foreach ( $res as $row ) {
5174 $data[$row->up_property
] = $row->up_value
;
5177 foreach ( $data as $property => $value ) {
5178 $this->mOptionOverrides
[$property] = $value;
5179 $this->mOptions
[$property] = $value;
5183 $this->mOptionsLoaded
= true;
5185 Hooks
::run( 'UserLoadOptions', [ $this, &$this->mOptions
] );
5189 * Saves the non-default options for this user, as previously set e.g. via
5190 * setOption(), in the database's "user_properties" (preferences) table.
5191 * Usually used via saveSettings().
5193 protected function saveOptions() {
5194 $this->loadOptions();
5196 // Not using getOptions(), to keep hidden preferences in database
5197 $saveOptions = $this->mOptions
;
5199 // Allow hooks to abort, for instance to save to a global profile.
5200 // Reset options to default state before saving.
5201 if ( !Hooks
::run( 'UserSaveOptions', [ $this, &$saveOptions ] ) ) {
5205 $userId = $this->getId();
5207 $insert_rows = []; // all the new preference rows
5208 foreach ( $saveOptions as $key => $value ) {
5209 // Don't bother storing default values
5210 $defaultOption = self
::getDefaultOption( $key );
5211 if ( ( $defaultOption === null && $value !== false && $value !== null )
5212 ||
$value != $defaultOption
5215 'up_user' => $userId,
5216 'up_property' => $key,
5217 'up_value' => $value,
5222 $dbw = wfGetDB( DB_MASTER
);
5224 $res = $dbw->select( 'user_properties',
5225 [ 'up_property', 'up_value' ], [ 'up_user' => $userId ], __METHOD__
);
5227 // Find prior rows that need to be removed or updated. These rows will
5228 // all be deleted (the later so that INSERT IGNORE applies the new values).
5230 foreach ( $res as $row ) {
5231 if ( !isset( $saveOptions[$row->up_property
] )
5232 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
5234 $keysDelete[] = $row->up_property
;
5238 if ( count( $keysDelete ) ) {
5239 // Do the DELETE by PRIMARY KEY for prior rows.
5240 // In the past a very large portion of calls to this function are for setting
5241 // 'rememberpassword' for new accounts (a preference that has since been removed).
5242 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5243 // caused gap locks on [max user ID,+infinity) which caused high contention since
5244 // updates would pile up on each other as they are for higher (newer) user IDs.
5245 // It might not be necessary these days, but it shouldn't hurt either.
5246 $dbw->delete( 'user_properties',
5247 [ 'up_user' => $userId, 'up_property' => $keysDelete ], __METHOD__
);
5249 // Insert the new preference rows
5250 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, [ 'IGNORE' ] );
5254 * Lazily instantiate and return a factory object for making passwords
5256 * @deprecated since 1.27, create a PasswordFactory directly instead
5257 * @return PasswordFactory
5259 public static function getPasswordFactory() {
5260 wfDeprecated( __METHOD__
, '1.27' );
5261 $ret = new PasswordFactory();
5262 $ret->init( RequestContext
::getMain()->getConfig() );
5267 * Provide an array of HTML5 attributes to put on an input element
5268 * intended for the user to enter a new password. This may include
5269 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
5271 * Do *not* use this when asking the user to enter his current password!
5272 * Regardless of configuration, users may have invalid passwords for whatever
5273 * reason (e.g., they were set before requirements were tightened up).
5274 * Only use it when asking for a new password, like on account creation or
5277 * Obviously, you still need to do server-side checking.
5279 * NOTE: A combination of bugs in various browsers means that this function
5280 * actually just returns array() unconditionally at the moment. May as
5281 * well keep it around for when the browser bugs get fixed, though.
5283 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
5285 * @deprecated since 1.27
5286 * @return array Array of HTML attributes suitable for feeding to
5287 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
5288 * That will get confused by the boolean attribute syntax used.)
5290 public static function passwordChangeInputAttribs() {
5291 global $wgMinimalPasswordLength;
5293 if ( $wgMinimalPasswordLength == 0 ) {
5297 # Note that the pattern requirement will always be satisfied if the
5298 # input is empty, so we need required in all cases.
5300 # @todo FIXME: Bug 23769: This needs to not claim the password is required
5301 # if e-mail confirmation is being used. Since HTML5 input validation
5302 # is b0rked anyway in some browsers, just return nothing. When it's
5303 # re-enabled, fix this code to not output required for e-mail
5305 # $ret = array( 'required' );
5308 # We can't actually do this right now, because Opera 9.6 will print out
5309 # the entered password visibly in its error message! When other
5310 # browsers add support for this attribute, or Opera fixes its support,
5311 # we can add support with a version check to avoid doing this on Opera
5312 # versions where it will be a problem. Reported to Opera as
5313 # DSK-262266, but they don't have a public bug tracker for us to follow.
5315 if ( $wgMinimalPasswordLength > 1 ) {
5316 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
5317 $ret['title'] = wfMessage( 'passwordtooshort' )
5318 ->numParams( $wgMinimalPasswordLength )->text();
5326 * Return the list of user fields that should be selected to create
5327 * a new user object.
5330 public static function selectFields() {
5338 'user_email_authenticated',
5340 'user_email_token_expires',
5341 'user_registration',
5347 * Factory function for fatal permission-denied errors
5350 * @param string $permission User right required
5353 static function newFatalPermissionDeniedStatus( $permission ) {
5356 $groups = array_map(
5357 [ 'User', 'makeGroupLinkWiki' ],
5358 User
::getGroupsWithPermission( $permission )
5362 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5364 return Status
::newFatal( 'badaccess-group0' );
5369 * Get a new instance of this user that was loaded from the master via a locking read
5371 * Use this instead of the main context User when updating that user. This avoids races
5372 * where that user was loaded from a slave or even the master but without proper locks.
5374 * @return User|null Returns null if the user was not found in the DB
5377 public function getInstanceForUpdate() {
5378 if ( !$this->getId() ) {
5379 return null; // anon
5382 $user = self
::newFromId( $this->getId() );
5383 if ( !$user->loadFromId( self
::READ_EXCLUSIVE
) ) {
5391 * Checks if two user objects point to the same user.
5397 public function equals( User
$user ) {
5398 return $this->getName() === $user->getName();