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 )
859 wfDebugLog( 'username', __METHOD__
.
860 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
864 // Ensure that the name can't be misresolved as a different title,
865 // such as with extra namespace keys at the start.
866 $parsed = Title
::newFromText( $name );
867 if ( is_null( $parsed )
868 ||
$parsed->getNamespace()
869 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
870 wfDebugLog( 'username', __METHOD__
.
871 ": '$name' invalid due to ambiguous prefixes" );
875 // Check an additional blacklist of troublemaker characters.
876 // Should these be merged into the title char list?
877 $unicodeBlacklist = '/[' .
878 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
879 '\x{00a0}' . # non-breaking space
880 '\x{2000}-\x{200f}' . # various whitespace
881 '\x{2028}-\x{202f}' . # breaks and control chars
882 '\x{3000}' . # ideographic space
883 '\x{e000}-\x{f8ff}' . # private use
885 if ( preg_match( $unicodeBlacklist, $name ) ) {
886 wfDebugLog( 'username', __METHOD__
.
887 ": '$name' invalid due to blacklisted characters" );
895 * Usernames which fail to pass this function will be blocked
896 * from user login and new account registrations, but may be used
897 * internally by batch processes.
899 * If an account already exists in this form, login will be blocked
900 * by a failure to pass this function.
902 * @param string $name Name to match
905 public static function isUsableName( $name ) {
906 global $wgReservedUsernames;
907 // Must be a valid username, obviously ;)
908 if ( !self
::isValidUserName( $name ) ) {
912 static $reservedUsernames = false;
913 if ( !$reservedUsernames ) {
914 $reservedUsernames = $wgReservedUsernames;
915 Hooks
::run( 'UserGetReservedNames', [ &$reservedUsernames ] );
918 // Certain names may be reserved for batch processes.
919 foreach ( $reservedUsernames as $reserved ) {
920 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
921 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
923 if ( $reserved == $name ) {
931 * Usernames which fail to pass this function will be blocked
932 * from new account registrations, but may be used internally
933 * either by batch processes or by user accounts which have
934 * already been created.
936 * Additional blacklisting may be added here rather than in
937 * isValidUserName() to avoid disrupting existing accounts.
939 * @param string $name String to match
942 public static function isCreatableName( $name ) {
943 global $wgInvalidUsernameCharacters;
945 // Ensure that the username isn't longer than 235 bytes, so that
946 // (at least for the builtin skins) user javascript and css files
947 // will work. (bug 23080)
948 if ( strlen( $name ) > 235 ) {
949 wfDebugLog( 'username', __METHOD__
.
950 ": '$name' invalid due to length" );
954 // Preg yells if you try to give it an empty string
955 if ( $wgInvalidUsernameCharacters !== '' ) {
956 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
957 wfDebugLog( 'username', __METHOD__
.
958 ": '$name' invalid due to wgInvalidUsernameCharacters" );
963 return self
::isUsableName( $name );
967 * Is the input a valid password for this user?
969 * @param string $password Desired password
972 public function isValidPassword( $password ) {
973 // simple boolean wrapper for getPasswordValidity
974 return $this->getPasswordValidity( $password ) === true;
978 * Given unvalidated password input, return error message on failure.
980 * @param string $password Desired password
981 * @return bool|string|array True on success, string or array of error message on failure
983 public function getPasswordValidity( $password ) {
984 $result = $this->checkPasswordValidity( $password );
985 if ( $result->isGood() ) {
989 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
990 $messages[] = $error['message'];
992 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
993 $messages[] = $warning['message'];
995 if ( count( $messages ) === 1 ) {
1003 * Check if this is a valid password for this user
1005 * Create a Status object based on the password's validity.
1006 * The Status should be set to fatal if the user should not
1007 * be allowed to log in, and should have any errors that
1008 * would block changing the password.
1010 * If the return value of this is not OK, the password
1011 * should not be checked. If the return value is not Good,
1012 * the password can be checked, but the user should not be
1013 * able to set their password to this.
1015 * @param string $password Desired password
1016 * @param string $purpose one of 'login', 'create', 'reset'
1020 public function checkPasswordValidity( $password, $purpose = 'login' ) {
1021 global $wgPasswordPolicy;
1023 $upp = new UserPasswordPolicy(
1024 $wgPasswordPolicy['policies'],
1025 $wgPasswordPolicy['checks']
1028 $status = Status
::newGood();
1029 $result = false; // init $result to false for the internal checks
1031 if ( !Hooks
::run( 'isValidPassword', [ $password, &$result, $this ] ) ) {
1032 $status->error( $result );
1036 if ( $result === false ) {
1037 $status->merge( $upp->checkUserPassword( $this, $password, $purpose ) );
1039 } elseif ( $result === true ) {
1042 $status->error( $result );
1043 return $status; // the isValidPassword hook set a string $result and returned true
1048 * Given unvalidated user input, return a canonical username, or false if
1049 * the username is invalid.
1050 * @param string $name User input
1051 * @param string|bool $validate Type of validation to use:
1052 * - false No validation
1053 * - 'valid' Valid for batch processes
1054 * - 'usable' Valid for batch processes and login
1055 * - 'creatable' Valid for batch processes, login and account creation
1057 * @throws InvalidArgumentException
1058 * @return bool|string
1060 public static function getCanonicalName( $name, $validate = 'valid' ) {
1061 // Force usernames to capital
1063 $name = $wgContLang->ucfirst( $name );
1065 # Reject names containing '#'; these will be cleaned up
1066 # with title normalisation, but then it's too late to
1068 if ( strpos( $name, '#' ) !== false ) {
1072 // Clean up name according to title rules,
1073 // but only when validation is requested (bug 12654)
1074 $t = ( $validate !== false ) ?
1075 Title
::newFromText( $name ) : Title
::makeTitle( NS_USER
, $name );
1076 // Check for invalid titles
1077 if ( is_null( $t ) ) {
1081 // Reject various classes of invalid names
1083 $name = $wgAuth->getCanonicalName( $t->getText() );
1085 switch ( $validate ) {
1089 if ( !User
::isValidUserName( $name ) ) {
1094 if ( !User
::isUsableName( $name ) ) {
1099 if ( !User
::isCreatableName( $name ) ) {
1104 throw new InvalidArgumentException(
1105 'Invalid parameter value for $validate in ' . __METHOD__
);
1111 * Count the number of edits of a user
1113 * @param int $uid User ID to check
1114 * @return int The user's edit count
1116 * @deprecated since 1.21 in favour of User::getEditCount
1118 public static function edits( $uid ) {
1119 wfDeprecated( __METHOD__
, '1.21' );
1120 $user = self
::newFromId( $uid );
1121 return $user->getEditCount();
1125 * Return a random password.
1127 * @deprecated since 1.27, use PasswordFactory::generateRandomPasswordString()
1128 * @return string New random password
1130 public static function randomPassword() {
1131 global $wgMinimalPasswordLength;
1132 return PasswordFactory
::generateRandomPasswordString( $wgMinimalPasswordLength );
1136 * Set cached properties to default.
1138 * @note This no longer clears uncached lazy-initialised properties;
1139 * the constructor does that instead.
1141 * @param string|bool $name
1143 public function loadDefaults( $name = false ) {
1145 $this->mName
= $name;
1146 $this->mRealName
= '';
1148 $this->mOptionOverrides
= null;
1149 $this->mOptionsLoaded
= false;
1151 $loggedOut = $this->mRequest
&& !defined( 'MW_NO_SESSION' )
1152 ?
$this->mRequest
->getSession()->getLoggedOutTimestamp() : 0;
1153 if ( $loggedOut !== 0 ) {
1154 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1156 $this->mTouched
= '1'; # Allow any pages to be cached
1159 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1160 $this->mEmailAuthenticated
= null;
1161 $this->mEmailToken
= '';
1162 $this->mEmailTokenExpires
= null;
1163 $this->mRegistration
= wfTimestamp( TS_MW
);
1164 $this->mGroups
= [];
1166 Hooks
::run( 'UserLoadDefaults', [ $this, $name ] );
1170 * Return whether an item has been loaded.
1172 * @param string $item Item to check. Current possibilities:
1176 * @param string $all 'all' to check if the whole object has been loaded
1177 * or any other string to check if only the item is available (e.g.
1181 public function isItemLoaded( $item, $all = 'all' ) {
1182 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1183 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1187 * Set that an item has been loaded
1189 * @param string $item
1191 protected function setItemLoaded( $item ) {
1192 if ( is_array( $this->mLoadedItems
) ) {
1193 $this->mLoadedItems
[$item] = true;
1198 * Load user data from the session.
1200 * @return bool True if the user is logged in, false otherwise.
1202 private function loadFromSession() {
1205 Hooks
::run( 'UserLoadFromSession', [ $this, &$result ], '1.27' );
1206 if ( $result !== null ) {
1210 // MediaWiki\Session\Session already did the necessary authentication of the user
1211 // returned here, so just use it if applicable.
1212 $session = $this->getRequest()->getSession();
1213 $user = $session->getUser();
1214 if ( $user->isLoggedIn() ) {
1215 $this->loadFromUserObject( $user );
1216 // Other code expects these to be set in the session, so set them.
1217 $session->set( 'wsUserID', $this->getId() );
1218 $session->set( 'wsUserName', $this->getName() );
1219 $session->set( 'wsToken', $this->getToken() );
1227 * Load user and user_group data from the database.
1228 * $this->mId must be set, this is how the user is identified.
1230 * @param integer $flags User::READ_* constant bitfield
1231 * @return bool True if the user exists, false if the user is anonymous
1233 public function loadFromDatabase( $flags = self
::READ_LATEST
) {
1235 $this->mId
= intval( $this->mId
);
1238 if ( !$this->mId
) {
1239 $this->loadDefaults();
1243 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
1244 $db = wfGetDB( $index );
1246 $s = $db->selectRow(
1248 self
::selectFields(),
1249 [ 'user_id' => $this->mId
],
1254 $this->queryFlagsUsed
= $flags;
1255 Hooks
::run( 'UserLoadFromDatabase', [ $this, &$s ] );
1257 if ( $s !== false ) {
1258 // Initialise user table data
1259 $this->loadFromRow( $s );
1260 $this->mGroups
= null; // deferred
1261 $this->getEditCount(); // revalidation for nulls
1266 $this->loadDefaults();
1272 * Initialize this object from a row from the user table.
1274 * @param stdClass $row Row from the user table to load.
1275 * @param array $data Further user data to load into the object
1277 * user_groups Array with groups out of the user_groups table
1278 * user_properties Array with properties out of the user_properties table
1280 protected function loadFromRow( $row, $data = null ) {
1283 $this->mGroups
= null; // deferred
1285 if ( isset( $row->user_name
) ) {
1286 $this->mName
= $row->user_name
;
1287 $this->mFrom
= 'name';
1288 $this->setItemLoaded( 'name' );
1293 if ( isset( $row->user_real_name
) ) {
1294 $this->mRealName
= $row->user_real_name
;
1295 $this->setItemLoaded( 'realname' );
1300 if ( isset( $row->user_id
) ) {
1301 $this->mId
= intval( $row->user_id
);
1302 $this->mFrom
= 'id';
1303 $this->setItemLoaded( 'id' );
1308 if ( isset( $row->user_id
) && isset( $row->user_name
) ) {
1309 self
::$idCacheByName[$row->user_name
] = $row->user_id
;
1312 if ( isset( $row->user_editcount
) ) {
1313 $this->mEditCount
= $row->user_editcount
;
1318 if ( isset( $row->user_touched
) ) {
1319 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1324 if ( isset( $row->user_token
) ) {
1325 // The definition for the column is binary(32), so trim the NULs
1326 // that appends. The previous definition was char(32), so trim
1328 $this->mToken
= rtrim( $row->user_token
, " \0" );
1329 if ( $this->mToken
=== '' ) {
1330 $this->mToken
= null;
1336 if ( isset( $row->user_email
) ) {
1337 $this->mEmail
= $row->user_email
;
1338 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1339 $this->mEmailToken
= $row->user_email_token
;
1340 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1341 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1347 $this->mLoadedItems
= true;
1350 if ( is_array( $data ) ) {
1351 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1352 $this->mGroups
= $data['user_groups'];
1354 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1355 $this->loadOptions( $data['user_properties'] );
1361 * Load the data for this user object from another user object.
1365 protected function loadFromUserObject( $user ) {
1367 $user->loadGroups();
1368 $user->loadOptions();
1369 foreach ( self
::$mCacheVars as $var ) {
1370 $this->$var = $user->$var;
1375 * Load the groups from the database if they aren't already loaded.
1377 private function loadGroups() {
1378 if ( is_null( $this->mGroups
) ) {
1379 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
1380 ?
wfGetDB( DB_MASTER
)
1381 : wfGetDB( DB_SLAVE
);
1382 $res = $db->select( 'user_groups',
1384 [ 'ug_user' => $this->mId
],
1386 $this->mGroups
= [];
1387 foreach ( $res as $row ) {
1388 $this->mGroups
[] = $row->ug_group
;
1394 * Add the user to the group if he/she meets given criteria.
1396 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1397 * possible to remove manually via Special:UserRights. In such case it
1398 * will not be re-added automatically. The user will also not lose the
1399 * group if they no longer meet the criteria.
1401 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1403 * @return array Array of groups the user has been promoted to.
1405 * @see $wgAutopromoteOnce
1407 public function addAutopromoteOnceGroups( $event ) {
1408 global $wgAutopromoteOnceLogInRC, $wgAuth;
1410 if ( wfReadOnly() ||
!$this->getId() ) {
1414 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1415 if ( !count( $toPromote ) ) {
1419 if ( !$this->checkAndSetTouched() ) {
1420 return []; // raced out (bug T48834)
1423 $oldGroups = $this->getGroups(); // previous groups
1424 foreach ( $toPromote as $group ) {
1425 $this->addGroup( $group );
1427 // update groups in external authentication database
1428 Hooks
::run( 'UserGroupsChanged', [ $this, $toPromote, [], false, false ] );
1429 $wgAuth->updateExternalDBGroups( $this, $toPromote );
1431 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1433 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1434 $logEntry->setPerformer( $this );
1435 $logEntry->setTarget( $this->getUserPage() );
1436 $logEntry->setParameters( [
1437 '4::oldgroups' => $oldGroups,
1438 '5::newgroups' => $newGroups,
1440 $logid = $logEntry->insert();
1441 if ( $wgAutopromoteOnceLogInRC ) {
1442 $logEntry->publish( $logid );
1449 * Bump user_touched if it didn't change since this object was loaded
1451 * On success, the mTouched field is updated.
1452 * The user serialization cache is always cleared.
1454 * @return bool Whether user_touched was actually updated
1457 protected function checkAndSetTouched() {
1460 if ( !$this->mId
) {
1461 return false; // anon
1464 // Get a new user_touched that is higher than the old one
1465 $oldTouched = $this->mTouched
;
1466 $newTouched = $this->newTouchedTimestamp();
1468 $dbw = wfGetDB( DB_MASTER
);
1469 $dbw->update( 'user',
1470 [ 'user_touched' => $dbw->timestamp( $newTouched ) ],
1472 'user_id' => $this->mId
,
1473 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
1477 $success = ( $dbw->affectedRows() > 0 );
1480 $this->mTouched
= $newTouched;
1481 $this->clearSharedCache();
1483 // Clears on failure too since that is desired if the cache is stale
1484 $this->clearSharedCache( 'refresh' );
1491 * Clear various cached data stored in this object. The cache of the user table
1492 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1494 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1495 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1497 public function clearInstanceCache( $reloadFrom = false ) {
1498 $this->mNewtalk
= -1;
1499 $this->mDatePreference
= null;
1500 $this->mBlockedby
= -1; # Unset
1501 $this->mHash
= false;
1502 $this->mRights
= null;
1503 $this->mEffectiveGroups
= null;
1504 $this->mImplicitGroups
= null;
1505 $this->mGroups
= null;
1506 $this->mOptions
= null;
1507 $this->mOptionsLoaded
= false;
1508 $this->mEditCount
= null;
1510 if ( $reloadFrom ) {
1511 $this->mLoadedItems
= [];
1512 $this->mFrom
= $reloadFrom;
1517 * Combine the language default options with any site-specific options
1518 * and add the default language variants.
1520 * @return array Array of String options
1522 public static function getDefaultOptions() {
1523 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1525 static $defOpt = null;
1526 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1527 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1528 // mid-request and see that change reflected in the return value of this function.
1529 // Which is insane and would never happen during normal MW operation
1533 $defOpt = $wgDefaultUserOptions;
1534 // Default language setting
1535 $defOpt['language'] = $wgContLang->getCode();
1536 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1537 $defOpt[$langCode == $wgContLang->getCode() ?
'variant' : "variant-$langCode"] = $langCode;
1539 foreach ( SearchEngine
::searchableNamespaces() as $nsnum => $nsname ) {
1540 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1542 $defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1544 Hooks
::run( 'UserGetDefaultOptions', [ &$defOpt ] );
1550 * Get a given default option value.
1552 * @param string $opt Name of option to retrieve
1553 * @return string Default option value
1555 public static function getDefaultOption( $opt ) {
1556 $defOpts = self
::getDefaultOptions();
1557 if ( isset( $defOpts[$opt] ) ) {
1558 return $defOpts[$opt];
1565 * Get blocking information
1566 * @param bool $bFromSlave Whether to check the slave database first.
1567 * To improve performance, non-critical checks are done against slaves.
1568 * Check when actually saving should be done against master.
1570 private function getBlockedStatus( $bFromSlave = true ) {
1571 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1573 if ( -1 != $this->mBlockedby
) {
1577 wfDebug( __METHOD__
. ": checking...\n" );
1579 // Initialize data...
1580 // Otherwise something ends up stomping on $this->mBlockedby when
1581 // things get lazy-loaded later, causing false positive block hits
1582 // due to -1 !== 0. Probably session-related... Nothing should be
1583 // overwriting mBlockedby, surely?
1586 # We only need to worry about passing the IP address to the Block generator if the
1587 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1588 # know which IP address they're actually coming from
1590 if ( !$this->isAllowed( 'ipblock-exempt' ) ) {
1591 // $wgUser->getName() only works after the end of Setup.php. Until
1592 // then, assume it's a logged-out user.
1593 $globalUserName = $wgUser->isSafeToLoad()
1594 ?
$wgUser->getName()
1595 : IP
::sanitizeIP( $wgUser->getRequest()->getIP() );
1596 if ( $this->getName() === $globalUserName ) {
1597 $ip = $this->getRequest()->getIP();
1602 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1605 if ( !$block instanceof Block
&& $ip !== null && !in_array( $ip, $wgProxyWhitelist ) ) {
1607 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1609 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1610 $block->mReason
= wfMessage( 'proxyblockreason' )->text();
1611 $block->setTarget( $ip );
1612 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1614 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1615 $block->mReason
= wfMessage( 'sorbsreason' )->text();
1616 $block->setTarget( $ip );
1620 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1621 if ( !$block instanceof Block
1622 && $wgApplyIpBlocksToXff
1624 && !in_array( $ip, $wgProxyWhitelist )
1626 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1627 $xff = array_map( 'trim', explode( ',', $xff ) );
1628 $xff = array_diff( $xff, [ $ip ] );
1629 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1630 $block = Block
::chooseBlock( $xffblocks, $xff );
1631 if ( $block instanceof Block
) {
1632 # Mangle the reason to alert the user that the block
1633 # originated from matching the X-Forwarded-For header.
1634 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->text();
1638 if ( $block instanceof Block
) {
1639 wfDebug( __METHOD__
. ": Found block.\n" );
1640 $this->mBlock
= $block;
1641 $this->mBlockedby
= $block->getByName();
1642 $this->mBlockreason
= $block->mReason
;
1643 $this->mHideName
= $block->mHideName
;
1644 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1646 $this->mBlockedby
= '';
1647 $this->mHideName
= 0;
1648 $this->mAllowUsertalk
= false;
1652 Hooks
::run( 'GetBlockedStatus', [ &$this ] );
1657 * Whether the given IP is in a DNS blacklist.
1659 * @param string $ip IP to check
1660 * @param bool $checkWhitelist Whether to check the whitelist first
1661 * @return bool True if blacklisted.
1663 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1664 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1666 if ( !$wgEnableDnsBlacklist ) {
1670 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1674 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1678 * Whether the given IP is in a given DNS blacklist.
1680 * @param string $ip IP to check
1681 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1682 * @return bool True if blacklisted.
1684 public function inDnsBlacklist( $ip, $bases ) {
1687 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1688 if ( IP
::isIPv4( $ip ) ) {
1689 // Reverse IP, bug 21255
1690 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1692 foreach ( (array)$bases as $base ) {
1694 // If we have an access key, use that too (ProjectHoneypot, etc.)
1696 if ( is_array( $base ) ) {
1697 if ( count( $base ) >= 2 ) {
1698 // Access key is 1, base URL is 0
1699 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1701 $host = "$ipReversed.{$base[0]}";
1703 $basename = $base[0];
1705 $host = "$ipReversed.$base";
1709 $ipList = gethostbynamel( $host );
1712 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
1716 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
1725 * Check if an IP address is in the local proxy list
1731 public static function isLocallyBlockedProxy( $ip ) {
1732 global $wgProxyList;
1734 if ( !$wgProxyList ) {
1738 if ( !is_array( $wgProxyList ) ) {
1739 // Load from the specified file
1740 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1743 if ( !is_array( $wgProxyList ) ) {
1745 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1747 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1748 // Old-style flipped proxy list
1757 * Is this user subject to rate limiting?
1759 * @return bool True if rate limited
1761 public function isPingLimitable() {
1762 global $wgRateLimitsExcludedIPs;
1763 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1764 // No other good way currently to disable rate limits
1765 // for specific IPs. :P
1766 // But this is a crappy hack and should die.
1769 return !$this->isAllowed( 'noratelimit' );
1773 * Primitive rate limits: enforce maximum actions per time period
1774 * to put a brake on flooding.
1776 * The method generates both a generic profiling point and a per action one
1777 * (suffix being "-$action".
1779 * @note When using a shared cache like memcached, IP-address
1780 * last-hit counters will be shared across wikis.
1782 * @param string $action Action to enforce; 'edit' if unspecified
1783 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1784 * @return bool True if a rate limiter was tripped
1786 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1787 // Call the 'PingLimiter' hook
1789 if ( !Hooks
::run( 'PingLimiter', [ &$this, $action, &$result, $incrBy ] ) ) {
1793 global $wgRateLimits;
1794 if ( !isset( $wgRateLimits[$action] ) ) {
1798 // Some groups shouldn't trigger the ping limiter, ever
1799 if ( !$this->isPingLimitable() ) {
1803 $limits = $wgRateLimits[$action];
1805 $id = $this->getId();
1807 $isNewbie = $this->isNewbie();
1811 if ( isset( $limits['anon'] ) ) {
1812 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1815 // limits for logged-in users
1816 if ( isset( $limits['user'] ) ) {
1817 $userLimit = $limits['user'];
1819 // limits for newbie logged-in users
1820 if ( $isNewbie && isset( $limits['newbie'] ) ) {
1821 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1825 // limits for anons and for newbie logged-in users
1828 if ( isset( $limits['ip'] ) ) {
1829 $ip = $this->getRequest()->getIP();
1830 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1832 // subnet-based limits
1833 if ( isset( $limits['subnet'] ) ) {
1834 $ip = $this->getRequest()->getIP();
1835 $subnet = IP
::getSubnet( $ip );
1836 if ( $subnet !== false ) {
1837 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1842 // Check for group-specific permissions
1843 // If more than one group applies, use the group with the highest limit ratio (max/period)
1844 foreach ( $this->getGroups() as $group ) {
1845 if ( isset( $limits[$group] ) ) {
1846 if ( $userLimit === false
1847 ||
$limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1849 $userLimit = $limits[$group];
1854 // Set the user limit key
1855 if ( $userLimit !== false ) {
1856 list( $max, $period ) = $userLimit;
1857 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
1858 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1861 // ip-based limits for all ping-limitable users
1862 if ( isset( $limits['ip-all'] ) ) {
1863 $ip = $this->getRequest()->getIP();
1864 // ignore if user limit is more permissive
1865 if ( $isNewbie ||
$userLimit === false
1866 ||
$limits['ip-all'][0] / $limits['ip-all'][1] > $userLimit[0] / $userLimit[1] ) {
1867 $keys["mediawiki:limiter:$action:ip-all:$ip"] = $limits['ip-all'];
1871 // subnet-based limits for all ping-limitable users
1872 if ( isset( $limits['subnet-all'] ) ) {
1873 $ip = $this->getRequest()->getIP();
1874 $subnet = IP
::getSubnet( $ip );
1875 if ( $subnet !== false ) {
1876 // ignore if user limit is more permissive
1877 if ( $isNewbie ||
$userLimit === false
1878 ||
$limits['ip-all'][0] / $limits['ip-all'][1]
1879 > $userLimit[0] / $userLimit[1] ) {
1880 $keys["mediawiki:limiter:$action:subnet-all:$subnet"] = $limits['subnet-all'];
1885 $cache = ObjectCache
::getLocalClusterInstance();
1888 foreach ( $keys as $key => $limit ) {
1889 list( $max, $period ) = $limit;
1890 $summary = "(limit $max in {$period}s)";
1891 $count = $cache->get( $key );
1894 if ( $count >= $max ) {
1895 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1896 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1899 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1902 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1903 if ( $incrBy > 0 ) {
1904 $cache->add( $key, 0, intval( $period ) ); // first ping
1907 if ( $incrBy > 0 ) {
1908 $cache->incr( $key, $incrBy );
1916 * Check if user is blocked
1918 * @param bool $bFromSlave Whether to check the slave database instead of
1919 * the master. Hacked from false due to horrible probs on site.
1920 * @return bool True if blocked, false otherwise
1922 public function isBlocked( $bFromSlave = true ) {
1923 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
1927 * Get the block affecting the user, or null if the user is not blocked
1929 * @param bool $bFromSlave Whether to check the slave database instead of the master
1930 * @return Block|null
1932 public function getBlock( $bFromSlave = true ) {
1933 $this->getBlockedStatus( $bFromSlave );
1934 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
1938 * Check if user is blocked from editing a particular article
1940 * @param Title $title Title to check
1941 * @param bool $bFromSlave Whether to check the slave database instead of the master
1944 public function isBlockedFrom( $title, $bFromSlave = false ) {
1945 global $wgBlockAllowsUTEdit;
1947 $blocked = $this->isBlocked( $bFromSlave );
1948 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
1949 // If a user's name is suppressed, they cannot make edits anywhere
1950 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName()
1951 && $title->getNamespace() == NS_USER_TALK
) {
1953 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
1956 Hooks
::run( 'UserIsBlockedFrom', [ $this, $title, &$blocked, &$allowUsertalk ] );
1962 * If user is blocked, return the name of the user who placed the block
1963 * @return string Name of blocker
1965 public function blockedBy() {
1966 $this->getBlockedStatus();
1967 return $this->mBlockedby
;
1971 * If user is blocked, return the specified reason for the block
1972 * @return string Blocking reason
1974 public function blockedFor() {
1975 $this->getBlockedStatus();
1976 return $this->mBlockreason
;
1980 * If user is blocked, return the ID for the block
1981 * @return int Block ID
1983 public function getBlockId() {
1984 $this->getBlockedStatus();
1985 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
1989 * Check if user is blocked on all wikis.
1990 * Do not use for actual edit permission checks!
1991 * This is intended for quick UI checks.
1993 * @param string $ip IP address, uses current client if none given
1994 * @return bool True if blocked, false otherwise
1996 public function isBlockedGlobally( $ip = '' ) {
1997 if ( $this->mBlockedGlobally
!== null ) {
1998 return $this->mBlockedGlobally
;
2000 // User is already an IP?
2001 if ( IP
::isIPAddress( $this->getName() ) ) {
2002 $ip = $this->getName();
2004 $ip = $this->getRequest()->getIP();
2007 Hooks
::run( 'UserIsBlockedGlobally', [ &$this, $ip, &$blocked ] );
2008 $this->mBlockedGlobally
= (bool)$blocked;
2009 return $this->mBlockedGlobally
;
2013 * Check if user account is locked
2015 * @return bool True if locked, false otherwise
2017 public function isLocked() {
2018 if ( $this->mLocked
!== null ) {
2019 return $this->mLocked
;
2022 $authUser = $wgAuth->getUserInstance( $this );
2023 $this->mLocked
= (bool)$authUser->isLocked();
2024 Hooks
::run( 'UserIsLocked', [ $this, &$this->mLocked
] );
2025 return $this->mLocked
;
2029 * Check if user account is hidden
2031 * @return bool True if hidden, false otherwise
2033 public function isHidden() {
2034 if ( $this->mHideName
!== null ) {
2035 return $this->mHideName
;
2037 $this->getBlockedStatus();
2038 if ( !$this->mHideName
) {
2040 $authUser = $wgAuth->getUserInstance( $this );
2041 $this->mHideName
= (bool)$authUser->isHidden();
2042 Hooks
::run( 'UserIsHidden', [ $this, &$this->mHideName
] );
2044 return $this->mHideName
;
2048 * Get the user's ID.
2049 * @return int The user's ID; 0 if the user is anonymous or nonexistent
2051 public function getId() {
2052 if ( $this->mId
=== null && $this->mName
!== null && User
::isIP( $this->mName
) ) {
2053 // Special case, we know the user is anonymous
2055 } elseif ( !$this->isItemLoaded( 'id' ) ) {
2056 // Don't load if this was initialized from an ID
2063 * Set the user and reload all fields according to a given ID
2064 * @param int $v User ID to reload
2066 public function setId( $v ) {
2068 $this->clearInstanceCache( 'id' );
2072 * Get the user name, or the IP of an anonymous user
2073 * @return string User's name or IP address
2075 public function getName() {
2076 if ( $this->isItemLoaded( 'name', 'only' ) ) {
2077 // Special case optimisation
2078 return $this->mName
;
2081 if ( $this->mName
=== false ) {
2083 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
2085 return $this->mName
;
2090 * Set the user name.
2092 * This does not reload fields from the database according to the given
2093 * name. Rather, it is used to create a temporary "nonexistent user" for
2094 * later addition to the database. It can also be used to set the IP
2095 * address for an anonymous user to something other than the current
2098 * @note User::newFromName() has roughly the same function, when the named user
2100 * @param string $str New user name to set
2102 public function setName( $str ) {
2104 $this->mName
= $str;
2108 * Get the user's name escaped by underscores.
2109 * @return string Username escaped by underscores.
2111 public function getTitleKey() {
2112 return str_replace( ' ', '_', $this->getName() );
2116 * Check if the user has new messages.
2117 * @return bool True if the user has new messages
2119 public function getNewtalk() {
2122 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2123 if ( $this->mNewtalk
=== -1 ) {
2124 $this->mNewtalk
= false; # reset talk page status
2126 // Check memcached separately for anons, who have no
2127 // entire User object stored in there.
2128 if ( !$this->mId
) {
2129 global $wgDisableAnonTalk;
2130 if ( $wgDisableAnonTalk ) {
2131 // Anon newtalk disabled by configuration.
2132 $this->mNewtalk
= false;
2134 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
2137 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2141 return (bool)$this->mNewtalk
;
2145 * Return the data needed to construct links for new talk page message
2146 * alerts. If there are new messages, this will return an associative array
2147 * with the following data:
2148 * wiki: The database name of the wiki
2149 * link: Root-relative link to the user's talk page
2150 * rev: The last talk page revision that the user has seen or null. This
2151 * is useful for building diff links.
2152 * If there are no new messages, it returns an empty array.
2153 * @note This function was designed to accomodate multiple talk pages, but
2154 * currently only returns a single link and revision.
2157 public function getNewMessageLinks() {
2159 if ( !Hooks
::run( 'UserRetrieveNewTalks', [ &$this, &$talks ] ) ) {
2161 } elseif ( !$this->getNewtalk() ) {
2164 $utp = $this->getTalkPage();
2165 $dbr = wfGetDB( DB_SLAVE
);
2166 // Get the "last viewed rev" timestamp from the oldest message notification
2167 $timestamp = $dbr->selectField( 'user_newtalk',
2168 'MIN(user_last_timestamp)',
2169 $this->isAnon() ?
[ 'user_ip' => $this->getName() ] : [ 'user_id' => $this->getID() ],
2171 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2172 return [ [ 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ] ];
2176 * Get the revision ID for the last talk page revision viewed by the talk
2178 * @return int|null Revision ID or null
2180 public function getNewMessageRevisionId() {
2181 $newMessageRevisionId = null;
2182 $newMessageLinks = $this->getNewMessageLinks();
2183 if ( $newMessageLinks ) {
2184 // Note: getNewMessageLinks() never returns more than a single link
2185 // and it is always for the same wiki, but we double-check here in
2186 // case that changes some time in the future.
2187 if ( count( $newMessageLinks ) === 1
2188 && $newMessageLinks[0]['wiki'] === wfWikiID()
2189 && $newMessageLinks[0]['rev']
2191 /** @var Revision $newMessageRevision */
2192 $newMessageRevision = $newMessageLinks[0]['rev'];
2193 $newMessageRevisionId = $newMessageRevision->getId();
2196 return $newMessageRevisionId;
2200 * Internal uncached check for new messages
2203 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2204 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2205 * @return bool True if the user has new messages
2207 protected function checkNewtalk( $field, $id ) {
2208 $dbr = wfGetDB( DB_SLAVE
);
2210 $ok = $dbr->selectField( 'user_newtalk', $field, [ $field => $id ], __METHOD__
);
2212 return $ok !== false;
2216 * Add or update the new messages flag
2217 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2218 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2219 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2220 * @return bool True if successful, false otherwise
2222 protected function updateNewtalk( $field, $id, $curRev = null ) {
2223 // Get timestamp of the talk page revision prior to the current one
2224 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2225 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2226 // Mark the user as having new messages since this revision
2227 $dbw = wfGetDB( DB_MASTER
);
2228 $dbw->insert( 'user_newtalk',
2229 [ $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ],
2232 if ( $dbw->affectedRows() ) {
2233 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2236 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2242 * Clear the new messages flag for the given user
2243 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2244 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2245 * @return bool True if successful, false otherwise
2247 protected function deleteNewtalk( $field, $id ) {
2248 $dbw = wfGetDB( DB_MASTER
);
2249 $dbw->delete( 'user_newtalk',
2252 if ( $dbw->affectedRows() ) {
2253 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2256 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2262 * Update the 'You have new messages!' status.
2263 * @param bool $val Whether the user has new messages
2264 * @param Revision $curRev New, as yet unseen revision of the user talk
2265 * page. Ignored if null or !$val.
2267 public function setNewtalk( $val, $curRev = null ) {
2268 if ( wfReadOnly() ) {
2273 $this->mNewtalk
= $val;
2275 if ( $this->isAnon() ) {
2277 $id = $this->getName();
2280 $id = $this->getId();
2284 $changed = $this->updateNewtalk( $field, $id, $curRev );
2286 $changed = $this->deleteNewtalk( $field, $id );
2290 $this->invalidateCache();
2295 * Generate a current or new-future timestamp to be stored in the
2296 * user_touched field when we update things.
2297 * @return string Timestamp in TS_MW format
2299 private function newTouchedTimestamp() {
2300 global $wgClockSkewFudge;
2302 $time = wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2303 if ( $this->mTouched
&& $time <= $this->mTouched
) {
2304 $time = wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $this->mTouched
) +
1 );
2311 * Clear user data from memcached
2313 * Use after applying updates to the database; caller's
2314 * responsibility to update user_touched if appropriate.
2316 * Called implicitly from invalidateCache() and saveSettings().
2318 * @param string $mode Use 'refresh' to clear now; otherwise before DB commit
2320 public function clearSharedCache( $mode = 'changed' ) {
2321 if ( !$this->getId() ) {
2325 $cache = ObjectCache
::getMainWANInstance();
2326 $processCache = self
::getInProcessCache();
2327 $key = $this->getCacheKey( $cache );
2328 if ( $mode === 'refresh' ) {
2329 $cache->delete( $key, 1 );
2330 $processCache->delete( $key );
2332 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle(
2333 function() use ( $cache, $processCache, $key ) {
2334 $cache->delete( $key );
2335 $processCache->delete( $key );
2342 * Immediately touch the user data cache for this account
2344 * Calls touch() and removes account data from memcached
2346 public function invalidateCache() {
2348 $this->clearSharedCache();
2352 * Update the "touched" timestamp for the user
2354 * This is useful on various login/logout events when making sure that
2355 * a browser or proxy that has multiple tenants does not suffer cache
2356 * pollution where the new user sees the old users content. The value
2357 * of getTouched() is checked when determining 304 vs 200 responses.
2358 * Unlike invalidateCache(), this preserves the User object cache and
2359 * avoids database writes.
2363 public function touch() {
2364 $id = $this->getId();
2366 $key = wfMemcKey( 'user-quicktouched', 'id', $id );
2367 ObjectCache
::getMainWANInstance()->touchCheckKey( $key );
2368 $this->mQuickTouched
= null;
2373 * Validate the cache for this account.
2374 * @param string $timestamp A timestamp in TS_MW format
2377 public function validateCache( $timestamp ) {
2378 return ( $timestamp >= $this->getTouched() );
2382 * Get the user touched timestamp
2384 * Use this value only to validate caches via inequalities
2385 * such as in the case of HTTP If-Modified-Since response logic
2387 * @return string TS_MW Timestamp
2389 public function getTouched() {
2393 if ( $this->mQuickTouched
=== null ) {
2394 $key = wfMemcKey( 'user-quicktouched', 'id', $this->mId
);
2395 $cache = ObjectCache
::getMainWANInstance();
2397 $this->mQuickTouched
= wfTimestamp( TS_MW
, $cache->getCheckKeyTime( $key ) );
2400 return max( $this->mTouched
, $this->mQuickTouched
);
2403 return $this->mTouched
;
2407 * Get the user_touched timestamp field (time of last DB updates)
2408 * @return string TS_MW Timestamp
2411 public function getDBTouched() {
2414 return $this->mTouched
;
2418 * @deprecated Removed in 1.27.
2422 public function getPassword() {
2423 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2427 * @deprecated Removed in 1.27.
2431 public function getTemporaryPassword() {
2432 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2436 * Set the password and reset the random token.
2437 * Calls through to authentication plugin if necessary;
2438 * will have no effect if the auth plugin refuses to
2439 * pass the change through or if the legal password
2442 * As a special case, setting the password to null
2443 * wipes it, so the account cannot be logged in until
2444 * a new password is set, for instance via e-mail.
2446 * @deprecated since 1.27. AuthManager is coming.
2447 * @param string $str New password to set
2448 * @throws PasswordError On failure
2451 public function setPassword( $str ) {
2454 if ( $str !== null ) {
2455 if ( !$wgAuth->allowPasswordChange() ) {
2456 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2459 $status = $this->checkPasswordValidity( $str );
2460 if ( !$status->isGood() ) {
2461 throw new PasswordError( $status->getMessage()->text() );
2465 if ( !$wgAuth->setPassword( $this, $str ) ) {
2466 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2470 $this->setOption( 'watchlisttoken', false );
2471 $this->setPasswordInternal( $str );
2477 * Set the password and reset the random token unconditionally.
2479 * @deprecated since 1.27. AuthManager is coming.
2480 * @param string|null $str New password to set or null to set an invalid
2481 * password hash meaning that the user will not be able to log in
2482 * through the web interface.
2484 public function setInternalPassword( $str ) {
2487 if ( $wgAuth->allowSetLocalPassword() ) {
2489 $this->setOption( 'watchlisttoken', false );
2490 $this->setPasswordInternal( $str );
2495 * Actually set the password and such
2496 * @since 1.27 cannot set a password for a user not in the database
2497 * @param string|null $str New password to set or null to set an invalid
2498 * password hash meaning that the user will not be able to log in
2499 * through the web interface.
2501 private function setPasswordInternal( $str ) {
2502 $id = self
::idFromName( $this->getName(), self
::READ_LATEST
);
2504 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2507 $passwordFactory = new PasswordFactory();
2508 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
2509 $dbw = wfGetDB( DB_MASTER
);
2513 'user_password' => $passwordFactory->newFromPlaintext( $str )->toString(),
2514 'user_newpassword' => PasswordFactory
::newInvalidPassword()->toString(),
2515 'user_newpass_time' => $dbw->timestampOrNull( null ),
2523 // When the main password is changed, invalidate all bot passwords too
2524 BotPassword
::invalidateAllPasswordsForUser( $this->getName() );
2528 * Get the user's current token.
2529 * @param bool $forceCreation Force the generation of a new token if the
2530 * user doesn't have one (default=true for backwards compatibility).
2531 * @return string|null Token
2533 public function getToken( $forceCreation = true ) {
2534 global $wgAuthenticationTokenVersion;
2537 if ( !$this->mToken
&& $forceCreation ) {
2541 if ( !$this->mToken
) {
2542 // The user doesn't have a token, return null to indicate that.
2544 } elseif ( $this->mToken
=== self
::INVALID_TOKEN
) {
2545 // We return a random value here so existing token checks are very
2547 return MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2548 } elseif ( $wgAuthenticationTokenVersion === null ) {
2549 // $wgAuthenticationTokenVersion not in use, so return the raw secret
2550 return $this->mToken
;
2552 // $wgAuthenticationTokenVersion in use, so hmac it.
2553 $ret = MWCryptHash
::hmac( $wgAuthenticationTokenVersion, $this->mToken
, false );
2555 // The raw hash can be overly long. Shorten it up.
2556 $len = max( 32, self
::TOKEN_LENGTH
);
2557 if ( strlen( $ret ) < $len ) {
2558 // Should never happen, even md5 is 128 bits
2559 throw new \
UnexpectedValueException( 'Hmac returned less than 128 bits' );
2561 return substr( $ret, -$len );
2566 * Set the random token (used for persistent authentication)
2567 * Called from loadDefaults() among other places.
2569 * @param string|bool $token If specified, set the token to this value
2571 public function setToken( $token = false ) {
2573 if ( $this->mToken
=== self
::INVALID_TOKEN
) {
2574 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
2575 ->debug( __METHOD__
. ": Ignoring attempt to set token for system user \"$this\"" );
2576 } elseif ( !$token ) {
2577 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2579 $this->mToken
= $token;
2584 * Set the password for a password reminder or new account email
2586 * @deprecated since 1.27, AuthManager is coming
2587 * @param string $str New password to set or null to set an invalid
2588 * password hash meaning that the user will not be able to use it
2589 * @param bool $throttle If true, reset the throttle timestamp to the present
2591 public function setNewpassword( $str, $throttle = true ) {
2592 $id = $this->getId();
2594 throw new LogicException( 'Cannot set new password for a user that is not in the database.' );
2597 $dbw = wfGetDB( DB_MASTER
);
2599 $passwordFactory = new PasswordFactory();
2600 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
2602 'user_newpassword' => $passwordFactory->newFromPlaintext( $str )->toString(),
2605 if ( $str === null ) {
2606 $update['user_newpass_time'] = null;
2607 } elseif ( $throttle ) {
2608 $update['user_newpass_time'] = $dbw->timestamp();
2611 $dbw->update( 'user', $update, [ 'user_id' => $id ], __METHOD__
);
2615 * Has password reminder email been sent within the last
2616 * $wgPasswordReminderResendTime hours?
2619 public function isPasswordReminderThrottled() {
2620 global $wgPasswordReminderResendTime;
2622 if ( !$wgPasswordReminderResendTime ) {
2628 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
2629 ?
wfGetDB( DB_MASTER
)
2630 : wfGetDB( DB_SLAVE
);
2631 $newpassTime = $db->selectField(
2633 'user_newpass_time',
2634 [ 'user_id' => $this->getId() ],
2638 if ( $newpassTime === null ) {
2641 $expiry = wfTimestamp( TS_UNIX
, $newpassTime ) +
$wgPasswordReminderResendTime * 3600;
2642 return time() < $expiry;
2646 * Get the user's e-mail address
2647 * @return string User's email address
2649 public function getEmail() {
2651 Hooks
::run( 'UserGetEmail', [ $this, &$this->mEmail
] );
2652 return $this->mEmail
;
2656 * Get the timestamp of the user's e-mail authentication
2657 * @return string TS_MW timestamp
2659 public function getEmailAuthenticationTimestamp() {
2661 Hooks
::run( 'UserGetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
2662 return $this->mEmailAuthenticated
;
2666 * Set the user's e-mail address
2667 * @param string $str New e-mail address
2669 public function setEmail( $str ) {
2671 if ( $str == $this->mEmail
) {
2674 $this->invalidateEmail();
2675 $this->mEmail
= $str;
2676 Hooks
::run( 'UserSetEmail', [ $this, &$this->mEmail
] );
2680 * Set the user's e-mail address and a confirmation mail if needed.
2683 * @param string $str New e-mail address
2686 public function setEmailWithConfirmation( $str ) {
2687 global $wgEnableEmail, $wgEmailAuthentication;
2689 if ( !$wgEnableEmail ) {
2690 return Status
::newFatal( 'emaildisabled' );
2693 $oldaddr = $this->getEmail();
2694 if ( $str === $oldaddr ) {
2695 return Status
::newGood( true );
2698 $this->setEmail( $str );
2700 if ( $str !== '' && $wgEmailAuthentication ) {
2701 // Send a confirmation request to the new address if needed
2702 $type = $oldaddr != '' ?
'changed' : 'set';
2703 $result = $this->sendConfirmationMail( $type );
2704 if ( $result->isGood() ) {
2705 // Say to the caller that a confirmation mail has been sent
2706 $result->value
= 'eauth';
2709 $result = Status
::newGood( true );
2716 * Get the user's real name
2717 * @return string User's real name
2719 public function getRealName() {
2720 if ( !$this->isItemLoaded( 'realname' ) ) {
2724 return $this->mRealName
;
2728 * Set the user's real name
2729 * @param string $str New real name
2731 public function setRealName( $str ) {
2733 $this->mRealName
= $str;
2737 * Get the user's current setting for a given option.
2739 * @param string $oname The option to check
2740 * @param string $defaultOverride A default value returned if the option does not exist
2741 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2742 * @return string User's current value for the option
2743 * @see getBoolOption()
2744 * @see getIntOption()
2746 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2747 global $wgHiddenPrefs;
2748 $this->loadOptions();
2750 # We want 'disabled' preferences to always behave as the default value for
2751 # users, even if they have set the option explicitly in their settings (ie they
2752 # set it, and then it was disabled removing their ability to change it). But
2753 # we don't want to erase the preferences in the database in case the preference
2754 # is re-enabled again. So don't touch $mOptions, just override the returned value
2755 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2756 return self
::getDefaultOption( $oname );
2759 if ( array_key_exists( $oname, $this->mOptions
) ) {
2760 return $this->mOptions
[$oname];
2762 return $defaultOverride;
2767 * Get all user's options
2769 * @param int $flags Bitwise combination of:
2770 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2771 * to the default value. (Since 1.25)
2774 public function getOptions( $flags = 0 ) {
2775 global $wgHiddenPrefs;
2776 $this->loadOptions();
2777 $options = $this->mOptions
;
2779 # We want 'disabled' preferences to always behave as the default value for
2780 # users, even if they have set the option explicitly in their settings (ie they
2781 # set it, and then it was disabled removing their ability to change it). But
2782 # we don't want to erase the preferences in the database in case the preference
2783 # is re-enabled again. So don't touch $mOptions, just override the returned value
2784 foreach ( $wgHiddenPrefs as $pref ) {
2785 $default = self
::getDefaultOption( $pref );
2786 if ( $default !== null ) {
2787 $options[$pref] = $default;
2791 if ( $flags & self
::GETOPTIONS_EXCLUDE_DEFAULTS
) {
2792 $options = array_diff_assoc( $options, self
::getDefaultOptions() );
2799 * Get the user's current setting for a given option, as a boolean value.
2801 * @param string $oname The option to check
2802 * @return bool User's current value for the option
2805 public function getBoolOption( $oname ) {
2806 return (bool)$this->getOption( $oname );
2810 * Get the user's current setting for a given option, as an integer value.
2812 * @param string $oname The option to check
2813 * @param int $defaultOverride A default value returned if the option does not exist
2814 * @return int User's current value for the option
2817 public function getIntOption( $oname, $defaultOverride = 0 ) {
2818 $val = $this->getOption( $oname );
2820 $val = $defaultOverride;
2822 return intval( $val );
2826 * Set the given option for a user.
2828 * You need to call saveSettings() to actually write to the database.
2830 * @param string $oname The option to set
2831 * @param mixed $val New value to set
2833 public function setOption( $oname, $val ) {
2834 $this->loadOptions();
2836 // Explicitly NULL values should refer to defaults
2837 if ( is_null( $val ) ) {
2838 $val = self
::getDefaultOption( $oname );
2841 $this->mOptions
[$oname] = $val;
2845 * Get a token stored in the preferences (like the watchlist one),
2846 * resetting it if it's empty (and saving changes).
2848 * @param string $oname The option name to retrieve the token from
2849 * @return string|bool User's current value for the option, or false if this option is disabled.
2850 * @see resetTokenFromOption()
2852 * @deprecated 1.26 Applications should use the OAuth extension
2854 public function getTokenFromOption( $oname ) {
2855 global $wgHiddenPrefs;
2857 $id = $this->getId();
2858 if ( !$id ||
in_array( $oname, $wgHiddenPrefs ) ) {
2862 $token = $this->getOption( $oname );
2864 // Default to a value based on the user token to avoid space
2865 // wasted on storing tokens for all users. When this option
2866 // is set manually by the user, only then is it stored.
2867 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
2874 * Reset a token stored in the preferences (like the watchlist one).
2875 * *Does not* save user's preferences (similarly to setOption()).
2877 * @param string $oname The option name to reset the token in
2878 * @return string|bool New token value, or false if this option is disabled.
2879 * @see getTokenFromOption()
2882 public function resetTokenFromOption( $oname ) {
2883 global $wgHiddenPrefs;
2884 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2888 $token = MWCryptRand
::generateHex( 40 );
2889 $this->setOption( $oname, $token );
2894 * Return a list of the types of user options currently returned by
2895 * User::getOptionKinds().
2897 * Currently, the option kinds are:
2898 * - 'registered' - preferences which are registered in core MediaWiki or
2899 * by extensions using the UserGetDefaultOptions hook.
2900 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2901 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2902 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2903 * be used by user scripts.
2904 * - 'special' - "preferences" that are not accessible via User::getOptions
2905 * or User::setOptions.
2906 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2907 * These are usually legacy options, removed in newer versions.
2909 * The API (and possibly others) use this function to determine the possible
2910 * option types for validation purposes, so make sure to update this when a
2911 * new option kind is added.
2913 * @see User::getOptionKinds
2914 * @return array Option kinds
2916 public static function listOptionKinds() {
2919 'registered-multiselect',
2920 'registered-checkmatrix',
2928 * Return an associative array mapping preferences keys to the kind of a preference they're
2929 * used for. Different kinds are handled differently when setting or reading preferences.
2931 * See User::listOptionKinds for the list of valid option types that can be provided.
2933 * @see User::listOptionKinds
2934 * @param IContextSource $context
2935 * @param array $options Assoc. array with options keys to check as keys.
2936 * Defaults to $this->mOptions.
2937 * @return array The key => kind mapping data
2939 public function getOptionKinds( IContextSource
$context, $options = null ) {
2940 $this->loadOptions();
2941 if ( $options === null ) {
2942 $options = $this->mOptions
;
2945 $prefs = Preferences
::getPreferences( $this, $context );
2948 // Pull out the "special" options, so they don't get converted as
2949 // multiselect or checkmatrix.
2950 $specialOptions = array_fill_keys( Preferences
::getSaveBlacklist(), true );
2951 foreach ( $specialOptions as $name => $value ) {
2952 unset( $prefs[$name] );
2955 // Multiselect and checkmatrix options are stored in the database with
2956 // one key per option, each having a boolean value. Extract those keys.
2957 $multiselectOptions = [];
2958 foreach ( $prefs as $name => $info ) {
2959 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2960 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2961 $opts = HTMLFormField
::flattenOptions( $info['options'] );
2962 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2964 foreach ( $opts as $value ) {
2965 $multiselectOptions["$prefix$value"] = true;
2968 unset( $prefs[$name] );
2971 $checkmatrixOptions = [];
2972 foreach ( $prefs as $name => $info ) {
2973 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2974 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2975 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
2976 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
2977 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2979 foreach ( $columns as $column ) {
2980 foreach ( $rows as $row ) {
2981 $checkmatrixOptions["$prefix$column-$row"] = true;
2985 unset( $prefs[$name] );
2989 // $value is ignored
2990 foreach ( $options as $key => $value ) {
2991 if ( isset( $prefs[$key] ) ) {
2992 $mapping[$key] = 'registered';
2993 } elseif ( isset( $multiselectOptions[$key] ) ) {
2994 $mapping[$key] = 'registered-multiselect';
2995 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2996 $mapping[$key] = 'registered-checkmatrix';
2997 } elseif ( isset( $specialOptions[$key] ) ) {
2998 $mapping[$key] = 'special';
2999 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
3000 $mapping[$key] = 'userjs';
3002 $mapping[$key] = 'unused';
3010 * Reset certain (or all) options to the site defaults
3012 * The optional parameter determines which kinds of preferences will be reset.
3013 * Supported values are everything that can be reported by getOptionKinds()
3014 * and 'all', which forces a reset of *all* preferences and overrides everything else.
3016 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
3017 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
3018 * for backwards-compatibility.
3019 * @param IContextSource|null $context Context source used when $resetKinds
3020 * does not contain 'all', passed to getOptionKinds().
3021 * Defaults to RequestContext::getMain() when null.
3023 public function resetOptions(
3024 $resetKinds = [ 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ],
3025 IContextSource
$context = null
3028 $defaultOptions = self
::getDefaultOptions();
3030 if ( !is_array( $resetKinds ) ) {
3031 $resetKinds = [ $resetKinds ];
3034 if ( in_array( 'all', $resetKinds ) ) {
3035 $newOptions = $defaultOptions;
3037 if ( $context === null ) {
3038 $context = RequestContext
::getMain();
3041 $optionKinds = $this->getOptionKinds( $context );
3042 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
3045 // Use default values for the options that should be deleted, and
3046 // copy old values for the ones that shouldn't.
3047 foreach ( $this->mOptions
as $key => $value ) {
3048 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
3049 if ( array_key_exists( $key, $defaultOptions ) ) {
3050 $newOptions[$key] = $defaultOptions[$key];
3053 $newOptions[$key] = $value;
3058 Hooks
::run( 'UserResetAllOptions', [ $this, &$newOptions, $this->mOptions
, $resetKinds ] );
3060 $this->mOptions
= $newOptions;
3061 $this->mOptionsLoaded
= true;
3065 * Get the user's preferred date format.
3066 * @return string User's preferred date format
3068 public function getDatePreference() {
3069 // Important migration for old data rows
3070 if ( is_null( $this->mDatePreference
) ) {
3072 $value = $this->getOption( 'date' );
3073 $map = $wgLang->getDatePreferenceMigrationMap();
3074 if ( isset( $map[$value] ) ) {
3075 $value = $map[$value];
3077 $this->mDatePreference
= $value;
3079 return $this->mDatePreference
;
3083 * Determine based on the wiki configuration and the user's options,
3084 * whether this user must be over HTTPS no matter what.
3088 public function requiresHTTPS() {
3089 global $wgSecureLogin;
3090 if ( !$wgSecureLogin ) {
3093 $https = $this->getBoolOption( 'prefershttps' );
3094 Hooks
::run( 'UserRequiresHTTPS', [ $this, &$https ] );
3096 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
3103 * Get the user preferred stub threshold
3107 public function getStubThreshold() {
3108 global $wgMaxArticleSize; # Maximum article size, in Kb
3109 $threshold = $this->getIntOption( 'stubthreshold' );
3110 if ( $threshold > $wgMaxArticleSize * 1024 ) {
3111 // If they have set an impossible value, disable the preference
3112 // so we can use the parser cache again.
3119 * Get the permissions this user has.
3120 * @return array Array of String permission names
3122 public function getRights() {
3123 if ( is_null( $this->mRights
) ) {
3124 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
3126 // Deny any rights denied by the user's session, unless this
3127 // endpoint has no sessions.
3128 if ( !defined( 'MW_NO_SESSION' ) ) {
3129 $allowedRights = $this->getRequest()->getSession()->getAllowedUserRights();
3130 if ( $allowedRights !== null ) {
3131 $this->mRights
= array_intersect( $this->mRights
, $allowedRights );
3135 Hooks
::run( 'UserGetRights', [ $this, &$this->mRights
] );
3136 // Force reindexation of rights when a hook has unset one of them
3137 $this->mRights
= array_values( array_unique( $this->mRights
) );
3139 return $this->mRights
;
3143 * Get the list of explicit group memberships this user has.
3144 * The implicit * and user groups are not included.
3145 * @return array Array of String internal group names
3147 public function getGroups() {
3149 $this->loadGroups();
3150 return $this->mGroups
;
3154 * Get the list of implicit group memberships this user has.
3155 * This includes all explicit groups, plus 'user' if logged in,
3156 * '*' for all accounts, and autopromoted groups
3157 * @param bool $recache Whether to avoid the cache
3158 * @return array Array of String internal group names
3160 public function getEffectiveGroups( $recache = false ) {
3161 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
3162 $this->mEffectiveGroups
= array_unique( array_merge(
3163 $this->getGroups(), // explicit groups
3164 $this->getAutomaticGroups( $recache ) // implicit groups
3166 // Hook for additional groups
3167 Hooks
::run( 'UserEffectiveGroups', [ &$this, &$this->mEffectiveGroups
] );
3168 // Force reindexation of groups when a hook has unset one of them
3169 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
3171 return $this->mEffectiveGroups
;
3175 * Get the list of implicit group memberships this user has.
3176 * This includes 'user' if logged in, '*' for all accounts,
3177 * and autopromoted groups
3178 * @param bool $recache Whether to avoid the cache
3179 * @return array Array of String internal group names
3181 public function getAutomaticGroups( $recache = false ) {
3182 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
3183 $this->mImplicitGroups
= [ '*' ];
3184 if ( $this->getId() ) {
3185 $this->mImplicitGroups
[] = 'user';
3187 $this->mImplicitGroups
= array_unique( array_merge(
3188 $this->mImplicitGroups
,
3189 Autopromote
::getAutopromoteGroups( $this )
3193 // Assure data consistency with rights/groups,
3194 // as getEffectiveGroups() depends on this function
3195 $this->mEffectiveGroups
= null;
3198 return $this->mImplicitGroups
;
3202 * Returns the groups the user has belonged to.
3204 * The user may still belong to the returned groups. Compare with getGroups().
3206 * The function will not return groups the user had belonged to before MW 1.17
3208 * @return array Names of the groups the user has belonged to.
3210 public function getFormerGroups() {
3213 if ( is_null( $this->mFormerGroups
) ) {
3214 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3215 ?
wfGetDB( DB_MASTER
)
3216 : wfGetDB( DB_SLAVE
);
3217 $res = $db->select( 'user_former_groups',
3219 [ 'ufg_user' => $this->mId
],
3221 $this->mFormerGroups
= [];
3222 foreach ( $res as $row ) {
3223 $this->mFormerGroups
[] = $row->ufg_group
;
3227 return $this->mFormerGroups
;
3231 * Get the user's edit count.
3232 * @return int|null Null for anonymous users
3234 public function getEditCount() {
3235 if ( !$this->getId() ) {
3239 if ( $this->mEditCount
=== null ) {
3240 /* Populate the count, if it has not been populated yet */
3241 $dbr = wfGetDB( DB_SLAVE
);
3242 // check if the user_editcount field has been initialized
3243 $count = $dbr->selectField(
3244 'user', 'user_editcount',
3245 [ 'user_id' => $this->mId
],
3249 if ( $count === null ) {
3250 // it has not been initialized. do so.
3251 $count = $this->initEditCount();
3253 $this->mEditCount
= $count;
3255 return (int)$this->mEditCount
;
3259 * Add the user to the given group.
3260 * This takes immediate effect.
3261 * @param string $group Name of the group to add
3264 public function addGroup( $group ) {
3267 if ( !Hooks
::run( 'UserAddGroup', [ $this, &$group ] ) ) {
3271 $dbw = wfGetDB( DB_MASTER
);
3272 if ( $this->getId() ) {
3273 $dbw->insert( 'user_groups',
3275 'ug_user' => $this->getID(),
3276 'ug_group' => $group,
3282 $this->loadGroups();
3283 $this->mGroups
[] = $group;
3284 // In case loadGroups was not called before, we now have the right twice.
3285 // Get rid of the duplicate.
3286 $this->mGroups
= array_unique( $this->mGroups
);
3288 // Refresh the groups caches, and clear the rights cache so it will be
3289 // refreshed on the next call to $this->getRights().
3290 $this->getEffectiveGroups( true );
3291 $this->mRights
= null;
3293 $this->invalidateCache();
3299 * Remove the user from the given group.
3300 * This takes immediate effect.
3301 * @param string $group Name of the group to remove
3304 public function removeGroup( $group ) {
3306 if ( !Hooks
::run( 'UserRemoveGroup', [ $this, &$group ] ) ) {
3310 $dbw = wfGetDB( DB_MASTER
);
3311 $dbw->delete( 'user_groups',
3313 'ug_user' => $this->getID(),
3314 'ug_group' => $group,
3317 // Remember that the user was in this group
3318 $dbw->insert( 'user_former_groups',
3320 'ufg_user' => $this->getID(),
3321 'ufg_group' => $group,
3327 $this->loadGroups();
3328 $this->mGroups
= array_diff( $this->mGroups
, [ $group ] );
3330 // Refresh the groups caches, and clear the rights cache so it will be
3331 // refreshed on the next call to $this->getRights().
3332 $this->getEffectiveGroups( true );
3333 $this->mRights
= null;
3335 $this->invalidateCache();
3341 * Get whether the user is logged in
3344 public function isLoggedIn() {
3345 return $this->getID() != 0;
3349 * Get whether the user is anonymous
3352 public function isAnon() {
3353 return !$this->isLoggedIn();
3357 * Check if user is allowed to access a feature / make an action
3359 * @param string ... Permissions to test
3360 * @return bool True if user is allowed to perform *any* of the given actions
3362 public function isAllowedAny() {
3363 $permissions = func_get_args();
3364 foreach ( $permissions as $permission ) {
3365 if ( $this->isAllowed( $permission ) ) {
3374 * @param string ... Permissions to test
3375 * @return bool True if the user is allowed to perform *all* of the given actions
3377 public function isAllowedAll() {
3378 $permissions = func_get_args();
3379 foreach ( $permissions as $permission ) {
3380 if ( !$this->isAllowed( $permission ) ) {
3388 * Internal mechanics of testing a permission
3389 * @param string $action
3392 public function isAllowed( $action = '' ) {
3393 if ( $action === '' ) {
3394 return true; // In the spirit of DWIM
3396 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3397 // by misconfiguration: 0 == 'foo'
3398 return in_array( $action, $this->getRights(), true );
3402 * Check whether to enable recent changes patrol features for this user
3403 * @return bool True or false
3405 public function useRCPatrol() {
3406 global $wgUseRCPatrol;
3407 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3411 * Check whether to enable new pages patrol features for this user
3412 * @return bool True or false
3414 public function useNPPatrol() {
3415 global $wgUseRCPatrol, $wgUseNPPatrol;
3417 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3418 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3423 * Check whether to enable new files patrol features for this user
3424 * @return bool True or false
3426 public function useFilePatrol() {
3427 global $wgUseRCPatrol, $wgUseFilePatrol;
3429 ( $wgUseRCPatrol ||
$wgUseFilePatrol )
3430 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3435 * Get the WebRequest object to use with this object
3437 * @return WebRequest
3439 public function getRequest() {
3440 if ( $this->mRequest
) {
3441 return $this->mRequest
;
3449 * Get a WatchedItem for this user and $title.
3451 * @since 1.22 $checkRights parameter added
3452 * @param Title $title
3453 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3454 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3455 * @return WatchedItem
3457 public function getWatchedItem( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3458 $key = $checkRights . ':' . $title->getNamespace() . ':' . $title->getDBkey();
3460 if ( isset( $this->mWatchedItems
[$key] ) ) {
3461 return $this->mWatchedItems
[$key];
3464 if ( count( $this->mWatchedItems
) >= self
::MAX_WATCHED_ITEMS_CACHE
) {
3465 $this->mWatchedItems
= [];
3468 $this->mWatchedItems
[$key] = WatchedItem
::fromUserTitle( $this, $title, $checkRights );
3469 return $this->mWatchedItems
[$key];
3473 * Check the watched status of an article.
3474 * @since 1.22 $checkRights parameter added
3475 * @param Title $title Title of the article to look at
3476 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3477 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3480 public function isWatched( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3481 return $this->getWatchedItem( $title, $checkRights )->isWatched();
3486 * @since 1.22 $checkRights parameter added
3487 * @param Title $title Title of the article to look at
3488 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3489 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3491 public function addWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3492 $this->getWatchedItem( $title, $checkRights )->addWatch();
3493 $this->invalidateCache();
3497 * Stop watching an article.
3498 * @since 1.22 $checkRights parameter added
3499 * @param Title $title Title of the article to look at
3500 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3501 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3503 public function removeWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3504 $this->getWatchedItem( $title, $checkRights )->removeWatch();
3505 $this->invalidateCache();
3509 * Clear the user's notification timestamp for the given title.
3510 * If e-notif e-mails are on, they will receive notification mails on
3511 * the next change of the page if it's watched etc.
3512 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3513 * @param Title $title Title of the article to look at
3514 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3516 public function clearNotification( &$title, $oldid = 0 ) {
3517 global $wgUseEnotif, $wgShowUpdatedMarker;
3519 // Do nothing if the database is locked to writes
3520 if ( wfReadOnly() ) {
3524 // Do nothing if not allowed to edit the watchlist
3525 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3529 // If we're working on user's talk page, we should update the talk page message indicator
3530 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3531 if ( !Hooks
::run( 'UserClearNewTalkNotification', [ &$this, $oldid ] ) ) {
3535 // Try to update the DB post-send and only if needed...
3536 DeferredUpdates
::addCallableUpdate( function() use ( $title, $oldid ) {
3537 if ( !$this->getNewtalk() ) {
3538 return; // no notifications to clear
3541 // Delete the last notifications (they stack up)
3542 $this->setNewtalk( false );
3544 // If there is a new, unseen, revision, use its timestamp
3546 ?
$title->getNextRevisionID( $oldid, Title
::GAID_FOR_UPDATE
)
3549 $this->setNewtalk( true, Revision
::newFromId( $nextid ) );
3554 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3558 if ( $this->isAnon() ) {
3559 // Nothing else to do...
3563 // Only update the timestamp if the page is being watched.
3564 // The query to find out if it is watched is cached both in memcached and per-invocation,
3565 // and when it does have to be executed, it can be on a slave
3566 // If this is the user's newtalk page, we always update the timestamp
3568 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3572 $this->getWatchedItem( $title )->resetNotificationTimestamp(
3578 * Resets all of the given user's page-change notification timestamps.
3579 * If e-notif e-mails are on, they will receive notification mails on
3580 * the next change of any watched page.
3581 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3583 public function clearAllNotifications() {
3584 if ( wfReadOnly() ) {
3588 // Do nothing if not allowed to edit the watchlist
3589 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3593 global $wgUseEnotif, $wgShowUpdatedMarker;
3594 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3595 $this->setNewtalk( false );
3598 $id = $this->getId();
3600 $dbw = wfGetDB( DB_MASTER
);
3601 $dbw->update( 'watchlist',
3602 [ /* SET */ 'wl_notificationtimestamp' => null ],
3603 [ /* WHERE */ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ],
3606 // We also need to clear here the "you have new message" notification for the own user_talk page;
3607 // it's cleared one page view later in WikiPage::doViewUpdates().
3612 * Set a cookie on the user's client. Wrapper for
3613 * WebResponse::setCookie
3614 * @deprecated since 1.27
3615 * @param string $name Name of the cookie to set
3616 * @param string $value Value to set
3617 * @param int $exp Expiration time, as a UNIX time value;
3618 * if 0 or not specified, use the default $wgCookieExpiration
3619 * @param bool $secure
3620 * true: Force setting the secure attribute when setting the cookie
3621 * false: Force NOT setting the secure attribute when setting the cookie
3622 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3623 * @param array $params Array of options sent passed to WebResponse::setcookie()
3624 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3627 protected function setCookie(
3628 $name, $value, $exp = 0, $secure = null, $params = [], $request = null
3630 wfDeprecated( __METHOD__
, '1.27' );
3631 if ( $request === null ) {
3632 $request = $this->getRequest();
3634 $params['secure'] = $secure;
3635 $request->response()->setCookie( $name, $value, $exp, $params );
3639 * Clear a cookie on the user's client
3640 * @deprecated since 1.27
3641 * @param string $name Name of the cookie to clear
3642 * @param bool $secure
3643 * true: Force setting the secure attribute when setting the cookie
3644 * false: Force NOT setting the secure attribute when setting the cookie
3645 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3646 * @param array $params Array of options sent passed to WebResponse::setcookie()
3648 protected function clearCookie( $name, $secure = null, $params = [] ) {
3649 wfDeprecated( __METHOD__
, '1.27' );
3650 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3654 * Set an extended login cookie on the user's client. The expiry of the cookie
3655 * is controlled by the $wgExtendedLoginCookieExpiration configuration
3658 * @see User::setCookie
3660 * @deprecated since 1.27
3661 * @param string $name Name of the cookie to set
3662 * @param string $value Value to set
3663 * @param bool $secure
3664 * true: Force setting the secure attribute when setting the cookie
3665 * false: Force NOT setting the secure attribute when setting the cookie
3666 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3668 protected function setExtendedLoginCookie( $name, $value, $secure ) {
3669 global $wgExtendedLoginCookieExpiration, $wgCookieExpiration;
3671 wfDeprecated( __METHOD__
, '1.27' );
3674 $exp +
= $wgExtendedLoginCookieExpiration !== null
3675 ?
$wgExtendedLoginCookieExpiration
3676 : $wgCookieExpiration;
3678 $this->setCookie( $name, $value, $exp, $secure );
3682 * Persist this user's session (e.g. set cookies)
3684 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3686 * @param bool $secure Whether to force secure/insecure cookies or use default
3687 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3689 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3691 if ( 0 == $this->mId
) {
3695 $session = $this->getRequest()->getSession();
3696 if ( $request && $session->getRequest() !== $request ) {
3697 $session = $session->sessionWithRequest( $request );
3699 $delay = $session->delaySave();
3701 if ( !$session->getUser()->equals( $this ) ) {
3702 if ( !$session->canSetUser() ) {
3703 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3704 ->warning( __METHOD__
.
3705 ": Cannot save user \"$this\" to a user \"{$session->getUser()}\"'s immutable session"
3709 $session->setUser( $this );
3712 $session->setRememberUser( $rememberMe );
3713 if ( $secure !== null ) {
3714 $session->setForceHTTPS( $secure );
3717 $session->persist();
3719 ScopedCallback
::consume( $delay );
3723 * Log this user out.
3725 public function logout() {
3726 if ( Hooks
::run( 'UserLogout', [ &$this ] ) ) {
3732 * Clear the user's session, and reset the instance cache.
3735 public function doLogout() {
3736 $session = $this->getRequest()->getSession();
3737 if ( !$session->canSetUser() ) {
3738 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3739 ->warning( __METHOD__
. ": Cannot log out of an immutable session" );
3740 } elseif ( !$session->getUser()->equals( $this ) ) {
3741 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3742 ->warning( __METHOD__
.
3743 ": Cannot log user \"$this\" out of a user \"{$session->getUser()}\"'s session"
3745 // But we still may as well make this user object anon
3746 $this->clearInstanceCache( 'defaults' );
3748 $this->clearInstanceCache( 'defaults' );
3749 $delay = $session->delaySave();
3750 $session->unpersist(); // Clear cookies (T127436)
3751 $session->setLoggedOutTimestamp( time() );
3752 $session->setUser( new User
);
3753 $session->set( 'wsUserID', 0 ); // Other code expects this
3754 ScopedCallback
::consume( $delay );
3759 * Save this user's settings into the database.
3760 * @todo Only rarely do all these fields need to be set!
3762 public function saveSettings() {
3763 if ( wfReadOnly() ) {
3764 // @TODO: caller should deal with this instead!
3765 // This should really just be an exception.
3766 MWExceptionHandler
::logException( new DBExpectedError(
3768 "Could not update user with ID '{$this->mId}'; DB is read-only."
3774 if ( 0 == $this->mId
) {
3778 // Get a new user_touched that is higher than the old one.
3779 // This will be used for a CAS check as a last-resort safety
3780 // check against race conditions and slave lag.
3781 $oldTouched = $this->mTouched
;
3782 $newTouched = $this->newTouchedTimestamp();
3784 $dbw = wfGetDB( DB_MASTER
);
3785 $dbw->update( 'user',
3787 'user_name' => $this->mName
,
3788 'user_real_name' => $this->mRealName
,
3789 'user_email' => $this->mEmail
,
3790 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3791 'user_touched' => $dbw->timestamp( $newTouched ),
3792 'user_token' => strval( $this->mToken
),
3793 'user_email_token' => $this->mEmailToken
,
3794 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
3796 'user_id' => $this->mId
,
3797 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
3801 if ( !$dbw->affectedRows() ) {
3802 // Maybe the problem was a missed cache update; clear it to be safe
3803 $this->clearSharedCache( 'refresh' );
3804 // User was changed in the meantime or loaded with stale data
3805 $from = ( $this->queryFlagsUsed
& self
::READ_LATEST
) ?
'master' : 'slave';
3806 throw new MWException(
3807 "CAS update failed on user_touched for user ID '{$this->mId}' (read from $from);" .
3808 " the version of the user to be saved is older than the current version."
3812 $this->mTouched
= $newTouched;
3813 $this->saveOptions();
3815 Hooks
::run( 'UserSaveSettings', [ $this ] );
3816 $this->clearSharedCache();
3817 $this->getUserPage()->invalidateCache();
3821 * If only this user's username is known, and it exists, return the user ID.
3823 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
3826 public function idForName( $flags = 0 ) {
3827 $s = trim( $this->getName() );
3832 $db = ( ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
)
3833 ?
wfGetDB( DB_MASTER
)
3834 : wfGetDB( DB_SLAVE
);
3836 $options = ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
)
3837 ?
[ 'LOCK IN SHARE MODE' ]
3840 $id = $db->selectField( 'user',
3841 'user_id', [ 'user_name' => $s ], __METHOD__
, $options );
3847 * Add a user to the database, return the user object
3849 * @param string $name Username to add
3850 * @param array $params Array of Strings Non-default parameters to save to
3851 * the database as user_* fields:
3852 * - email: The user's email address.
3853 * - email_authenticated: The email authentication timestamp.
3854 * - real_name: The user's real name.
3855 * - options: An associative array of non-default options.
3856 * - token: Random authentication token. Do not set.
3857 * - registration: Registration timestamp. Do not set.
3859 * @return User|null User object, or null if the username already exists.
3861 public static function createNew( $name, $params = [] ) {
3862 foreach ( [ 'password', 'newpassword', 'newpass_time', 'password_expires' ] as $field ) {
3863 if ( isset( $params[$field] ) ) {
3864 wfDeprecated( __METHOD__
. " with param '$field'", '1.27' );
3865 unset( $params[$field] );
3871 $user->setToken(); // init token
3872 if ( isset( $params['options'] ) ) {
3873 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
3874 unset( $params['options'] );
3876 $dbw = wfGetDB( DB_MASTER
);
3877 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3879 $noPass = PasswordFactory
::newInvalidPassword()->toString();
3882 'user_id' => $seqVal,
3883 'user_name' => $name,
3884 'user_password' => $noPass,
3885 'user_newpassword' => $noPass,
3886 'user_email' => $user->mEmail
,
3887 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
3888 'user_real_name' => $user->mRealName
,
3889 'user_token' => strval( $user->mToken
),
3890 'user_registration' => $dbw->timestamp( $user->mRegistration
),
3891 'user_editcount' => 0,
3892 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
3894 foreach ( $params as $name => $value ) {
3895 $fields["user_$name"] = $value;
3897 $dbw->insert( 'user', $fields, __METHOD__
, [ 'IGNORE' ] );
3898 if ( $dbw->affectedRows() ) {
3899 $newUser = User
::newFromId( $dbw->insertId() );
3907 * Add this existing user object to the database. If the user already
3908 * exists, a fatal status object is returned, and the user object is
3909 * initialised with the data from the database.
3911 * Previously, this function generated a DB error due to a key conflict
3912 * if the user already existed. Many extension callers use this function
3913 * in code along the lines of:
3915 * $user = User::newFromName( $name );
3916 * if ( !$user->isLoggedIn() ) {
3917 * $user->addToDatabase();
3919 * // do something with $user...
3921 * However, this was vulnerable to a race condition (bug 16020). By
3922 * initialising the user object if the user exists, we aim to support this
3923 * calling sequence as far as possible.
3925 * Note that if the user exists, this function will acquire a write lock,
3926 * so it is still advisable to make the call conditional on isLoggedIn(),
3927 * and to commit the transaction after calling.
3929 * @throws MWException
3932 public function addToDatabase() {
3934 if ( !$this->mToken
) {
3935 $this->setToken(); // init token
3938 $this->mTouched
= $this->newTouchedTimestamp();
3940 $noPass = PasswordFactory
::newInvalidPassword()->toString();
3942 $dbw = wfGetDB( DB_MASTER
);
3943 $inWrite = $dbw->writesOrCallbacksPending();
3944 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3945 $dbw->insert( 'user',
3947 'user_id' => $seqVal,
3948 'user_name' => $this->mName
,
3949 'user_password' => $noPass,
3950 'user_newpassword' => $noPass,
3951 'user_email' => $this->mEmail
,
3952 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3953 'user_real_name' => $this->mRealName
,
3954 'user_token' => strval( $this->mToken
),
3955 'user_registration' => $dbw->timestamp( $this->mRegistration
),
3956 'user_editcount' => 0,
3957 'user_touched' => $dbw->timestamp( $this->mTouched
),
3961 if ( !$dbw->affectedRows() ) {
3962 // The queries below cannot happen in the same REPEATABLE-READ snapshot.
3963 // Handle this by COMMIT, if possible, or by LOCK IN SHARE MODE otherwise.
3965 // Can't commit due to pending writes that may need atomicity.
3966 // This may cause some lock contention unlike the case below.
3967 $options = [ 'LOCK IN SHARE MODE' ];
3968 $flags = self
::READ_LOCKING
;
3970 // Often, this case happens early in views before any writes when
3971 // using CentralAuth. It's should be OK to commit and break the snapshot.
3972 $dbw->commit( __METHOD__
, 'flush' );
3974 $flags = self
::READ_LATEST
;
3976 $this->mId
= $dbw->selectField( 'user', 'user_id',
3977 [ 'user_name' => $this->mName
], __METHOD__
, $options );
3980 if ( $this->loadFromDatabase( $flags ) ) {
3985 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
3986 "to insert user '{$this->mName}' row, but it was not present in select!" );
3988 return Status
::newFatal( 'userexists' );
3990 $this->mId
= $dbw->insertId();
3991 self
::$idCacheByName[$this->mName
] = $this->mId
;
3993 // Clear instance cache other than user table data, which is already accurate
3994 $this->clearInstanceCache();
3996 $this->saveOptions();
3997 return Status
::newGood();
4001 * If this user is logged-in and blocked,
4002 * block any IP address they've successfully logged in from.
4003 * @return bool A block was spread
4005 public function spreadAnyEditBlock() {
4006 if ( $this->isLoggedIn() && $this->isBlocked() ) {
4007 return $this->spreadBlock();
4013 * If this (non-anonymous) user is blocked,
4014 * block the IP address they've successfully logged in from.
4015 * @return bool A block was spread
4017 protected function spreadBlock() {
4018 wfDebug( __METHOD__
. "()\n" );
4020 if ( $this->mId
== 0 ) {
4024 $userblock = Block
::newFromTarget( $this->getName() );
4025 if ( !$userblock ) {
4029 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
4033 * Get whether the user is explicitly blocked from account creation.
4034 * @return bool|Block
4036 public function isBlockedFromCreateAccount() {
4037 $this->getBlockedStatus();
4038 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
4039 return $this->mBlock
;
4042 # bug 13611: if the IP address the user is trying to create an account from is
4043 # blocked with createaccount disabled, prevent new account creation there even
4044 # when the user is logged in
4045 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
4046 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
4048 return $this->mBlockedFromCreateAccount
instanceof Block
4049 && $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
4050 ?
$this->mBlockedFromCreateAccount
4055 * Get whether the user is blocked from using Special:Emailuser.
4058 public function isBlockedFromEmailuser() {
4059 $this->getBlockedStatus();
4060 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
4064 * Get whether the user is allowed to create an account.
4067 public function isAllowedToCreateAccount() {
4068 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
4072 * Get this user's personal page title.
4074 * @return Title User's personal page title
4076 public function getUserPage() {
4077 return Title
::makeTitle( NS_USER
, $this->getName() );
4081 * Get this user's talk page title.
4083 * @return Title User's talk page title
4085 public function getTalkPage() {
4086 $title = $this->getUserPage();
4087 return $title->getTalkPage();
4091 * Determine whether the user is a newbie. Newbies are either
4092 * anonymous IPs, or the most recently created accounts.
4095 public function isNewbie() {
4096 return !$this->isAllowed( 'autoconfirmed' );
4100 * Check to see if the given clear-text password is one of the accepted passwords
4101 * @deprecated since 1.27. AuthManager is coming.
4102 * @param string $password User password
4103 * @return bool True if the given password is correct, otherwise False
4105 public function checkPassword( $password ) {
4106 global $wgAuth, $wgLegacyEncoding;
4110 // Some passwords will give a fatal Status, which means there is
4111 // some sort of technical or security reason for this password to
4112 // be completely invalid and should never be checked (e.g., T64685)
4113 if ( !$this->checkPasswordValidity( $password )->isOK() ) {
4117 // Certain authentication plugins do NOT want to save
4118 // domain passwords in a mysql database, so we should
4119 // check this (in case $wgAuth->strict() is false).
4120 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
4122 } elseif ( $wgAuth->strict() ) {
4123 // Auth plugin doesn't allow local authentication
4125 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
4126 // Auth plugin doesn't allow local authentication for this user name
4130 $passwordFactory = new PasswordFactory();
4131 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4132 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
4133 ?
wfGetDB( DB_MASTER
)
4134 : wfGetDB( DB_SLAVE
);
4137 $mPassword = $passwordFactory->newFromCiphertext( $db->selectField(
4138 'user', 'user_password', [ 'user_id' => $this->getId() ], __METHOD__
4140 } catch ( PasswordError
$e ) {
4141 wfDebug( 'Invalid password hash found in database.' );
4142 $mPassword = PasswordFactory
::newInvalidPassword();
4145 if ( !$mPassword->equals( $password ) ) {
4146 if ( $wgLegacyEncoding ) {
4147 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
4148 // Check for this with iconv
4149 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
4150 if ( $cp1252Password === $password ||
!$mPassword->equals( $cp1252Password ) ) {
4158 if ( $passwordFactory->needsUpdate( $mPassword ) && !wfReadOnly() ) {
4159 $this->setPasswordInternal( $password );
4166 * Check if the given clear-text password matches the temporary password
4167 * sent by e-mail for password reset operations.
4169 * @deprecated since 1.27. AuthManager is coming.
4170 * @param string $plaintext
4171 * @return bool True if matches, false otherwise
4173 public function checkTemporaryPassword( $plaintext ) {
4174 global $wgNewPasswordExpiry;
4178 $passwordFactory = new PasswordFactory();
4179 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4180 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
4181 ?
wfGetDB( DB_MASTER
)
4182 : wfGetDB( DB_SLAVE
);
4184 $row = $db->selectRow(
4186 [ 'user_newpassword', 'user_newpass_time' ],
4187 [ 'user_id' => $this->getId() ],
4191 $newPassword = $passwordFactory->newFromCiphertext( $row->user_newpassword
);
4192 } catch ( PasswordError
$e ) {
4193 wfDebug( 'Invalid password hash found in database.' );
4194 $newPassword = PasswordFactory
::newInvalidPassword();
4197 if ( $newPassword->equals( $plaintext ) ) {
4198 if ( is_null( $row->user_newpass_time
) ) {
4201 $expiry = wfTimestamp( TS_UNIX
, $row->user_newpass_time
) +
$wgNewPasswordExpiry;
4202 return ( time() < $expiry );
4209 * Initialize (if necessary) and return a session token value
4210 * which can be used in edit forms to show that the user's
4211 * login credentials aren't being hijacked with a foreign form
4215 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4216 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4217 * @return MediaWiki\\Session\\Token The new edit token
4219 public function getEditTokenObject( $salt = '', $request = null ) {
4220 if ( $this->isAnon() ) {
4221 return new LoggedOutEditToken();
4225 $request = $this->getRequest();
4227 return $request->getSession()->getToken( $salt );
4231 * Initialize (if necessary) and return a session token value
4232 * which can be used in edit forms to show that the user's
4233 * login credentials aren't being hijacked with a foreign form
4237 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4238 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4239 * @return string The new edit token
4241 public function getEditToken( $salt = '', $request = null ) {
4242 return $this->getEditTokenObject( $salt, $request )->toString();
4246 * Get the embedded timestamp from a token.
4247 * @deprecated since 1.27, use \\MediaWiki\\Session\\Token::getTimestamp instead.
4248 * @param string $val Input token
4251 public static function getEditTokenTimestamp( $val ) {
4252 wfDeprecated( __METHOD__
, '1.27' );
4253 return MediaWiki\Session\Token
::getTimestamp( $val );
4257 * Check given value against the token value stored in the session.
4258 * A match should confirm that the form was submitted from the
4259 * user's own login session, not a form submission from a third-party
4262 * @param string $val Input value to compare
4263 * @param string $salt Optional function-specific data for hashing
4264 * @param WebRequest|null $request Object to use or null to use $wgRequest
4265 * @param int $maxage Fail tokens older than this, in seconds
4266 * @return bool Whether the token matches
4268 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4269 return $this->getEditTokenObject( $salt, $request )->match( $val, $maxage );
4273 * Check given value against the token value stored in the session,
4274 * ignoring the suffix.
4276 * @param string $val Input value to compare
4277 * @param string $salt Optional function-specific data for hashing
4278 * @param WebRequest|null $request Object to use or null to use $wgRequest
4279 * @param int $maxage Fail tokens older than this, in seconds
4280 * @return bool Whether the token matches
4282 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4283 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . self
::EDIT_TOKEN_SUFFIX
;
4284 return $this->matchEditToken( $val, $salt, $request, $maxage );
4288 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4289 * mail to the user's given address.
4291 * @param string $type Message to send, either "created", "changed" or "set"
4294 public function sendConfirmationMail( $type = 'created' ) {
4296 $expiration = null; // gets passed-by-ref and defined in next line.
4297 $token = $this->confirmationToken( $expiration );
4298 $url = $this->confirmationTokenUrl( $token );
4299 $invalidateURL = $this->invalidationTokenUrl( $token );
4300 $this->saveSettings();
4302 if ( $type == 'created' ||
$type === false ) {
4303 $message = 'confirmemail_body';
4304 } elseif ( $type === true ) {
4305 $message = 'confirmemail_body_changed';
4307 // Messages: confirmemail_body_changed, confirmemail_body_set
4308 $message = 'confirmemail_body_' . $type;
4311 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4312 wfMessage( $message,
4313 $this->getRequest()->getIP(),
4316 $wgLang->userTimeAndDate( $expiration, $this ),
4318 $wgLang->userDate( $expiration, $this ),
4319 $wgLang->userTime( $expiration, $this ) )->text() );
4323 * Send an e-mail to this user's account. Does not check for
4324 * confirmed status or validity.
4326 * @param string $subject Message subject
4327 * @param string $body Message body
4328 * @param User|null $from Optional sending user; if unspecified, default
4329 * $wgPasswordSender will be used.
4330 * @param string $replyto Reply-To address
4333 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4334 global $wgPasswordSender;
4336 if ( $from instanceof User
) {
4337 $sender = MailAddress
::newFromUser( $from );
4339 $sender = new MailAddress( $wgPasswordSender,
4340 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4342 $to = MailAddress
::newFromUser( $this );
4344 return UserMailer
::send( $to, $sender, $subject, $body, [
4345 'replyTo' => $replyto,
4350 * Generate, store, and return a new e-mail confirmation code.
4351 * A hash (unsalted, since it's used as a key) is stored.
4353 * @note Call saveSettings() after calling this function to commit
4354 * this change to the database.
4356 * @param string &$expiration Accepts the expiration time
4357 * @return string New token
4359 protected function confirmationToken( &$expiration ) {
4360 global $wgUserEmailConfirmationTokenExpiry;
4362 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4363 $expiration = wfTimestamp( TS_MW
, $expires );
4365 $token = MWCryptRand
::generateHex( 32 );
4366 $hash = md5( $token );
4367 $this->mEmailToken
= $hash;
4368 $this->mEmailTokenExpires
= $expiration;
4373 * Return a URL the user can use to confirm their email address.
4374 * @param string $token Accepts the email confirmation token
4375 * @return string New token URL
4377 protected function confirmationTokenUrl( $token ) {
4378 return $this->getTokenUrl( 'ConfirmEmail', $token );
4382 * Return a URL the user can use to invalidate their email address.
4383 * @param string $token Accepts the email confirmation token
4384 * @return string New token URL
4386 protected function invalidationTokenUrl( $token ) {
4387 return $this->getTokenUrl( 'InvalidateEmail', $token );
4391 * Internal function to format the e-mail validation/invalidation URLs.
4392 * This uses a quickie hack to use the
4393 * hardcoded English names of the Special: pages, for ASCII safety.
4395 * @note Since these URLs get dropped directly into emails, using the
4396 * short English names avoids insanely long URL-encoded links, which
4397 * also sometimes can get corrupted in some browsers/mailers
4398 * (bug 6957 with Gmail and Internet Explorer).
4400 * @param string $page Special page
4401 * @param string $token Token
4402 * @return string Formatted URL
4404 protected function getTokenUrl( $page, $token ) {
4405 // Hack to bypass localization of 'Special:'
4406 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4407 return $title->getCanonicalURL();
4411 * Mark the e-mail address confirmed.
4413 * @note Call saveSettings() after calling this function to commit the change.
4417 public function confirmEmail() {
4418 // Check if it's already confirmed, so we don't touch the database
4419 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4420 if ( !$this->isEmailConfirmed() ) {
4421 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4422 Hooks
::run( 'ConfirmEmailComplete', [ $this ] );
4428 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4429 * address if it was already confirmed.
4431 * @note Call saveSettings() after calling this function to commit the change.
4432 * @return bool Returns true
4434 public function invalidateEmail() {
4436 $this->mEmailToken
= null;
4437 $this->mEmailTokenExpires
= null;
4438 $this->setEmailAuthenticationTimestamp( null );
4440 Hooks
::run( 'InvalidateEmailComplete', [ $this ] );
4445 * Set the e-mail authentication timestamp.
4446 * @param string $timestamp TS_MW timestamp
4448 public function setEmailAuthenticationTimestamp( $timestamp ) {
4450 $this->mEmailAuthenticated
= $timestamp;
4451 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
4455 * Is this user allowed to send e-mails within limits of current
4456 * site configuration?
4459 public function canSendEmail() {
4460 global $wgEnableEmail, $wgEnableUserEmail;
4461 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4464 $canSend = $this->isEmailConfirmed();
4465 Hooks
::run( 'UserCanSendEmail', [ &$this, &$canSend ] );
4470 * Is this user allowed to receive e-mails within limits of current
4471 * site configuration?
4474 public function canReceiveEmail() {
4475 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4479 * Is this user's e-mail address valid-looking and confirmed within
4480 * limits of the current site configuration?
4482 * @note If $wgEmailAuthentication is on, this may require the user to have
4483 * confirmed their address by returning a code or using a password
4484 * sent to the address from the wiki.
4488 public function isEmailConfirmed() {
4489 global $wgEmailAuthentication;
4492 if ( Hooks
::run( 'EmailConfirmed', [ &$this, &$confirmed ] ) ) {
4493 if ( $this->isAnon() ) {
4496 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4499 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4509 * Check whether there is an outstanding request for e-mail confirmation.
4512 public function isEmailConfirmationPending() {
4513 global $wgEmailAuthentication;
4514 return $wgEmailAuthentication &&
4515 !$this->isEmailConfirmed() &&
4516 $this->mEmailToken
&&
4517 $this->mEmailTokenExpires
> wfTimestamp();
4521 * Get the timestamp of account creation.
4523 * @return string|bool|null Timestamp of account creation, false for
4524 * non-existent/anonymous user accounts, or null if existing account
4525 * but information is not in database.
4527 public function getRegistration() {
4528 if ( $this->isAnon() ) {
4532 return $this->mRegistration
;
4536 * Get the timestamp of the first edit
4538 * @return string|bool Timestamp of first edit, or false for
4539 * non-existent/anonymous user accounts.
4541 public function getFirstEditTimestamp() {
4542 if ( $this->getId() == 0 ) {
4543 return false; // anons
4545 $dbr = wfGetDB( DB_SLAVE
);
4546 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4547 [ 'rev_user' => $this->getId() ],
4549 [ 'ORDER BY' => 'rev_timestamp ASC' ]
4552 return false; // no edits
4554 return wfTimestamp( TS_MW
, $time );
4558 * Get the permissions associated with a given list of groups
4560 * @param array $groups Array of Strings List of internal group names
4561 * @return array Array of Strings List of permission key names for given groups combined
4563 public static function getGroupPermissions( $groups ) {
4564 global $wgGroupPermissions, $wgRevokePermissions;
4566 // grant every granted permission first
4567 foreach ( $groups as $group ) {
4568 if ( isset( $wgGroupPermissions[$group] ) ) {
4569 $rights = array_merge( $rights,
4570 // array_filter removes empty items
4571 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4574 // now revoke the revoked permissions
4575 foreach ( $groups as $group ) {
4576 if ( isset( $wgRevokePermissions[$group] ) ) {
4577 $rights = array_diff( $rights,
4578 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4581 return array_unique( $rights );
4585 * Get all the groups who have a given permission
4587 * @param string $role Role to check
4588 * @return array Array of Strings List of internal group names with the given permission
4590 public static function getGroupsWithPermission( $role ) {
4591 global $wgGroupPermissions;
4592 $allowedGroups = [];
4593 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4594 if ( self
::groupHasPermission( $group, $role ) ) {
4595 $allowedGroups[] = $group;
4598 return $allowedGroups;
4602 * Check, if the given group has the given permission
4604 * If you're wanting to check whether all users have a permission, use
4605 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4609 * @param string $group Group to check
4610 * @param string $role Role to check
4613 public static function groupHasPermission( $group, $role ) {
4614 global $wgGroupPermissions, $wgRevokePermissions;
4615 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4616 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4620 * Check if all users may be assumed to have the given permission
4622 * We generally assume so if the right is granted to '*' and isn't revoked
4623 * on any group. It doesn't attempt to take grants or other extension
4624 * limitations on rights into account in the general case, though, as that
4625 * would require it to always return false and defeat the purpose.
4626 * Specifically, session-based rights restrictions (such as OAuth or bot
4627 * passwords) are applied based on the current session.
4630 * @param string $right Right to check
4633 public static function isEveryoneAllowed( $right ) {
4634 global $wgGroupPermissions, $wgRevokePermissions;
4637 // Use the cached results, except in unit tests which rely on
4638 // being able change the permission mid-request
4639 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4640 return $cache[$right];
4643 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4644 $cache[$right] = false;
4648 // If it's revoked anywhere, then everyone doesn't have it
4649 foreach ( $wgRevokePermissions as $rights ) {
4650 if ( isset( $rights[$right] ) && $rights[$right] ) {
4651 $cache[$right] = false;
4656 // Remove any rights that aren't allowed to the global-session user,
4657 // unless there are no sessions for this endpoint.
4658 if ( !defined( 'MW_NO_SESSION' ) ) {
4659 $allowedRights = SessionManager
::getGlobalSession()->getAllowedUserRights();
4660 if ( $allowedRights !== null && !in_array( $right, $allowedRights, true ) ) {
4661 $cache[$right] = false;
4666 // Allow extensions to say false
4667 if ( !Hooks
::run( 'UserIsEveryoneAllowed', [ $right ] ) ) {
4668 $cache[$right] = false;
4672 $cache[$right] = true;
4677 * Get the localized descriptive name for a group, if it exists
4679 * @param string $group Internal group name
4680 * @return string Localized descriptive group name
4682 public static function getGroupName( $group ) {
4683 $msg = wfMessage( "group-$group" );
4684 return $msg->isBlank() ?
$group : $msg->text();
4688 * Get the localized descriptive name for a member of a group, if it exists
4690 * @param string $group Internal group name
4691 * @param string $username Username for gender (since 1.19)
4692 * @return string Localized name for group member
4694 public static function getGroupMember( $group, $username = '#' ) {
4695 $msg = wfMessage( "group-$group-member", $username );
4696 return $msg->isBlank() ?
$group : $msg->text();
4700 * Return the set of defined explicit groups.
4701 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4702 * are not included, as they are defined automatically, not in the database.
4703 * @return array Array of internal group names
4705 public static function getAllGroups() {
4706 global $wgGroupPermissions, $wgRevokePermissions;
4708 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4709 self
::getImplicitGroups()
4714 * Get a list of all available permissions.
4715 * @return string[] Array of permission names
4717 public static function getAllRights() {
4718 if ( self
::$mAllRights === false ) {
4719 global $wgAvailableRights;
4720 if ( count( $wgAvailableRights ) ) {
4721 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
4723 self
::$mAllRights = self
::$mCoreRights;
4725 Hooks
::run( 'UserGetAllRights', [ &self
::$mAllRights ] );
4727 return self
::$mAllRights;
4731 * Get a list of implicit groups
4732 * @return array Array of Strings Array of internal group names
4734 public static function getImplicitGroups() {
4735 global $wgImplicitGroups;
4737 $groups = $wgImplicitGroups;
4738 # Deprecated, use $wgImplicitGroups instead
4739 Hooks
::run( 'UserGetImplicitGroups', [ &$groups ], '1.25' );
4745 * Get the title of a page describing a particular group
4747 * @param string $group Internal group name
4748 * @return Title|bool Title of the page if it exists, false otherwise
4750 public static function getGroupPage( $group ) {
4751 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4752 if ( $msg->exists() ) {
4753 $title = Title
::newFromText( $msg->text() );
4754 if ( is_object( $title ) ) {
4762 * Create a link to the group in HTML, if available;
4763 * else return the group name.
4765 * @param string $group Internal name of the group
4766 * @param string $text The text of the link
4767 * @return string HTML link to the group
4769 public static function makeGroupLinkHTML( $group, $text = '' ) {
4770 if ( $text == '' ) {
4771 $text = self
::getGroupName( $group );
4773 $title = self
::getGroupPage( $group );
4775 return Linker
::link( $title, htmlspecialchars( $text ) );
4777 return htmlspecialchars( $text );
4782 * Create a link to the group in Wikitext, if available;
4783 * else return the group name.
4785 * @param string $group Internal name of the group
4786 * @param string $text The text of the link
4787 * @return string Wikilink to the group
4789 public static function makeGroupLinkWiki( $group, $text = '' ) {
4790 if ( $text == '' ) {
4791 $text = self
::getGroupName( $group );
4793 $title = self
::getGroupPage( $group );
4795 $page = $title->getFullText();
4796 return "[[$page|$text]]";
4803 * Returns an array of the groups that a particular group can add/remove.
4805 * @param string $group The group to check for whether it can add/remove
4806 * @return array Array( 'add' => array( addablegroups ),
4807 * 'remove' => array( removablegroups ),
4808 * 'add-self' => array( addablegroups to self),
4809 * 'remove-self' => array( removable groups from self) )
4811 public static function changeableByGroup( $group ) {
4812 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4821 if ( empty( $wgAddGroups[$group] ) ) {
4822 // Don't add anything to $groups
4823 } elseif ( $wgAddGroups[$group] === true ) {
4824 // You get everything
4825 $groups['add'] = self
::getAllGroups();
4826 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4827 $groups['add'] = $wgAddGroups[$group];
4830 // Same thing for remove
4831 if ( empty( $wgRemoveGroups[$group] ) ) {
4833 } elseif ( $wgRemoveGroups[$group] === true ) {
4834 $groups['remove'] = self
::getAllGroups();
4835 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4836 $groups['remove'] = $wgRemoveGroups[$group];
4839 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4840 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4841 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4842 if ( is_int( $key ) ) {
4843 $wgGroupsAddToSelf['user'][] = $value;
4848 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
4849 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4850 if ( is_int( $key ) ) {
4851 $wgGroupsRemoveFromSelf['user'][] = $value;
4856 // Now figure out what groups the user can add to him/herself
4857 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4859 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4860 // No idea WHY this would be used, but it's there
4861 $groups['add-self'] = User
::getAllGroups();
4862 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4863 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4866 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4868 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4869 $groups['remove-self'] = User
::getAllGroups();
4870 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4871 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4878 * Returns an array of groups that this user can add and remove
4879 * @return array Array( 'add' => array( addablegroups ),
4880 * 'remove' => array( removablegroups ),
4881 * 'add-self' => array( addablegroups to self),
4882 * 'remove-self' => array( removable groups from self) )
4884 public function changeableGroups() {
4885 if ( $this->isAllowed( 'userrights' ) ) {
4886 // This group gives the right to modify everything (reverse-
4887 // compatibility with old "userrights lets you change
4889 // Using array_merge to make the groups reindexed
4890 $all = array_merge( User
::getAllGroups() );
4899 // Okay, it's not so simple, we will have to go through the arrays
4906 $addergroups = $this->getEffectiveGroups();
4908 foreach ( $addergroups as $addergroup ) {
4909 $groups = array_merge_recursive(
4910 $groups, $this->changeableByGroup( $addergroup )
4912 $groups['add'] = array_unique( $groups['add'] );
4913 $groups['remove'] = array_unique( $groups['remove'] );
4914 $groups['add-self'] = array_unique( $groups['add-self'] );
4915 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4921 * Deferred version of incEditCountImmediate()
4923 public function incEditCount() {
4924 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle( function() {
4925 $this->incEditCountImmediate();
4930 * Increment the user's edit-count field.
4931 * Will have no effect for anonymous users.
4934 public function incEditCountImmediate() {
4935 if ( $this->isAnon() ) {
4939 $dbw = wfGetDB( DB_MASTER
);
4940 // No rows will be "affected" if user_editcount is NULL
4943 [ 'user_editcount=user_editcount+1' ],
4944 [ 'user_id' => $this->getId(), 'user_editcount IS NOT NULL' ],
4947 // Lazy initialization check...
4948 if ( $dbw->affectedRows() == 0 ) {
4949 // Now here's a goddamn hack...
4950 $dbr = wfGetDB( DB_SLAVE
);
4951 if ( $dbr !== $dbw ) {
4952 // If we actually have a slave server, the count is
4953 // at least one behind because the current transaction
4954 // has not been committed and replicated.
4955 $this->initEditCount( 1 );
4957 // But if DB_SLAVE is selecting the master, then the
4958 // count we just read includes the revision that was
4959 // just added in the working transaction.
4960 $this->initEditCount();
4963 // Edit count in user cache too
4964 $this->invalidateCache();
4968 * Initialize user_editcount from data out of the revision table
4970 * @param int $add Edits to add to the count from the revision table
4971 * @return int Number of edits
4973 protected function initEditCount( $add = 0 ) {
4974 // Pull from a slave to be less cruel to servers
4975 // Accuracy isn't the point anyway here
4976 $dbr = wfGetDB( DB_SLAVE
);
4977 $count = (int)$dbr->selectField(
4980 [ 'rev_user' => $this->getId() ],
4983 $count = $count +
$add;
4985 $dbw = wfGetDB( DB_MASTER
);
4988 [ 'user_editcount' => $count ],
4989 [ 'user_id' => $this->getId() ],
4997 * Get the description of a given right
4999 * @param string $right Right to query
5000 * @return string Localized description of the right
5002 public static function getRightDescription( $right ) {
5003 $key = "right-$right";
5004 $msg = wfMessage( $key );
5005 return $msg->isBlank() ?
$right : $msg->text();
5009 * Make a new-style password hash
5011 * @param string $password Plain-text password
5012 * @param bool|string $salt Optional salt, may be random or the user ID.
5013 * If unspecified or false, will generate one automatically
5014 * @return string Password hash
5015 * @deprecated since 1.24, use Password class
5017 public static function crypt( $password, $salt = false ) {
5018 wfDeprecated( __METHOD__
, '1.24' );
5019 $passwordFactory = new PasswordFactory();
5020 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
5021 $hash = $passwordFactory->newFromPlaintext( $password );
5022 return $hash->toString();
5026 * Compare a password hash with a plain-text password. Requires the user
5027 * ID if there's a chance that the hash is an old-style hash.
5029 * @param string $hash Password hash
5030 * @param string $password Plain-text password to compare
5031 * @param string|bool $userId User ID for old-style password salt
5034 * @deprecated since 1.24, use Password class
5036 public static function comparePasswords( $hash, $password, $userId = false ) {
5037 wfDeprecated( __METHOD__
, '1.24' );
5039 // Check for *really* old password hashes that don't even have a type
5040 // The old hash format was just an md5 hex hash, with no type information
5041 if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) {
5042 global $wgPasswordSalt;
5043 if ( $wgPasswordSalt ) {
5044 $password = ":B:{$userId}:{$hash}";
5046 $password = ":A:{$hash}";
5050 $passwordFactory = new PasswordFactory();
5051 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
5052 $hash = $passwordFactory->newFromCiphertext( $hash );
5053 return $hash->equals( $password );
5057 * Add a newuser log entry for this user.
5058 * Before 1.19 the return value was always true.
5060 * @param string|bool $action Account creation type.
5061 * - String, one of the following values:
5062 * - 'create' for an anonymous user creating an account for himself.
5063 * This will force the action's performer to be the created user itself,
5064 * no matter the value of $wgUser
5065 * - 'create2' for a logged in user creating an account for someone else
5066 * - 'byemail' when the created user will receive its password by e-mail
5067 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
5068 * - Boolean means whether the account was created by e-mail (deprecated):
5069 * - true will be converted to 'byemail'
5070 * - false will be converted to 'create' if this object is the same as
5071 * $wgUser and to 'create2' otherwise
5073 * @param string $reason User supplied reason
5075 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
5077 public function addNewUserLogEntry( $action = false, $reason = '' ) {
5078 global $wgUser, $wgNewUserLog;
5079 if ( empty( $wgNewUserLog ) ) {
5080 return true; // disabled
5083 if ( $action === true ) {
5084 $action = 'byemail';
5085 } elseif ( $action === false ) {
5086 if ( $this->equals( $wgUser ) ) {
5089 $action = 'create2';
5093 if ( $action === 'create' ||
$action === 'autocreate' ) {
5096 $performer = $wgUser;
5099 $logEntry = new ManualLogEntry( 'newusers', $action );
5100 $logEntry->setPerformer( $performer );
5101 $logEntry->setTarget( $this->getUserPage() );
5102 $logEntry->setComment( $reason );
5103 $logEntry->setParameters( [
5104 '4::userid' => $this->getId(),
5106 $logid = $logEntry->insert();
5108 if ( $action !== 'autocreate' ) {
5109 $logEntry->publish( $logid );
5116 * Add an autocreate newuser log entry for this user
5117 * Used by things like CentralAuth and perhaps other authplugins.
5118 * Consider calling addNewUserLogEntry() directly instead.
5122 public function addNewUserLogEntryAutoCreate() {
5123 $this->addNewUserLogEntry( 'autocreate' );
5129 * Load the user options either from cache, the database or an array
5131 * @param array $data Rows for the current user out of the user_properties table
5133 protected function loadOptions( $data = null ) {
5138 if ( $this->mOptionsLoaded
) {
5142 $this->mOptions
= self
::getDefaultOptions();
5144 if ( !$this->getId() ) {
5145 // For unlogged-in users, load language/variant options from request.
5146 // There's no need to do it for logged-in users: they can set preferences,
5147 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5148 // so don't override user's choice (especially when the user chooses site default).
5149 $variant = $wgContLang->getDefaultVariant();
5150 $this->mOptions
['variant'] = $variant;
5151 $this->mOptions
['language'] = $variant;
5152 $this->mOptionsLoaded
= true;
5156 // Maybe load from the object
5157 if ( !is_null( $this->mOptionOverrides
) ) {
5158 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5159 foreach ( $this->mOptionOverrides
as $key => $value ) {
5160 $this->mOptions
[$key] = $value;
5163 if ( !is_array( $data ) ) {
5164 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5165 // Load from database
5166 $dbr = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
5167 ?
wfGetDB( DB_MASTER
)
5168 : wfGetDB( DB_SLAVE
);
5170 $res = $dbr->select(
5172 [ 'up_property', 'up_value' ],
5173 [ 'up_user' => $this->getId() ],
5177 $this->mOptionOverrides
= [];
5179 foreach ( $res as $row ) {
5180 $data[$row->up_property
] = $row->up_value
;
5183 foreach ( $data as $property => $value ) {
5184 $this->mOptionOverrides
[$property] = $value;
5185 $this->mOptions
[$property] = $value;
5189 $this->mOptionsLoaded
= true;
5191 Hooks
::run( 'UserLoadOptions', [ $this, &$this->mOptions
] );
5195 * Saves the non-default options for this user, as previously set e.g. via
5196 * setOption(), in the database's "user_properties" (preferences) table.
5197 * Usually used via saveSettings().
5199 protected function saveOptions() {
5200 $this->loadOptions();
5202 // Not using getOptions(), to keep hidden preferences in database
5203 $saveOptions = $this->mOptions
;
5205 // Allow hooks to abort, for instance to save to a global profile.
5206 // Reset options to default state before saving.
5207 if ( !Hooks
::run( 'UserSaveOptions', [ $this, &$saveOptions ] ) ) {
5211 $userId = $this->getId();
5213 $insert_rows = []; // all the new preference rows
5214 foreach ( $saveOptions as $key => $value ) {
5215 // Don't bother storing default values
5216 $defaultOption = self
::getDefaultOption( $key );
5217 if ( ( $defaultOption === null && $value !== false && $value !== null )
5218 ||
$value != $defaultOption
5221 'up_user' => $userId,
5222 'up_property' => $key,
5223 'up_value' => $value,
5228 $dbw = wfGetDB( DB_MASTER
);
5230 $res = $dbw->select( 'user_properties',
5231 [ 'up_property', 'up_value' ], [ 'up_user' => $userId ], __METHOD__
);
5233 // Find prior rows that need to be removed or updated. These rows will
5234 // all be deleted (the later so that INSERT IGNORE applies the new values).
5236 foreach ( $res as $row ) {
5237 if ( !isset( $saveOptions[$row->up_property
] )
5238 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
5240 $keysDelete[] = $row->up_property
;
5244 if ( count( $keysDelete ) ) {
5245 // Do the DELETE by PRIMARY KEY for prior rows.
5246 // In the past a very large portion of calls to this function are for setting
5247 // 'rememberpassword' for new accounts (a preference that has since been removed).
5248 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5249 // caused gap locks on [max user ID,+infinity) which caused high contention since
5250 // updates would pile up on each other as they are for higher (newer) user IDs.
5251 // It might not be necessary these days, but it shouldn't hurt either.
5252 $dbw->delete( 'user_properties',
5253 [ 'up_user' => $userId, 'up_property' => $keysDelete ], __METHOD__
);
5255 // Insert the new preference rows
5256 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, [ 'IGNORE' ] );
5260 * Lazily instantiate and return a factory object for making passwords
5262 * @deprecated since 1.27, create a PasswordFactory directly instead
5263 * @return PasswordFactory
5265 public static function getPasswordFactory() {
5266 wfDeprecated( __METHOD__
, '1.27' );
5267 $ret = new PasswordFactory();
5268 $ret->init( RequestContext
::getMain()->getConfig() );
5273 * Provide an array of HTML5 attributes to put on an input element
5274 * intended for the user to enter a new password. This may include
5275 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
5277 * Do *not* use this when asking the user to enter his current password!
5278 * Regardless of configuration, users may have invalid passwords for whatever
5279 * reason (e.g., they were set before requirements were tightened up).
5280 * Only use it when asking for a new password, like on account creation or
5283 * Obviously, you still need to do server-side checking.
5285 * NOTE: A combination of bugs in various browsers means that this function
5286 * actually just returns array() unconditionally at the moment. May as
5287 * well keep it around for when the browser bugs get fixed, though.
5289 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
5291 * @deprecated since 1.27
5292 * @return array Array of HTML attributes suitable for feeding to
5293 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
5294 * That will get confused by the boolean attribute syntax used.)
5296 public static function passwordChangeInputAttribs() {
5297 global $wgMinimalPasswordLength;
5299 if ( $wgMinimalPasswordLength == 0 ) {
5303 # Note that the pattern requirement will always be satisfied if the
5304 # input is empty, so we need required in all cases.
5306 # @todo FIXME: Bug 23769: This needs to not claim the password is required
5307 # if e-mail confirmation is being used. Since HTML5 input validation
5308 # is b0rked anyway in some browsers, just return nothing. When it's
5309 # re-enabled, fix this code to not output required for e-mail
5311 # $ret = array( 'required' );
5314 # We can't actually do this right now, because Opera 9.6 will print out
5315 # the entered password visibly in its error message! When other
5316 # browsers add support for this attribute, or Opera fixes its support,
5317 # we can add support with a version check to avoid doing this on Opera
5318 # versions where it will be a problem. Reported to Opera as
5319 # DSK-262266, but they don't have a public bug tracker for us to follow.
5321 if ( $wgMinimalPasswordLength > 1 ) {
5322 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
5323 $ret['title'] = wfMessage( 'passwordtooshort' )
5324 ->numParams( $wgMinimalPasswordLength )->text();
5332 * Return the list of user fields that should be selected to create
5333 * a new user object.
5336 public static function selectFields() {
5344 'user_email_authenticated',
5346 'user_email_token_expires',
5347 'user_registration',
5353 * Factory function for fatal permission-denied errors
5356 * @param string $permission User right required
5359 static function newFatalPermissionDeniedStatus( $permission ) {
5362 $groups = array_map(
5363 [ 'User', 'makeGroupLinkWiki' ],
5364 User
::getGroupsWithPermission( $permission )
5368 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5370 return Status
::newFatal( 'badaccess-group0' );
5375 * Get a new instance of this user that was loaded from the master via a locking read
5377 * Use this instead of the main context User when updating that user. This avoids races
5378 * where that user was loaded from a slave or even the master but without proper locks.
5380 * @return User|null Returns null if the user was not found in the DB
5383 public function getInstanceForUpdate() {
5384 if ( !$this->getId() ) {
5385 return null; // anon
5388 $user = self
::newFromId( $this->getId() );
5389 if ( !$user->loadFromId( self
::READ_EXCLUSIVE
) ) {
5397 * Checks if two user objects point to the same user.
5403 public function equals( User
$user ) {
5404 return $this->getName() === $user->getName();