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 * Exclude user options that are set to their default value.
69 const GETOPTIONS_EXCLUDE_DEFAULTS
= 1;
74 const CHECK_USER_RIGHTS
= true;
79 const IGNORE_USER_RIGHTS
= false;
82 * Array of Strings List of member variables which are saved to the
83 * shared cache (memcached). Any operation which changes the
84 * corresponding database fields must call a cache-clearing function.
87 protected static $mCacheVars = [
95 'mEmailAuthenticated',
102 // user_properties table
107 * Array of Strings Core rights.
108 * Each of these should have a corresponding message of the form
112 protected static $mCoreRights = [
142 'editusercssjs', # deprecated
155 'move-categorypages',
156 'move-rootuserpages',
160 'override-export-depth',
183 'userrights-interwiki',
191 * String Cached results of getAllRights()
193 protected static $mAllRights = false;
196 * An in-process cache for user data lookup
199 protected static $inProcessCache;
201 /** Cache variables */
211 /** @var string TS_MW timestamp from the DB */
213 /** @var string TS_MW timestamp from cache */
214 protected $mQuickTouched;
218 public $mEmailAuthenticated;
220 protected $mEmailToken;
222 protected $mEmailTokenExpires;
224 protected $mRegistration;
226 protected $mEditCount;
230 protected $mOptionOverrides;
234 * Bool Whether the cache variables have been loaded.
237 public $mOptionsLoaded;
240 * Array with already loaded items or true if all items have been loaded.
242 protected $mLoadedItems = [];
246 * String Initialization data source if mLoadedItems!==true. May be one of:
247 * - 'defaults' anonymous user initialised from class defaults
248 * - 'name' initialise from mName
249 * - 'id' initialise from mId
250 * - 'session' log in from session if possible
252 * Use the User::newFrom*() family of functions to set this.
257 * Lazy-initialized variables, invalidated with clearInstanceCache
261 protected $mDatePreference;
269 protected $mBlockreason;
271 protected $mEffectiveGroups;
273 protected $mImplicitGroups;
275 protected $mFormerGroups;
277 protected $mBlockedGlobally;
294 protected $mAllowUsertalk;
297 private $mBlockedFromCreateAccount = false;
299 /** @var integer User::READ_* constant bitfield used to load data */
300 protected $queryFlagsUsed = self
::READ_NORMAL
;
302 public static $idCacheByName = [];
305 * Lightweight constructor for an anonymous user.
306 * Use the User::newFrom* factory functions for other kinds of users.
310 * @see newFromConfirmationCode()
311 * @see newFromSession()
314 public function __construct() {
315 $this->clearInstanceCache( 'defaults' );
321 public function __toString() {
322 return $this->getName();
326 * Test if it's safe to load this User object.
328 * You should typically check this before using $wgUser or
329 * RequestContext::getUser in a method that might be called before the
330 * system has been fully initialized. If the object is unsafe, you should
331 * use an anonymous user:
333 * $user = $wgUser->isSafeToLoad() ? $wgUser : new User;
339 public function isSafeToLoad() {
340 global $wgFullyInitialised;
342 // The user is safe to load if:
343 // * MW_NO_SESSION is undefined AND $wgFullyInitialised is true (safe to use session data)
344 // * mLoadedItems === true (already loaded)
345 // * mFrom !== 'session' (sessions not involved at all)
347 return ( !defined( 'MW_NO_SESSION' ) && $wgFullyInitialised ) ||
348 $this->mLoadedItems
=== true ||
$this->mFrom
!== 'session';
352 * Load the user table data for this object from the source given by mFrom.
354 * @param integer $flags User::READ_* constant bitfield
356 public function load( $flags = self
::READ_NORMAL
) {
357 global $wgFullyInitialised;
359 if ( $this->mLoadedItems
=== true ) {
363 // Set it now to avoid infinite recursion in accessors
364 $oldLoadedItems = $this->mLoadedItems
;
365 $this->mLoadedItems
= true;
366 $this->queryFlagsUsed
= $flags;
368 // If this is called too early, things are likely to break.
369 if ( !$wgFullyInitialised && $this->mFrom
=== 'session' ) {
370 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
371 ->warning( 'User::loadFromSession called before the end of Setup.php', [
372 'exception' => new Exception( 'User::loadFromSession called before the end of Setup.php' ),
374 $this->loadDefaults();
375 $this->mLoadedItems
= $oldLoadedItems;
379 switch ( $this->mFrom
) {
381 $this->loadDefaults();
384 // Make sure this thread sees its own changes
385 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
386 $flags |
= self
::READ_LATEST
;
387 $this->queryFlagsUsed
= $flags;
390 $this->mId
= self
::idFromName( $this->mName
, $flags );
392 // Nonexistent user placeholder object
393 $this->loadDefaults( $this->mName
);
395 $this->loadFromId( $flags );
399 $this->loadFromId( $flags );
402 if ( !$this->loadFromSession() ) {
403 // Loading from session failed. Load defaults.
404 $this->loadDefaults();
406 Hooks
::run( 'UserLoadAfterLoadFromSession', [ $this ] );
409 throw new UnexpectedValueException(
410 "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
415 * Load user table data, given mId has already been set.
416 * @param integer $flags User::READ_* constant bitfield
417 * @return bool False if the ID does not exist, true otherwise
419 public function loadFromId( $flags = self
::READ_NORMAL
) {
420 if ( $this->mId
== 0 ) {
421 $this->loadDefaults();
425 // Try cache (unless this needs data from the master DB).
426 // NOTE: if this thread called saveSettings(), the cache was cleared.
427 $latest = DBAccessObjectUtils
::hasFlags( $flags, self
::READ_LATEST
);
428 if ( $latest ||
!$this->loadFromCache() ) {
429 wfDebug( "User: cache miss for user {$this->mId}\n" );
430 // Load from DB (make sure this thread sees its own changes)
431 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
432 $flags |
= self
::READ_LATEST
;
434 if ( !$this->loadFromDatabase( $flags ) ) {
435 // Can't load from ID, user is anonymous
438 $this->saveToCache();
441 $this->mLoadedItems
= true;
442 $this->queryFlagsUsed
= $flags;
449 * @param string $wikiId
450 * @param integer $userId
452 public static function purge( $wikiId, $userId ) {
453 $cache = ObjectCache
::getMainWANInstance();
454 $processCache = self
::getInProcessCache();
455 $key = $cache->makeGlobalKey( 'user', 'id', $wikiId, $userId );
456 $cache->delete( $key );
457 $processCache->delete( $key );
462 * @param WANObjectCache $cache
465 protected function getCacheKey( WANObjectCache
$cache ) {
466 return $cache->makeGlobalKey( 'user', 'id', wfWikiID(), $this->mId
);
471 * @return HashBagOStuff
473 protected static function getInProcessCache() {
474 if ( !self
::$inProcessCache ) {
475 self
::$inProcessCache = new HashBagOStuff( ['maxKeys' => 10] );
477 return self
::$inProcessCache;
481 * Load user data from shared cache, given mId has already been set.
483 * @return bool false if the ID does not exist or data is invalid, true otherwise
486 protected function loadFromCache() {
487 if ( $this->mId
== 0 ) {
488 $this->loadDefaults();
492 $cache = ObjectCache
::getMainWANInstance();
493 $processCache = self
::getInProcessCache();
494 $key = $this->getCacheKey( $cache );
495 $data = $processCache->get( $key );
496 if ( !is_array( $data ) ) {
497 $data = $cache->get( $key );
498 if ( !is_array( $data ) ||
$data['mVersion'] < self
::VERSION
) {
502 $processCache->set( $key, $data );
504 wfDebug( "User: got user {$this->mId} from cache\n" );
506 // Restore from cache
507 foreach ( self
::$mCacheVars as $name ) {
508 $this->$name = $data[$name];
515 * Save user data to the shared cache
517 * This method should not be called outside the User class
519 public function saveToCache() {
522 $this->loadOptions();
524 if ( $this->isAnon() ) {
525 // Anonymous users are uncached
530 foreach ( self
::$mCacheVars as $name ) {
531 $data[$name] = $this->$name;
533 $data['mVersion'] = self
::VERSION
;
534 $opts = Database
::getCacheSetOptions( wfGetDB( DB_SLAVE
) );
536 $cache = ObjectCache
::getMainWANInstance();
537 $processCache = self
::getInProcessCache();
538 $key = $this->getCacheKey( $cache );
539 $cache->set( $key, $data, $cache::TTL_HOUR
, $opts );
540 $processCache->set( $key, $data );
543 /** @name newFrom*() static factory methods */
547 * Static factory method for creation from username.
549 * This is slightly less efficient than newFromId(), so use newFromId() if
550 * you have both an ID and a name handy.
552 * @param string $name Username, validated by Title::newFromText()
553 * @param string|bool $validate Validate username. Takes the same parameters as
554 * User::getCanonicalName(), except that true is accepted as an alias
555 * for 'valid', for BC.
557 * @return User|bool User object, or false if the username is invalid
558 * (e.g. if it contains illegal characters or is an IP address). If the
559 * username is not present in the database, the result will be a user object
560 * with a name, zero user ID and default settings.
562 public static function newFromName( $name, $validate = 'valid' ) {
563 if ( $validate === true ) {
566 $name = self
::getCanonicalName( $name, $validate );
567 if ( $name === false ) {
570 // Create unloaded user object
574 $u->setItemLoaded( 'name' );
580 * Static factory method for creation from a given user ID.
582 * @param int $id Valid user ID
583 * @return User The corresponding User object
585 public static function newFromId( $id ) {
589 $u->setItemLoaded( 'id' );
594 * Factory method to fetch whichever user has a given email confirmation code.
595 * This code is generated when an account is created or its e-mail address
598 * If the code is invalid or has expired, returns NULL.
600 * @param string $code Confirmation code
601 * @param int $flags User::READ_* bitfield
604 public static function newFromConfirmationCode( $code, $flags = 0 ) {
605 $db = ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
606 ?
wfGetDB( DB_MASTER
)
607 : wfGetDB( DB_SLAVE
);
609 $id = $db->selectField(
613 'user_email_token' => md5( $code ),
614 'user_email_token_expires > ' . $db->addQuotes( $db->timestamp() ),
618 return $id ? User
::newFromId( $id ) : null;
622 * Create a new user object using data from session. If the login
623 * credentials are invalid, the result is an anonymous user.
625 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
628 public static function newFromSession( WebRequest
$request = null ) {
630 $user->mFrom
= 'session';
631 $user->mRequest
= $request;
636 * Create a new user object from a user row.
637 * The row should have the following fields from the user table in it:
638 * - either user_name or user_id to load further data if needed (or both)
640 * - all other fields (email, etc.)
641 * It is useless to provide the remaining fields if either user_id,
642 * user_name and user_real_name are not provided because the whole row
643 * will be loaded once more from the database when accessing them.
645 * @param stdClass $row A row from the user table
646 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
649 public static function newFromRow( $row, $data = null ) {
651 $user->loadFromRow( $row, $data );
656 * Static factory method for creation of a "system" user from username.
658 * A "system" user is an account that's used to attribute logged actions
659 * taken by MediaWiki itself, as opposed to a bot or human user. Examples
660 * might include the 'Maintenance script' or 'Conversion script' accounts
661 * used by various scripts in the maintenance/ directory or accounts such
662 * as 'MediaWiki message delivery' used by the MassMessage extension.
664 * This can optionally create the user if it doesn't exist, and "steal" the
665 * account if it does exist.
667 * @param string $name Username
668 * @param array $options Options are:
669 * - validate: As for User::getCanonicalName(), default 'valid'
670 * - create: Whether to create the user if it doesn't already exist, default true
671 * - steal: Whether to reset the account's password and email if it
672 * already exists, default false
675 public static function newSystemUser( $name, $options = [] ) {
677 'validate' => 'valid',
682 $name = self
::getCanonicalName( $name, $options['validate'] );
683 if ( $name === false ) {
687 $dbw = wfGetDB( DB_MASTER
);
688 $row = $dbw->selectRow(
691 self
::selectFields(),
692 [ 'user_password', 'user_newpassword' ]
694 [ 'user_name' => $name ],
698 // No user. Create it?
699 return $options['create'] ? self
::createNew( $name ) : null;
701 $user = self
::newFromRow( $row );
703 // A user is considered to exist as a non-system user if it has a
704 // password set, or a temporary password set, or an email set, or a
705 // non-invalid token.
706 $passwordFactory = new PasswordFactory();
707 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
709 $password = $passwordFactory->newFromCiphertext( $row->user_password
);
710 } catch ( PasswordError
$e ) {
711 wfDebug( 'Invalid password hash found in database.' );
712 $password = PasswordFactory
::newInvalidPassword();
715 $newpassword = $passwordFactory->newFromCiphertext( $row->user_newpassword
);
716 } catch ( PasswordError
$e ) {
717 wfDebug( 'Invalid password hash found in database.' );
718 $newpassword = PasswordFactory
::newInvalidPassword();
720 if ( !$password instanceof InvalidPassword ||
!$newpassword instanceof InvalidPassword
721 ||
$user->mEmail ||
$user->mToken
!== self
::INVALID_TOKEN
723 // User exists. Steal it?
724 if ( !$options['steal'] ) {
728 $nopass = PasswordFactory
::newInvalidPassword()->toString();
733 'user_password' => $nopass,
734 'user_newpassword' => $nopass,
735 'user_newpass_time' => null,
737 [ 'user_id' => $user->getId() ],
740 $user->invalidateEmail();
741 $user->mToken
= self
::INVALID_TOKEN
;
742 $user->saveSettings();
743 SessionManager
::singleton()->preventSessionsForUser( $user->getName() );
752 * Get the username corresponding to a given user ID
753 * @param int $id User ID
754 * @return string|bool The corresponding username
756 public static function whoIs( $id ) {
757 return UserCache
::singleton()->getProp( $id, 'name' );
761 * Get the real name of a user given their user ID
763 * @param int $id User ID
764 * @return string|bool The corresponding user's real name
766 public static function whoIsReal( $id ) {
767 return UserCache
::singleton()->getProp( $id, 'real_name' );
771 * Get database id given a user name
772 * @param string $name Username
773 * @param integer $flags User::READ_* constant bitfield
774 * @return int|null The corresponding user's ID, or null if user is nonexistent
776 public static function idFromName( $name, $flags = self
::READ_NORMAL
) {
777 $nt = Title
::makeTitleSafe( NS_USER
, $name );
778 if ( is_null( $nt ) ) {
783 if ( !( $flags & self
::READ_LATEST
) && isset( self
::$idCacheByName[$name] ) ) {
784 return self
::$idCacheByName[$name];
787 $db = ( $flags & self
::READ_LATEST
)
788 ?
wfGetDB( DB_MASTER
)
789 : wfGetDB( DB_SLAVE
);
794 [ 'user_name' => $nt->getText() ],
798 if ( $s === false ) {
801 $result = $s->user_id
;
804 self
::$idCacheByName[$name] = $result;
806 if ( count( self
::$idCacheByName ) > 1000 ) {
807 self
::$idCacheByName = [];
814 * Reset the cache used in idFromName(). For use in tests.
816 public static function resetIdByNameCache() {
817 self
::$idCacheByName = [];
821 * Does the string match an anonymous IPv4 address?
823 * This function exists for username validation, in order to reject
824 * usernames which are similar in form to IP addresses. Strings such
825 * as 300.300.300.300 will return true because it looks like an IP
826 * address, despite not being strictly valid.
828 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
829 * address because the usemod software would "cloak" anonymous IP
830 * addresses like this, if we allowed accounts like this to be created
831 * new users could get the old edits of these anonymous users.
833 * @param string $name Name to match
836 public static function isIP( $name ) {
837 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
838 || IP
::isIPv6( $name );
842 * Is the input a valid username?
844 * Checks if the input is a valid username, we don't want an empty string,
845 * an IP address, anything that contains slashes (would mess up subpages),
846 * is longer than the maximum allowed username size or doesn't begin with
849 * @param string $name Name to match
852 public static function isValidUserName( $name ) {
853 global $wgContLang, $wgMaxNameChars;
856 || User
::isIP( $name )
857 ||
strpos( $name, '/' ) !== false
858 ||
strlen( $name ) > $wgMaxNameChars
859 ||
$name != $wgContLang->ucfirst( $name )
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() ) ) {
873 // Check an additional blacklist of troublemaker characters.
874 // Should these be merged into the title char list?
875 $unicodeBlacklist = '/[' .
876 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
877 '\x{00a0}' . # non-breaking space
878 '\x{2000}-\x{200f}' . # various whitespace
879 '\x{2028}-\x{202f}' . # breaks and control chars
880 '\x{3000}' . # ideographic space
881 '\x{e000}-\x{f8ff}' . # private use
883 if ( preg_match( $unicodeBlacklist, $name ) ) {
891 * Usernames which fail to pass this function will be blocked
892 * from user login and new account registrations, but may be used
893 * internally by batch processes.
895 * If an account already exists in this form, login will be blocked
896 * by a failure to pass this function.
898 * @param string $name Name to match
901 public static function isUsableName( $name ) {
902 global $wgReservedUsernames;
903 // Must be a valid username, obviously ;)
904 if ( !self
::isValidUserName( $name ) ) {
908 static $reservedUsernames = false;
909 if ( !$reservedUsernames ) {
910 $reservedUsernames = $wgReservedUsernames;
911 Hooks
::run( 'UserGetReservedNames', [ &$reservedUsernames ] );
914 // Certain names may be reserved for batch processes.
915 foreach ( $reservedUsernames as $reserved ) {
916 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
917 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
919 if ( $reserved == $name ) {
927 * Usernames which fail to pass this function will be blocked
928 * from new account registrations, but may be used internally
929 * either by batch processes or by user accounts which have
930 * already been created.
932 * Additional blacklisting may be added here rather than in
933 * isValidUserName() to avoid disrupting existing accounts.
935 * @param string $name String to match
938 public static function isCreatableName( $name ) {
939 global $wgInvalidUsernameCharacters;
941 // Ensure that the username isn't longer than 235 bytes, so that
942 // (at least for the builtin skins) user javascript and css files
943 // will work. (bug 23080)
944 if ( strlen( $name ) > 235 ) {
945 wfDebugLog( 'username', __METHOD__
.
946 ": '$name' invalid due to length" );
950 // Preg yells if you try to give it an empty string
951 if ( $wgInvalidUsernameCharacters !== '' ) {
952 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
953 wfDebugLog( 'username', __METHOD__
.
954 ": '$name' invalid due to wgInvalidUsernameCharacters" );
959 return self
::isUsableName( $name );
963 * Is the input a valid password for this user?
965 * @param string $password Desired password
968 public function isValidPassword( $password ) {
969 // simple boolean wrapper for getPasswordValidity
970 return $this->getPasswordValidity( $password ) === true;
974 * Given unvalidated password input, return error message on failure.
976 * @param string $password Desired password
977 * @return bool|string|array True on success, string or array of error message on failure
979 public function getPasswordValidity( $password ) {
980 $result = $this->checkPasswordValidity( $password );
981 if ( $result->isGood() ) {
985 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
986 $messages[] = $error['message'];
988 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
989 $messages[] = $warning['message'];
991 if ( count( $messages ) === 1 ) {
999 * Check if this is a valid password for this user
1001 * Create a Status object based on the password's validity.
1002 * The Status should be set to fatal if the user should not
1003 * be allowed to log in, and should have any errors that
1004 * would block changing the password.
1006 * If the return value of this is not OK, the password
1007 * should not be checked. If the return value is not Good,
1008 * the password can be checked, but the user should not be
1009 * able to set their password to this.
1011 * @param string $password Desired password
1012 * @param string $purpose one of 'login', 'create', 'reset'
1016 public function checkPasswordValidity( $password, $purpose = 'login' ) {
1017 global $wgPasswordPolicy;
1019 $upp = new UserPasswordPolicy(
1020 $wgPasswordPolicy['policies'],
1021 $wgPasswordPolicy['checks']
1024 $status = Status
::newGood();
1025 $result = false; // init $result to false for the internal checks
1027 if ( !Hooks
::run( 'isValidPassword', [ $password, &$result, $this ] ) ) {
1028 $status->error( $result );
1032 if ( $result === false ) {
1033 $status->merge( $upp->checkUserPassword( $this, $password, $purpose ) );
1035 } elseif ( $result === true ) {
1038 $status->error( $result );
1039 return $status; // the isValidPassword hook set a string $result and returned true
1044 * Given unvalidated user input, return a canonical username, or false if
1045 * the username is invalid.
1046 * @param string $name User input
1047 * @param string|bool $validate Type of validation to use:
1048 * - false No validation
1049 * - 'valid' Valid for batch processes
1050 * - 'usable' Valid for batch processes and login
1051 * - 'creatable' Valid for batch processes, login and account creation
1053 * @throws InvalidArgumentException
1054 * @return bool|string
1056 public static function getCanonicalName( $name, $validate = 'valid' ) {
1057 // Force usernames to capital
1059 $name = $wgContLang->ucfirst( $name );
1061 # Reject names containing '#'; these will be cleaned up
1062 # with title normalisation, but then it's too late to
1064 if ( strpos( $name, '#' ) !== false ) {
1068 // Clean up name according to title rules,
1069 // but only when validation is requested (bug 12654)
1070 $t = ( $validate !== false ) ?
1071 Title
::newFromText( $name ) : Title
::makeTitle( NS_USER
, $name );
1072 // Check for invalid titles
1073 if ( is_null( $t ) ) {
1077 // Reject various classes of invalid names
1079 $name = $wgAuth->getCanonicalName( $t->getText() );
1081 switch ( $validate ) {
1085 if ( !User
::isValidUserName( $name ) ) {
1090 if ( !User
::isUsableName( $name ) ) {
1095 if ( !User
::isCreatableName( $name ) ) {
1100 throw new InvalidArgumentException(
1101 'Invalid parameter value for $validate in ' . __METHOD__
);
1107 * Count the number of edits of a user
1109 * @param int $uid User ID to check
1110 * @return int The user's edit count
1112 * @deprecated since 1.21 in favour of User::getEditCount
1114 public static function edits( $uid ) {
1115 wfDeprecated( __METHOD__
, '1.21' );
1116 $user = self
::newFromId( $uid );
1117 return $user->getEditCount();
1121 * Return a random password.
1123 * @deprecated since 1.27, use PasswordFactory::generateRandomPasswordString()
1124 * @return string New random password
1126 public static function randomPassword() {
1127 global $wgMinimalPasswordLength;
1128 return PasswordFactory
::generateRandomPasswordString( $wgMinimalPasswordLength );
1132 * Set cached properties to default.
1134 * @note This no longer clears uncached lazy-initialised properties;
1135 * the constructor does that instead.
1137 * @param string|bool $name
1139 public function loadDefaults( $name = false ) {
1141 $this->mName
= $name;
1142 $this->mRealName
= '';
1144 $this->mOptionOverrides
= null;
1145 $this->mOptionsLoaded
= false;
1147 $loggedOut = $this->mRequest
&& !defined( 'MW_NO_SESSION' )
1148 ?
$this->mRequest
->getSession()->getLoggedOutTimestamp() : 0;
1149 if ( $loggedOut !== 0 ) {
1150 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1152 $this->mTouched
= '1'; # Allow any pages to be cached
1155 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1156 $this->mEmailAuthenticated
= null;
1157 $this->mEmailToken
= '';
1158 $this->mEmailTokenExpires
= null;
1159 $this->mRegistration
= wfTimestamp( TS_MW
);
1160 $this->mGroups
= [];
1162 Hooks
::run( 'UserLoadDefaults', [ $this, $name ] );
1166 * Return whether an item has been loaded.
1168 * @param string $item Item to check. Current possibilities:
1172 * @param string $all 'all' to check if the whole object has been loaded
1173 * or any other string to check if only the item is available (e.g.
1177 public function isItemLoaded( $item, $all = 'all' ) {
1178 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1179 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1183 * Set that an item has been loaded
1185 * @param string $item
1187 protected function setItemLoaded( $item ) {
1188 if ( is_array( $this->mLoadedItems
) ) {
1189 $this->mLoadedItems
[$item] = true;
1194 * Load user data from the session.
1196 * @return bool True if the user is logged in, false otherwise.
1198 private function loadFromSession() {
1201 Hooks
::run( 'UserLoadFromSession', [ $this, &$result ], '1.27' );
1202 if ( $result !== null ) {
1206 // MediaWiki\Session\Session already did the necessary authentication of the user
1207 // returned here, so just use it if applicable.
1208 $session = $this->getRequest()->getSession();
1209 $user = $session->getUser();
1210 if ( $user->isLoggedIn() ) {
1211 $this->loadFromUserObject( $user );
1212 // Other code expects these to be set in the session, so set them.
1213 $session->set( 'wsUserID', $this->getId() );
1214 $session->set( 'wsUserName', $this->getName() );
1215 $session->set( 'wsToken', $this->getToken() );
1223 * Load user and user_group data from the database.
1224 * $this->mId must be set, this is how the user is identified.
1226 * @param integer $flags User::READ_* constant bitfield
1227 * @return bool True if the user exists, false if the user is anonymous
1229 public function loadFromDatabase( $flags = self
::READ_LATEST
) {
1231 $this->mId
= intval( $this->mId
);
1234 if ( !$this->mId
) {
1235 $this->loadDefaults();
1239 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
1240 $db = wfGetDB( $index );
1242 $s = $db->selectRow(
1244 self
::selectFields(),
1245 [ 'user_id' => $this->mId
],
1250 $this->queryFlagsUsed
= $flags;
1251 Hooks
::run( 'UserLoadFromDatabase', [ $this, &$s ] );
1253 if ( $s !== false ) {
1254 // Initialise user table data
1255 $this->loadFromRow( $s );
1256 $this->mGroups
= null; // deferred
1257 $this->getEditCount(); // revalidation for nulls
1262 $this->loadDefaults();
1268 * Initialize this object from a row from the user table.
1270 * @param stdClass $row Row from the user table to load.
1271 * @param array $data Further user data to load into the object
1273 * user_groups Array with groups out of the user_groups table
1274 * user_properties Array with properties out of the user_properties table
1276 protected function loadFromRow( $row, $data = null ) {
1279 $this->mGroups
= null; // deferred
1281 if ( isset( $row->user_name
) ) {
1282 $this->mName
= $row->user_name
;
1283 $this->mFrom
= 'name';
1284 $this->setItemLoaded( 'name' );
1289 if ( isset( $row->user_real_name
) ) {
1290 $this->mRealName
= $row->user_real_name
;
1291 $this->setItemLoaded( 'realname' );
1296 if ( isset( $row->user_id
) ) {
1297 $this->mId
= intval( $row->user_id
);
1298 $this->mFrom
= 'id';
1299 $this->setItemLoaded( 'id' );
1304 if ( isset( $row->user_id
) && isset( $row->user_name
) ) {
1305 self
::$idCacheByName[$row->user_name
] = $row->user_id
;
1308 if ( isset( $row->user_editcount
) ) {
1309 $this->mEditCount
= $row->user_editcount
;
1314 if ( isset( $row->user_touched
) ) {
1315 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1320 if ( isset( $row->user_token
) ) {
1321 // The definition for the column is binary(32), so trim the NULs
1322 // that appends. The previous definition was char(32), so trim
1324 $this->mToken
= rtrim( $row->user_token
, " \0" );
1325 if ( $this->mToken
=== '' ) {
1326 $this->mToken
= null;
1332 if ( isset( $row->user_email
) ) {
1333 $this->mEmail
= $row->user_email
;
1334 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1335 $this->mEmailToken
= $row->user_email_token
;
1336 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1337 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1343 $this->mLoadedItems
= true;
1346 if ( is_array( $data ) ) {
1347 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1348 $this->mGroups
= $data['user_groups'];
1350 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1351 $this->loadOptions( $data['user_properties'] );
1357 * Load the data for this user object from another user object.
1361 protected function loadFromUserObject( $user ) {
1363 $user->loadGroups();
1364 $user->loadOptions();
1365 foreach ( self
::$mCacheVars as $var ) {
1366 $this->$var = $user->$var;
1371 * Load the groups from the database if they aren't already loaded.
1373 private function loadGroups() {
1374 if ( is_null( $this->mGroups
) ) {
1375 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
1376 ?
wfGetDB( DB_MASTER
)
1377 : wfGetDB( DB_SLAVE
);
1378 $res = $db->select( 'user_groups',
1380 [ 'ug_user' => $this->mId
],
1382 $this->mGroups
= [];
1383 foreach ( $res as $row ) {
1384 $this->mGroups
[] = $row->ug_group
;
1390 * Add the user to the group if he/she meets given criteria.
1392 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1393 * possible to remove manually via Special:UserRights. In such case it
1394 * will not be re-added automatically. The user will also not lose the
1395 * group if they no longer meet the criteria.
1397 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1399 * @return array Array of groups the user has been promoted to.
1401 * @see $wgAutopromoteOnce
1403 public function addAutopromoteOnceGroups( $event ) {
1404 global $wgAutopromoteOnceLogInRC, $wgAuth;
1406 if ( wfReadOnly() ||
!$this->getId() ) {
1410 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1411 if ( !count( $toPromote ) ) {
1415 if ( !$this->checkAndSetTouched() ) {
1416 return []; // raced out (bug T48834)
1419 $oldGroups = $this->getGroups(); // previous groups
1420 foreach ( $toPromote as $group ) {
1421 $this->addGroup( $group );
1423 // update groups in external authentication database
1424 Hooks
::run( 'UserGroupsChanged', [ $this, $toPromote, [], false, false ] );
1425 $wgAuth->updateExternalDBGroups( $this, $toPromote );
1427 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1429 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1430 $logEntry->setPerformer( $this );
1431 $logEntry->setTarget( $this->getUserPage() );
1432 $logEntry->setParameters( [
1433 '4::oldgroups' => $oldGroups,
1434 '5::newgroups' => $newGroups,
1436 $logid = $logEntry->insert();
1437 if ( $wgAutopromoteOnceLogInRC ) {
1438 $logEntry->publish( $logid );
1445 * Bump user_touched if it didn't change since this object was loaded
1447 * On success, the mTouched field is updated.
1448 * The user serialization cache is always cleared.
1450 * @return bool Whether user_touched was actually updated
1453 protected function checkAndSetTouched() {
1456 if ( !$this->mId
) {
1457 return false; // anon
1460 // Get a new user_touched that is higher than the old one
1461 $oldTouched = $this->mTouched
;
1462 $newTouched = $this->newTouchedTimestamp();
1464 $dbw = wfGetDB( DB_MASTER
);
1465 $dbw->update( 'user',
1466 [ 'user_touched' => $dbw->timestamp( $newTouched ) ],
1468 'user_id' => $this->mId
,
1469 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
1473 $success = ( $dbw->affectedRows() > 0 );
1476 $this->mTouched
= $newTouched;
1477 $this->clearSharedCache();
1479 // Clears on failure too since that is desired if the cache is stale
1480 $this->clearSharedCache( 'refresh' );
1487 * Clear various cached data stored in this object. The cache of the user table
1488 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1490 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1491 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1493 public function clearInstanceCache( $reloadFrom = false ) {
1494 $this->mNewtalk
= -1;
1495 $this->mDatePreference
= null;
1496 $this->mBlockedby
= -1; # Unset
1497 $this->mHash
= false;
1498 $this->mRights
= null;
1499 $this->mEffectiveGroups
= null;
1500 $this->mImplicitGroups
= null;
1501 $this->mGroups
= null;
1502 $this->mOptions
= null;
1503 $this->mOptionsLoaded
= false;
1504 $this->mEditCount
= null;
1506 if ( $reloadFrom ) {
1507 $this->mLoadedItems
= [];
1508 $this->mFrom
= $reloadFrom;
1513 * Combine the language default options with any site-specific options
1514 * and add the default language variants.
1516 * @return array Array of String options
1518 public static function getDefaultOptions() {
1519 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1521 static $defOpt = null;
1522 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1523 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1524 // mid-request and see that change reflected in the return value of this function.
1525 // Which is insane and would never happen during normal MW operation
1529 $defOpt = $wgDefaultUserOptions;
1530 // Default language setting
1531 $defOpt['language'] = $wgContLang->getCode();
1532 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1533 $defOpt[$langCode == $wgContLang->getCode() ?
'variant' : "variant-$langCode"] = $langCode;
1535 foreach ( SearchEngine
::searchableNamespaces() as $nsnum => $nsname ) {
1536 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1538 $defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1540 Hooks
::run( 'UserGetDefaultOptions', [ &$defOpt ] );
1546 * Get a given default option value.
1548 * @param string $opt Name of option to retrieve
1549 * @return string Default option value
1551 public static function getDefaultOption( $opt ) {
1552 $defOpts = self
::getDefaultOptions();
1553 if ( isset( $defOpts[$opt] ) ) {
1554 return $defOpts[$opt];
1561 * Get blocking information
1562 * @param bool $bFromSlave Whether to check the slave database first.
1563 * To improve performance, non-critical checks are done against slaves.
1564 * Check when actually saving should be done against master.
1566 private function getBlockedStatus( $bFromSlave = true ) {
1567 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1569 if ( -1 != $this->mBlockedby
) {
1573 wfDebug( __METHOD__
. ": checking...\n" );
1575 // Initialize data...
1576 // Otherwise something ends up stomping on $this->mBlockedby when
1577 // things get lazy-loaded later, causing false positive block hits
1578 // due to -1 !== 0. Probably session-related... Nothing should be
1579 // overwriting mBlockedby, surely?
1582 # We only need to worry about passing the IP address to the Block generator if the
1583 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1584 # know which IP address they're actually coming from
1586 if ( !$this->isAllowed( 'ipblock-exempt' ) ) {
1587 // $wgUser->getName() only works after the end of Setup.php. Until
1588 // then, assume it's a logged-out user.
1589 $globalUserName = $wgUser->isSafeToLoad()
1590 ?
$wgUser->getName()
1591 : IP
::sanitizeIP( $wgUser->getRequest()->getIP() );
1592 if ( $this->getName() === $globalUserName ) {
1593 $ip = $this->getRequest()->getIP();
1598 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1601 if ( !$block instanceof Block
&& $ip !== null && !in_array( $ip, $wgProxyWhitelist ) ) {
1603 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1605 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1606 $block->mReason
= wfMessage( 'proxyblockreason' )->text();
1607 $block->setTarget( $ip );
1608 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1610 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1611 $block->mReason
= wfMessage( 'sorbsreason' )->text();
1612 $block->setTarget( $ip );
1616 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1617 if ( !$block instanceof Block
1618 && $wgApplyIpBlocksToXff
1620 && !in_array( $ip, $wgProxyWhitelist )
1622 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1623 $xff = array_map( 'trim', explode( ',', $xff ) );
1624 $xff = array_diff( $xff, [ $ip ] );
1625 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1626 $block = Block
::chooseBlock( $xffblocks, $xff );
1627 if ( $block instanceof Block
) {
1628 # Mangle the reason to alert the user that the block
1629 # originated from matching the X-Forwarded-For header.
1630 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->text();
1634 if ( $block instanceof Block
) {
1635 wfDebug( __METHOD__
. ": Found block.\n" );
1636 $this->mBlock
= $block;
1637 $this->mBlockedby
= $block->getByName();
1638 $this->mBlockreason
= $block->mReason
;
1639 $this->mHideName
= $block->mHideName
;
1640 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1642 $this->mBlockedby
= '';
1643 $this->mHideName
= 0;
1644 $this->mAllowUsertalk
= false;
1648 Hooks
::run( 'GetBlockedStatus', [ &$this ] );
1653 * Whether the given IP is in a DNS blacklist.
1655 * @param string $ip IP to check
1656 * @param bool $checkWhitelist Whether to check the whitelist first
1657 * @return bool True if blacklisted.
1659 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1660 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1662 if ( !$wgEnableDnsBlacklist ) {
1666 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1670 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1674 * Whether the given IP is in a given DNS blacklist.
1676 * @param string $ip IP to check
1677 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1678 * @return bool True if blacklisted.
1680 public function inDnsBlacklist( $ip, $bases ) {
1683 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1684 if ( IP
::isIPv4( $ip ) ) {
1685 // Reverse IP, bug 21255
1686 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1688 foreach ( (array)$bases as $base ) {
1690 // If we have an access key, use that too (ProjectHoneypot, etc.)
1692 if ( is_array( $base ) ) {
1693 if ( count( $base ) >= 2 ) {
1694 // Access key is 1, base URL is 0
1695 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1697 $host = "$ipReversed.{$base[0]}";
1699 $basename = $base[0];
1701 $host = "$ipReversed.$base";
1705 $ipList = gethostbynamel( $host );
1708 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
1712 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
1721 * Check if an IP address is in the local proxy list
1727 public static function isLocallyBlockedProxy( $ip ) {
1728 global $wgProxyList;
1730 if ( !$wgProxyList ) {
1734 if ( !is_array( $wgProxyList ) ) {
1735 // Load from the specified file
1736 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1739 if ( !is_array( $wgProxyList ) ) {
1741 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1743 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1744 // Old-style flipped proxy list
1753 * Is this user subject to rate limiting?
1755 * @return bool True if rate limited
1757 public function isPingLimitable() {
1758 global $wgRateLimitsExcludedIPs;
1759 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1760 // No other good way currently to disable rate limits
1761 // for specific IPs. :P
1762 // But this is a crappy hack and should die.
1765 return !$this->isAllowed( 'noratelimit' );
1769 * Primitive rate limits: enforce maximum actions per time period
1770 * to put a brake on flooding.
1772 * The method generates both a generic profiling point and a per action one
1773 * (suffix being "-$action".
1775 * @note When using a shared cache like memcached, IP-address
1776 * last-hit counters will be shared across wikis.
1778 * @param string $action Action to enforce; 'edit' if unspecified
1779 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1780 * @return bool True if a rate limiter was tripped
1782 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1783 // Call the 'PingLimiter' hook
1785 if ( !Hooks
::run( 'PingLimiter', [ &$this, $action, &$result, $incrBy ] ) ) {
1789 global $wgRateLimits;
1790 if ( !isset( $wgRateLimits[$action] ) ) {
1794 // Some groups shouldn't trigger the ping limiter, ever
1795 if ( !$this->isPingLimitable() ) {
1799 $limits = $wgRateLimits[$action];
1801 $id = $this->getId();
1803 $isNewbie = $this->isNewbie();
1807 if ( isset( $limits['anon'] ) ) {
1808 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1811 // limits for logged-in users
1812 if ( isset( $limits['user'] ) ) {
1813 $userLimit = $limits['user'];
1815 // limits for newbie logged-in users
1816 if ( $isNewbie && isset( $limits['newbie'] ) ) {
1817 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1821 // limits for anons and for newbie logged-in users
1824 if ( isset( $limits['ip'] ) ) {
1825 $ip = $this->getRequest()->getIP();
1826 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1828 // subnet-based limits
1829 if ( isset( $limits['subnet'] ) ) {
1830 $ip = $this->getRequest()->getIP();
1831 $subnet = IP
::getSubnet( $ip );
1832 if ( $subnet !== false ) {
1833 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1838 // Check for group-specific permissions
1839 // If more than one group applies, use the group with the highest limit ratio (max/period)
1840 foreach ( $this->getGroups() as $group ) {
1841 if ( isset( $limits[$group] ) ) {
1842 if ( $userLimit === false
1843 ||
$limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1845 $userLimit = $limits[$group];
1850 // Set the user limit key
1851 if ( $userLimit !== false ) {
1852 list( $max, $period ) = $userLimit;
1853 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
1854 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1857 // ip-based limits for all ping-limitable users
1858 if ( isset( $limits['ip-all'] ) ) {
1859 $ip = $this->getRequest()->getIP();
1860 // ignore if user limit is more permissive
1861 if ( $isNewbie ||
$userLimit === false
1862 ||
$limits['ip-all'][0] / $limits['ip-all'][1] > $userLimit[0] / $userLimit[1] ) {
1863 $keys["mediawiki:limiter:$action:ip-all:$ip"] = $limits['ip-all'];
1867 // subnet-based limits for all ping-limitable users
1868 if ( isset( $limits['subnet-all'] ) ) {
1869 $ip = $this->getRequest()->getIP();
1870 $subnet = IP
::getSubnet( $ip );
1871 if ( $subnet !== false ) {
1872 // ignore if user limit is more permissive
1873 if ( $isNewbie ||
$userLimit === false
1874 ||
$limits['ip-all'][0] / $limits['ip-all'][1]
1875 > $userLimit[0] / $userLimit[1] ) {
1876 $keys["mediawiki:limiter:$action:subnet-all:$subnet"] = $limits['subnet-all'];
1881 $cache = ObjectCache
::getLocalClusterInstance();
1884 foreach ( $keys as $key => $limit ) {
1885 list( $max, $period ) = $limit;
1886 $summary = "(limit $max in {$period}s)";
1887 $count = $cache->get( $key );
1890 if ( $count >= $max ) {
1891 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1892 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1895 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1898 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1899 if ( $incrBy > 0 ) {
1900 $cache->add( $key, 0, intval( $period ) ); // first ping
1903 if ( $incrBy > 0 ) {
1904 $cache->incr( $key, $incrBy );
1912 * Check if user is blocked
1914 * @param bool $bFromSlave Whether to check the slave database instead of
1915 * the master. Hacked from false due to horrible probs on site.
1916 * @return bool True if blocked, false otherwise
1918 public function isBlocked( $bFromSlave = true ) {
1919 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
1923 * Get the block affecting the user, or null if the user is not blocked
1925 * @param bool $bFromSlave Whether to check the slave database instead of the master
1926 * @return Block|null
1928 public function getBlock( $bFromSlave = true ) {
1929 $this->getBlockedStatus( $bFromSlave );
1930 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
1934 * Check if user is blocked from editing a particular article
1936 * @param Title $title Title to check
1937 * @param bool $bFromSlave Whether to check the slave database instead of the master
1940 public function isBlockedFrom( $title, $bFromSlave = false ) {
1941 global $wgBlockAllowsUTEdit;
1943 $blocked = $this->isBlocked( $bFromSlave );
1944 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
1945 // If a user's name is suppressed, they cannot make edits anywhere
1946 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName()
1947 && $title->getNamespace() == NS_USER_TALK
) {
1949 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
1952 Hooks
::run( 'UserIsBlockedFrom', [ $this, $title, &$blocked, &$allowUsertalk ] );
1958 * If user is blocked, return the name of the user who placed the block
1959 * @return string Name of blocker
1961 public function blockedBy() {
1962 $this->getBlockedStatus();
1963 return $this->mBlockedby
;
1967 * If user is blocked, return the specified reason for the block
1968 * @return string Blocking reason
1970 public function blockedFor() {
1971 $this->getBlockedStatus();
1972 return $this->mBlockreason
;
1976 * If user is blocked, return the ID for the block
1977 * @return int Block ID
1979 public function getBlockId() {
1980 $this->getBlockedStatus();
1981 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
1985 * Check if user is blocked on all wikis.
1986 * Do not use for actual edit permission checks!
1987 * This is intended for quick UI checks.
1989 * @param string $ip IP address, uses current client if none given
1990 * @return bool True if blocked, false otherwise
1992 public function isBlockedGlobally( $ip = '' ) {
1993 if ( $this->mBlockedGlobally
!== null ) {
1994 return $this->mBlockedGlobally
;
1996 // User is already an IP?
1997 if ( IP
::isIPAddress( $this->getName() ) ) {
1998 $ip = $this->getName();
2000 $ip = $this->getRequest()->getIP();
2003 Hooks
::run( 'UserIsBlockedGlobally', [ &$this, $ip, &$blocked ] );
2004 $this->mBlockedGlobally
= (bool)$blocked;
2005 return $this->mBlockedGlobally
;
2009 * Check if user account is locked
2011 * @return bool True if locked, false otherwise
2013 public function isLocked() {
2014 if ( $this->mLocked
!== null ) {
2015 return $this->mLocked
;
2018 $authUser = $wgAuth->getUserInstance( $this );
2019 $this->mLocked
= (bool)$authUser->isLocked();
2020 Hooks
::run( 'UserIsLocked', [ $this, &$this->mLocked
] );
2021 return $this->mLocked
;
2025 * Check if user account is hidden
2027 * @return bool True if hidden, false otherwise
2029 public function isHidden() {
2030 if ( $this->mHideName
!== null ) {
2031 return $this->mHideName
;
2033 $this->getBlockedStatus();
2034 if ( !$this->mHideName
) {
2036 $authUser = $wgAuth->getUserInstance( $this );
2037 $this->mHideName
= (bool)$authUser->isHidden();
2038 Hooks
::run( 'UserIsHidden', [ $this, &$this->mHideName
] );
2040 return $this->mHideName
;
2044 * Get the user's ID.
2045 * @return int The user's ID; 0 if the user is anonymous or nonexistent
2047 public function getId() {
2048 if ( $this->mId
=== null && $this->mName
!== null && User
::isIP( $this->mName
) ) {
2049 // Special case, we know the user is anonymous
2051 } elseif ( !$this->isItemLoaded( 'id' ) ) {
2052 // Don't load if this was initialized from an ID
2059 * Set the user and reload all fields according to a given ID
2060 * @param int $v User ID to reload
2062 public function setId( $v ) {
2064 $this->clearInstanceCache( 'id' );
2068 * Get the user name, or the IP of an anonymous user
2069 * @return string User's name or IP address
2071 public function getName() {
2072 if ( $this->isItemLoaded( 'name', 'only' ) ) {
2073 // Special case optimisation
2074 return $this->mName
;
2077 if ( $this->mName
=== false ) {
2079 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
2081 return $this->mName
;
2086 * Set the user name.
2088 * This does not reload fields from the database according to the given
2089 * name. Rather, it is used to create a temporary "nonexistent user" for
2090 * later addition to the database. It can also be used to set the IP
2091 * address for an anonymous user to something other than the current
2094 * @note User::newFromName() has roughly the same function, when the named user
2096 * @param string $str New user name to set
2098 public function setName( $str ) {
2100 $this->mName
= $str;
2104 * Get the user's name escaped by underscores.
2105 * @return string Username escaped by underscores.
2107 public function getTitleKey() {
2108 return str_replace( ' ', '_', $this->getName() );
2112 * Check if the user has new messages.
2113 * @return bool True if the user has new messages
2115 public function getNewtalk() {
2118 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2119 if ( $this->mNewtalk
=== -1 ) {
2120 $this->mNewtalk
= false; # reset talk page status
2122 // Check memcached separately for anons, who have no
2123 // entire User object stored in there.
2124 if ( !$this->mId
) {
2125 global $wgDisableAnonTalk;
2126 if ( $wgDisableAnonTalk ) {
2127 // Anon newtalk disabled by configuration.
2128 $this->mNewtalk
= false;
2130 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
2133 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2137 return (bool)$this->mNewtalk
;
2141 * Return the data needed to construct links for new talk page message
2142 * alerts. If there are new messages, this will return an associative array
2143 * with the following data:
2144 * wiki: The database name of the wiki
2145 * link: Root-relative link to the user's talk page
2146 * rev: The last talk page revision that the user has seen or null. This
2147 * is useful for building diff links.
2148 * If there are no new messages, it returns an empty array.
2149 * @note This function was designed to accomodate multiple talk pages, but
2150 * currently only returns a single link and revision.
2153 public function getNewMessageLinks() {
2155 if ( !Hooks
::run( 'UserRetrieveNewTalks', [ &$this, &$talks ] ) ) {
2157 } elseif ( !$this->getNewtalk() ) {
2160 $utp = $this->getTalkPage();
2161 $dbr = wfGetDB( DB_SLAVE
);
2162 // Get the "last viewed rev" timestamp from the oldest message notification
2163 $timestamp = $dbr->selectField( 'user_newtalk',
2164 'MIN(user_last_timestamp)',
2165 $this->isAnon() ?
[ 'user_ip' => $this->getName() ] : [ 'user_id' => $this->getID() ],
2167 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2168 return [ [ 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ] ];
2172 * Get the revision ID for the last talk page revision viewed by the talk
2174 * @return int|null Revision ID or null
2176 public function getNewMessageRevisionId() {
2177 $newMessageRevisionId = null;
2178 $newMessageLinks = $this->getNewMessageLinks();
2179 if ( $newMessageLinks ) {
2180 // Note: getNewMessageLinks() never returns more than a single link
2181 // and it is always for the same wiki, but we double-check here in
2182 // case that changes some time in the future.
2183 if ( count( $newMessageLinks ) === 1
2184 && $newMessageLinks[0]['wiki'] === wfWikiID()
2185 && $newMessageLinks[0]['rev']
2187 /** @var Revision $newMessageRevision */
2188 $newMessageRevision = $newMessageLinks[0]['rev'];
2189 $newMessageRevisionId = $newMessageRevision->getId();
2192 return $newMessageRevisionId;
2196 * Internal uncached check for new messages
2199 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2200 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2201 * @return bool True if the user has new messages
2203 protected function checkNewtalk( $field, $id ) {
2204 $dbr = wfGetDB( DB_SLAVE
);
2206 $ok = $dbr->selectField( 'user_newtalk', $field, [ $field => $id ], __METHOD__
);
2208 return $ok !== false;
2212 * Add or update the new messages flag
2213 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2214 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2215 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2216 * @return bool True if successful, false otherwise
2218 protected function updateNewtalk( $field, $id, $curRev = null ) {
2219 // Get timestamp of the talk page revision prior to the current one
2220 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2221 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2222 // Mark the user as having new messages since this revision
2223 $dbw = wfGetDB( DB_MASTER
);
2224 $dbw->insert( 'user_newtalk',
2225 [ $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ],
2228 if ( $dbw->affectedRows() ) {
2229 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2232 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2238 * Clear the new messages flag for the given user
2239 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2240 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2241 * @return bool True if successful, false otherwise
2243 protected function deleteNewtalk( $field, $id ) {
2244 $dbw = wfGetDB( DB_MASTER
);
2245 $dbw->delete( 'user_newtalk',
2248 if ( $dbw->affectedRows() ) {
2249 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2252 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2258 * Update the 'You have new messages!' status.
2259 * @param bool $val Whether the user has new messages
2260 * @param Revision $curRev New, as yet unseen revision of the user talk
2261 * page. Ignored if null or !$val.
2263 public function setNewtalk( $val, $curRev = null ) {
2264 if ( wfReadOnly() ) {
2269 $this->mNewtalk
= $val;
2271 if ( $this->isAnon() ) {
2273 $id = $this->getName();
2276 $id = $this->getId();
2280 $changed = $this->updateNewtalk( $field, $id, $curRev );
2282 $changed = $this->deleteNewtalk( $field, $id );
2286 $this->invalidateCache();
2291 * Generate a current or new-future timestamp to be stored in the
2292 * user_touched field when we update things.
2293 * @return string Timestamp in TS_MW format
2295 private function newTouchedTimestamp() {
2296 global $wgClockSkewFudge;
2298 $time = wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2299 if ( $this->mTouched
&& $time <= $this->mTouched
) {
2300 $time = wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $this->mTouched
) +
1 );
2307 * Clear user data from memcached
2309 * Use after applying updates to the database; caller's
2310 * responsibility to update user_touched if appropriate.
2312 * Called implicitly from invalidateCache() and saveSettings().
2314 * @param string $mode Use 'refresh' to clear now; otherwise before DB commit
2316 public function clearSharedCache( $mode = 'changed' ) {
2317 if ( !$this->getId() ) {
2321 $cache = ObjectCache
::getMainWANInstance();
2322 $processCache = self
::getInProcessCache();
2323 $key = $this->getCacheKey( $cache );
2324 if ( $mode === 'refresh' ) {
2325 $cache->delete( $key, 1 );
2326 $processCache->delete( $key );
2328 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle(
2329 function() use ( $cache, $processCache, $key ) {
2330 $cache->delete( $key );
2331 $processCache->delete( $key );
2338 * Immediately touch the user data cache for this account
2340 * Calls touch() and removes account data from memcached
2342 public function invalidateCache() {
2344 $this->clearSharedCache();
2348 * Update the "touched" timestamp for the user
2350 * This is useful on various login/logout events when making sure that
2351 * a browser or proxy that has multiple tenants does not suffer cache
2352 * pollution where the new user sees the old users content. The value
2353 * of getTouched() is checked when determining 304 vs 200 responses.
2354 * Unlike invalidateCache(), this preserves the User object cache and
2355 * avoids database writes.
2359 public function touch() {
2360 $id = $this->getId();
2362 $key = wfMemcKey( 'user-quicktouched', 'id', $id );
2363 ObjectCache
::getMainWANInstance()->touchCheckKey( $key );
2364 $this->mQuickTouched
= null;
2369 * Validate the cache for this account.
2370 * @param string $timestamp A timestamp in TS_MW format
2373 public function validateCache( $timestamp ) {
2374 return ( $timestamp >= $this->getTouched() );
2378 * Get the user touched timestamp
2380 * Use this value only to validate caches via inequalities
2381 * such as in the case of HTTP If-Modified-Since response logic
2383 * @return string TS_MW Timestamp
2385 public function getTouched() {
2389 if ( $this->mQuickTouched
=== null ) {
2390 $key = wfMemcKey( 'user-quicktouched', 'id', $this->mId
);
2391 $cache = ObjectCache
::getMainWANInstance();
2393 $this->mQuickTouched
= wfTimestamp( TS_MW
, $cache->getCheckKeyTime( $key ) );
2396 return max( $this->mTouched
, $this->mQuickTouched
);
2399 return $this->mTouched
;
2403 * Get the user_touched timestamp field (time of last DB updates)
2404 * @return string TS_MW Timestamp
2407 public function getDBTouched() {
2410 return $this->mTouched
;
2414 * @deprecated Removed in 1.27.
2418 public function getPassword() {
2419 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2423 * @deprecated Removed in 1.27.
2427 public function getTemporaryPassword() {
2428 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2432 * Set the password and reset the random token.
2433 * Calls through to authentication plugin if necessary;
2434 * will have no effect if the auth plugin refuses to
2435 * pass the change through or if the legal password
2438 * As a special case, setting the password to null
2439 * wipes it, so the account cannot be logged in until
2440 * a new password is set, for instance via e-mail.
2442 * @deprecated since 1.27. AuthManager is coming.
2443 * @param string $str New password to set
2444 * @throws PasswordError On failure
2447 public function setPassword( $str ) {
2450 if ( $str !== null ) {
2451 if ( !$wgAuth->allowPasswordChange() ) {
2452 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2455 $status = $this->checkPasswordValidity( $str );
2456 if ( !$status->isGood() ) {
2457 throw new PasswordError( $status->getMessage()->text() );
2461 if ( !$wgAuth->setPassword( $this, $str ) ) {
2462 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2466 $this->setOption( 'watchlisttoken', false );
2467 $this->setPasswordInternal( $str );
2473 * Set the password and reset the random token unconditionally.
2475 * @deprecated since 1.27. AuthManager is coming.
2476 * @param string|null $str New password to set or null to set an invalid
2477 * password hash meaning that the user will not be able to log in
2478 * through the web interface.
2480 public function setInternalPassword( $str ) {
2483 if ( $wgAuth->allowSetLocalPassword() ) {
2485 $this->setOption( 'watchlisttoken', false );
2486 $this->setPasswordInternal( $str );
2491 * Actually set the password and such
2492 * @since 1.27 cannot set a password for a user not in the database
2493 * @param string|null $str New password to set or null to set an invalid
2494 * password hash meaning that the user will not be able to log in
2495 * through the web interface.
2497 private function setPasswordInternal( $str ) {
2498 $id = self
::idFromName( $this->getName(), self
::READ_LATEST
);
2500 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2503 $passwordFactory = new PasswordFactory();
2504 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
2505 $dbw = wfGetDB( DB_MASTER
);
2509 'user_password' => $passwordFactory->newFromPlaintext( $str )->toString(),
2510 'user_newpassword' => PasswordFactory
::newInvalidPassword()->toString(),
2511 'user_newpass_time' => $dbw->timestampOrNull( null ),
2519 // When the main password is changed, invalidate all bot passwords too
2520 BotPassword
::invalidateAllPasswordsForUser( $this->getName() );
2524 * Get the user's current token.
2525 * @param bool $forceCreation Force the generation of a new token if the
2526 * user doesn't have one (default=true for backwards compatibility).
2527 * @return string|null Token
2529 public function getToken( $forceCreation = true ) {
2530 global $wgAuthenticationTokenVersion;
2533 if ( !$this->mToken
&& $forceCreation ) {
2537 if ( !$this->mToken
) {
2538 // The user doesn't have a token, return null to indicate that.
2540 } elseif ( $this->mToken
=== self
::INVALID_TOKEN
) {
2541 // We return a random value here so existing token checks are very
2543 return MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2544 } elseif ( $wgAuthenticationTokenVersion === null ) {
2545 // $wgAuthenticationTokenVersion not in use, so return the raw secret
2546 return $this->mToken
;
2548 // $wgAuthenticationTokenVersion in use, so hmac it.
2549 $ret = MWCryptHash
::hmac( $wgAuthenticationTokenVersion, $this->mToken
, false );
2551 // The raw hash can be overly long. Shorten it up.
2552 $len = max( 32, self
::TOKEN_LENGTH
);
2553 if ( strlen( $ret ) < $len ) {
2554 // Should never happen, even md5 is 128 bits
2555 throw new \
UnexpectedValueException( 'Hmac returned less than 128 bits' );
2557 return substr( $ret, -$len );
2562 * Set the random token (used for persistent authentication)
2563 * Called from loadDefaults() among other places.
2565 * @param string|bool $token If specified, set the token to this value
2567 public function setToken( $token = false ) {
2569 if ( $this->mToken
=== self
::INVALID_TOKEN
) {
2570 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
2571 ->debug( __METHOD__
. ": Ignoring attempt to set token for system user \"$this\"" );
2572 } elseif ( !$token ) {
2573 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2575 $this->mToken
= $token;
2580 * Set the password for a password reminder or new account email
2582 * @deprecated since 1.27, AuthManager is coming
2583 * @param string $str New password to set or null to set an invalid
2584 * password hash meaning that the user will not be able to use it
2585 * @param bool $throttle If true, reset the throttle timestamp to the present
2587 public function setNewpassword( $str, $throttle = true ) {
2588 $id = $this->getId();
2590 throw new LogicException( 'Cannot set new password for a user that is not in the database.' );
2593 $dbw = wfGetDB( DB_MASTER
);
2595 $passwordFactory = new PasswordFactory();
2596 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
2598 'user_newpassword' => $passwordFactory->newFromPlaintext( $str )->toString(),
2601 if ( $str === null ) {
2602 $update['user_newpass_time'] = null;
2603 } elseif ( $throttle ) {
2604 $update['user_newpass_time'] = $dbw->timestamp();
2607 $dbw->update( 'user', $update, [ 'user_id' => $id ], __METHOD__
);
2611 * Has password reminder email been sent within the last
2612 * $wgPasswordReminderResendTime hours?
2615 public function isPasswordReminderThrottled() {
2616 global $wgPasswordReminderResendTime;
2618 if ( !$wgPasswordReminderResendTime ) {
2624 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
2625 ?
wfGetDB( DB_MASTER
)
2626 : wfGetDB( DB_SLAVE
);
2627 $newpassTime = $db->selectField(
2629 'user_newpass_time',
2630 [ 'user_id' => $this->getId() ],
2634 if ( $newpassTime === null ) {
2637 $expiry = wfTimestamp( TS_UNIX
, $newpassTime ) +
$wgPasswordReminderResendTime * 3600;
2638 return time() < $expiry;
2642 * Get the user's e-mail address
2643 * @return string User's email address
2645 public function getEmail() {
2647 Hooks
::run( 'UserGetEmail', [ $this, &$this->mEmail
] );
2648 return $this->mEmail
;
2652 * Get the timestamp of the user's e-mail authentication
2653 * @return string TS_MW timestamp
2655 public function getEmailAuthenticationTimestamp() {
2657 Hooks
::run( 'UserGetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
2658 return $this->mEmailAuthenticated
;
2662 * Set the user's e-mail address
2663 * @param string $str New e-mail address
2665 public function setEmail( $str ) {
2667 if ( $str == $this->mEmail
) {
2670 $this->invalidateEmail();
2671 $this->mEmail
= $str;
2672 Hooks
::run( 'UserSetEmail', [ $this, &$this->mEmail
] );
2676 * Set the user's e-mail address and a confirmation mail if needed.
2679 * @param string $str New e-mail address
2682 public function setEmailWithConfirmation( $str ) {
2683 global $wgEnableEmail, $wgEmailAuthentication;
2685 if ( !$wgEnableEmail ) {
2686 return Status
::newFatal( 'emaildisabled' );
2689 $oldaddr = $this->getEmail();
2690 if ( $str === $oldaddr ) {
2691 return Status
::newGood( true );
2694 $this->setEmail( $str );
2696 if ( $str !== '' && $wgEmailAuthentication ) {
2697 // Send a confirmation request to the new address if needed
2698 $type = $oldaddr != '' ?
'changed' : 'set';
2699 $result = $this->sendConfirmationMail( $type );
2700 if ( $result->isGood() ) {
2701 // Say to the caller that a confirmation mail has been sent
2702 $result->value
= 'eauth';
2705 $result = Status
::newGood( true );
2712 * Get the user's real name
2713 * @return string User's real name
2715 public function getRealName() {
2716 if ( !$this->isItemLoaded( 'realname' ) ) {
2720 return $this->mRealName
;
2724 * Set the user's real name
2725 * @param string $str New real name
2727 public function setRealName( $str ) {
2729 $this->mRealName
= $str;
2733 * Get the user's current setting for a given option.
2735 * @param string $oname The option to check
2736 * @param string $defaultOverride A default value returned if the option does not exist
2737 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2738 * @return string User's current value for the option
2739 * @see getBoolOption()
2740 * @see getIntOption()
2742 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2743 global $wgHiddenPrefs;
2744 $this->loadOptions();
2746 # We want 'disabled' preferences to always behave as the default value for
2747 # users, even if they have set the option explicitly in their settings (ie they
2748 # set it, and then it was disabled removing their ability to change it). But
2749 # we don't want to erase the preferences in the database in case the preference
2750 # is re-enabled again. So don't touch $mOptions, just override the returned value
2751 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2752 return self
::getDefaultOption( $oname );
2755 if ( array_key_exists( $oname, $this->mOptions
) ) {
2756 return $this->mOptions
[$oname];
2758 return $defaultOverride;
2763 * Get all user's options
2765 * @param int $flags Bitwise combination of:
2766 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2767 * to the default value. (Since 1.25)
2770 public function getOptions( $flags = 0 ) {
2771 global $wgHiddenPrefs;
2772 $this->loadOptions();
2773 $options = $this->mOptions
;
2775 # We want 'disabled' preferences to always behave as the default value for
2776 # users, even if they have set the option explicitly in their settings (ie they
2777 # set it, and then it was disabled removing their ability to change it). But
2778 # we don't want to erase the preferences in the database in case the preference
2779 # is re-enabled again. So don't touch $mOptions, just override the returned value
2780 foreach ( $wgHiddenPrefs as $pref ) {
2781 $default = self
::getDefaultOption( $pref );
2782 if ( $default !== null ) {
2783 $options[$pref] = $default;
2787 if ( $flags & self
::GETOPTIONS_EXCLUDE_DEFAULTS
) {
2788 $options = array_diff_assoc( $options, self
::getDefaultOptions() );
2795 * Get the user's current setting for a given option, as a boolean value.
2797 * @param string $oname The option to check
2798 * @return bool User's current value for the option
2801 public function getBoolOption( $oname ) {
2802 return (bool)$this->getOption( $oname );
2806 * Get the user's current setting for a given option, as an integer value.
2808 * @param string $oname The option to check
2809 * @param int $defaultOverride A default value returned if the option does not exist
2810 * @return int User's current value for the option
2813 public function getIntOption( $oname, $defaultOverride = 0 ) {
2814 $val = $this->getOption( $oname );
2816 $val = $defaultOverride;
2818 return intval( $val );
2822 * Set the given option for a user.
2824 * You need to call saveSettings() to actually write to the database.
2826 * @param string $oname The option to set
2827 * @param mixed $val New value to set
2829 public function setOption( $oname, $val ) {
2830 $this->loadOptions();
2832 // Explicitly NULL values should refer to defaults
2833 if ( is_null( $val ) ) {
2834 $val = self
::getDefaultOption( $oname );
2837 $this->mOptions
[$oname] = $val;
2841 * Get a token stored in the preferences (like the watchlist one),
2842 * resetting it if it's empty (and saving changes).
2844 * @param string $oname The option name to retrieve the token from
2845 * @return string|bool User's current value for the option, or false if this option is disabled.
2846 * @see resetTokenFromOption()
2848 * @deprecated 1.26 Applications should use the OAuth extension
2850 public function getTokenFromOption( $oname ) {
2851 global $wgHiddenPrefs;
2853 $id = $this->getId();
2854 if ( !$id ||
in_array( $oname, $wgHiddenPrefs ) ) {
2858 $token = $this->getOption( $oname );
2860 // Default to a value based on the user token to avoid space
2861 // wasted on storing tokens for all users. When this option
2862 // is set manually by the user, only then is it stored.
2863 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
2870 * Reset a token stored in the preferences (like the watchlist one).
2871 * *Does not* save user's preferences (similarly to setOption()).
2873 * @param string $oname The option name to reset the token in
2874 * @return string|bool New token value, or false if this option is disabled.
2875 * @see getTokenFromOption()
2878 public function resetTokenFromOption( $oname ) {
2879 global $wgHiddenPrefs;
2880 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2884 $token = MWCryptRand
::generateHex( 40 );
2885 $this->setOption( $oname, $token );
2890 * Return a list of the types of user options currently returned by
2891 * User::getOptionKinds().
2893 * Currently, the option kinds are:
2894 * - 'registered' - preferences which are registered in core MediaWiki or
2895 * by extensions using the UserGetDefaultOptions hook.
2896 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2897 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2898 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2899 * be used by user scripts.
2900 * - 'special' - "preferences" that are not accessible via User::getOptions
2901 * or User::setOptions.
2902 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2903 * These are usually legacy options, removed in newer versions.
2905 * The API (and possibly others) use this function to determine the possible
2906 * option types for validation purposes, so make sure to update this when a
2907 * new option kind is added.
2909 * @see User::getOptionKinds
2910 * @return array Option kinds
2912 public static function listOptionKinds() {
2915 'registered-multiselect',
2916 'registered-checkmatrix',
2924 * Return an associative array mapping preferences keys to the kind of a preference they're
2925 * used for. Different kinds are handled differently when setting or reading preferences.
2927 * See User::listOptionKinds for the list of valid option types that can be provided.
2929 * @see User::listOptionKinds
2930 * @param IContextSource $context
2931 * @param array $options Assoc. array with options keys to check as keys.
2932 * Defaults to $this->mOptions.
2933 * @return array The key => kind mapping data
2935 public function getOptionKinds( IContextSource
$context, $options = null ) {
2936 $this->loadOptions();
2937 if ( $options === null ) {
2938 $options = $this->mOptions
;
2941 $prefs = Preferences
::getPreferences( $this, $context );
2944 // Pull out the "special" options, so they don't get converted as
2945 // multiselect or checkmatrix.
2946 $specialOptions = array_fill_keys( Preferences
::getSaveBlacklist(), true );
2947 foreach ( $specialOptions as $name => $value ) {
2948 unset( $prefs[$name] );
2951 // Multiselect and checkmatrix options are stored in the database with
2952 // one key per option, each having a boolean value. Extract those keys.
2953 $multiselectOptions = [];
2954 foreach ( $prefs as $name => $info ) {
2955 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2956 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2957 $opts = HTMLFormField
::flattenOptions( $info['options'] );
2958 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2960 foreach ( $opts as $value ) {
2961 $multiselectOptions["$prefix$value"] = true;
2964 unset( $prefs[$name] );
2967 $checkmatrixOptions = [];
2968 foreach ( $prefs as $name => $info ) {
2969 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2970 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2971 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
2972 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
2973 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2975 foreach ( $columns as $column ) {
2976 foreach ( $rows as $row ) {
2977 $checkmatrixOptions["$prefix$column-$row"] = true;
2981 unset( $prefs[$name] );
2985 // $value is ignored
2986 foreach ( $options as $key => $value ) {
2987 if ( isset( $prefs[$key] ) ) {
2988 $mapping[$key] = 'registered';
2989 } elseif ( isset( $multiselectOptions[$key] ) ) {
2990 $mapping[$key] = 'registered-multiselect';
2991 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2992 $mapping[$key] = 'registered-checkmatrix';
2993 } elseif ( isset( $specialOptions[$key] ) ) {
2994 $mapping[$key] = 'special';
2995 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2996 $mapping[$key] = 'userjs';
2998 $mapping[$key] = 'unused';
3006 * Reset certain (or all) options to the site defaults
3008 * The optional parameter determines which kinds of preferences will be reset.
3009 * Supported values are everything that can be reported by getOptionKinds()
3010 * and 'all', which forces a reset of *all* preferences and overrides everything else.
3012 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
3013 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
3014 * for backwards-compatibility.
3015 * @param IContextSource|null $context Context source used when $resetKinds
3016 * does not contain 'all', passed to getOptionKinds().
3017 * Defaults to RequestContext::getMain() when null.
3019 public function resetOptions(
3020 $resetKinds = [ 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ],
3021 IContextSource
$context = null
3024 $defaultOptions = self
::getDefaultOptions();
3026 if ( !is_array( $resetKinds ) ) {
3027 $resetKinds = [ $resetKinds ];
3030 if ( in_array( 'all', $resetKinds ) ) {
3031 $newOptions = $defaultOptions;
3033 if ( $context === null ) {
3034 $context = RequestContext
::getMain();
3037 $optionKinds = $this->getOptionKinds( $context );
3038 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
3041 // Use default values for the options that should be deleted, and
3042 // copy old values for the ones that shouldn't.
3043 foreach ( $this->mOptions
as $key => $value ) {
3044 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
3045 if ( array_key_exists( $key, $defaultOptions ) ) {
3046 $newOptions[$key] = $defaultOptions[$key];
3049 $newOptions[$key] = $value;
3054 Hooks
::run( 'UserResetAllOptions', [ $this, &$newOptions, $this->mOptions
, $resetKinds ] );
3056 $this->mOptions
= $newOptions;
3057 $this->mOptionsLoaded
= true;
3061 * Get the user's preferred date format.
3062 * @return string User's preferred date format
3064 public function getDatePreference() {
3065 // Important migration for old data rows
3066 if ( is_null( $this->mDatePreference
) ) {
3068 $value = $this->getOption( 'date' );
3069 $map = $wgLang->getDatePreferenceMigrationMap();
3070 if ( isset( $map[$value] ) ) {
3071 $value = $map[$value];
3073 $this->mDatePreference
= $value;
3075 return $this->mDatePreference
;
3079 * Determine based on the wiki configuration and the user's options,
3080 * whether this user must be over HTTPS no matter what.
3084 public function requiresHTTPS() {
3085 global $wgSecureLogin;
3086 if ( !$wgSecureLogin ) {
3089 $https = $this->getBoolOption( 'prefershttps' );
3090 Hooks
::run( 'UserRequiresHTTPS', [ $this, &$https ] );
3092 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
3099 * Get the user preferred stub threshold
3103 public function getStubThreshold() {
3104 global $wgMaxArticleSize; # Maximum article size, in Kb
3105 $threshold = $this->getIntOption( 'stubthreshold' );
3106 if ( $threshold > $wgMaxArticleSize * 1024 ) {
3107 // If they have set an impossible value, disable the preference
3108 // so we can use the parser cache again.
3115 * Get the permissions this user has.
3116 * @return array Array of String permission names
3118 public function getRights() {
3119 if ( is_null( $this->mRights
) ) {
3120 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
3122 // Deny any rights denied by the user's session, unless this
3123 // endpoint has no sessions.
3124 if ( !defined( 'MW_NO_SESSION' ) ) {
3125 $allowedRights = $this->getRequest()->getSession()->getAllowedUserRights();
3126 if ( $allowedRights !== null ) {
3127 $this->mRights
= array_intersect( $this->mRights
, $allowedRights );
3131 Hooks
::run( 'UserGetRights', [ $this, &$this->mRights
] );
3132 // Force reindexation of rights when a hook has unset one of them
3133 $this->mRights
= array_values( array_unique( $this->mRights
) );
3135 return $this->mRights
;
3139 * Get the list of explicit group memberships this user has.
3140 * The implicit * and user groups are not included.
3141 * @return array Array of String internal group names
3143 public function getGroups() {
3145 $this->loadGroups();
3146 return $this->mGroups
;
3150 * Get the list of implicit group memberships this user has.
3151 * This includes all explicit groups, plus 'user' if logged in,
3152 * '*' for all accounts, and autopromoted groups
3153 * @param bool $recache Whether to avoid the cache
3154 * @return array Array of String internal group names
3156 public function getEffectiveGroups( $recache = false ) {
3157 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
3158 $this->mEffectiveGroups
= array_unique( array_merge(
3159 $this->getGroups(), // explicit groups
3160 $this->getAutomaticGroups( $recache ) // implicit groups
3162 // Hook for additional groups
3163 Hooks
::run( 'UserEffectiveGroups', [ &$this, &$this->mEffectiveGroups
] );
3164 // Force reindexation of groups when a hook has unset one of them
3165 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
3167 return $this->mEffectiveGroups
;
3171 * Get the list of implicit group memberships this user has.
3172 * This includes 'user' if logged in, '*' for all accounts,
3173 * and autopromoted groups
3174 * @param bool $recache Whether to avoid the cache
3175 * @return array Array of String internal group names
3177 public function getAutomaticGroups( $recache = false ) {
3178 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
3179 $this->mImplicitGroups
= [ '*' ];
3180 if ( $this->getId() ) {
3181 $this->mImplicitGroups
[] = 'user';
3183 $this->mImplicitGroups
= array_unique( array_merge(
3184 $this->mImplicitGroups
,
3185 Autopromote
::getAutopromoteGroups( $this )
3189 // Assure data consistency with rights/groups,
3190 // as getEffectiveGroups() depends on this function
3191 $this->mEffectiveGroups
= null;
3194 return $this->mImplicitGroups
;
3198 * Returns the groups the user has belonged to.
3200 * The user may still belong to the returned groups. Compare with getGroups().
3202 * The function will not return groups the user had belonged to before MW 1.17
3204 * @return array Names of the groups the user has belonged to.
3206 public function getFormerGroups() {
3209 if ( is_null( $this->mFormerGroups
) ) {
3210 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3211 ?
wfGetDB( DB_MASTER
)
3212 : wfGetDB( DB_SLAVE
);
3213 $res = $db->select( 'user_former_groups',
3215 [ 'ufg_user' => $this->mId
],
3217 $this->mFormerGroups
= [];
3218 foreach ( $res as $row ) {
3219 $this->mFormerGroups
[] = $row->ufg_group
;
3223 return $this->mFormerGroups
;
3227 * Get the user's edit count.
3228 * @return int|null Null for anonymous users
3230 public function getEditCount() {
3231 if ( !$this->getId() ) {
3235 if ( $this->mEditCount
=== null ) {
3236 /* Populate the count, if it has not been populated yet */
3237 $dbr = wfGetDB( DB_SLAVE
);
3238 // check if the user_editcount field has been initialized
3239 $count = $dbr->selectField(
3240 'user', 'user_editcount',
3241 [ 'user_id' => $this->mId
],
3245 if ( $count === null ) {
3246 // it has not been initialized. do so.
3247 $count = $this->initEditCount();
3249 $this->mEditCount
= $count;
3251 return (int)$this->mEditCount
;
3255 * Add the user to the given group.
3256 * This takes immediate effect.
3257 * @param string $group Name of the group to add
3260 public function addGroup( $group ) {
3263 if ( !Hooks
::run( 'UserAddGroup', [ $this, &$group ] ) ) {
3267 $dbw = wfGetDB( DB_MASTER
);
3268 if ( $this->getId() ) {
3269 $dbw->insert( 'user_groups',
3271 'ug_user' => $this->getID(),
3272 'ug_group' => $group,
3278 $this->loadGroups();
3279 $this->mGroups
[] = $group;
3280 // In case loadGroups was not called before, we now have the right twice.
3281 // Get rid of the duplicate.
3282 $this->mGroups
= array_unique( $this->mGroups
);
3284 // Refresh the groups caches, and clear the rights cache so it will be
3285 // refreshed on the next call to $this->getRights().
3286 $this->getEffectiveGroups( true );
3287 $this->mRights
= null;
3289 $this->invalidateCache();
3295 * Remove the user from the given group.
3296 * This takes immediate effect.
3297 * @param string $group Name of the group to remove
3300 public function removeGroup( $group ) {
3302 if ( !Hooks
::run( 'UserRemoveGroup', [ $this, &$group ] ) ) {
3306 $dbw = wfGetDB( DB_MASTER
);
3307 $dbw->delete( 'user_groups',
3309 'ug_user' => $this->getID(),
3310 'ug_group' => $group,
3313 // Remember that the user was in this group
3314 $dbw->insert( 'user_former_groups',
3316 'ufg_user' => $this->getID(),
3317 'ufg_group' => $group,
3323 $this->loadGroups();
3324 $this->mGroups
= array_diff( $this->mGroups
, [ $group ] );
3326 // Refresh the groups caches, and clear the rights cache so it will be
3327 // refreshed on the next call to $this->getRights().
3328 $this->getEffectiveGroups( true );
3329 $this->mRights
= null;
3331 $this->invalidateCache();
3337 * Get whether the user is logged in
3340 public function isLoggedIn() {
3341 return $this->getID() != 0;
3345 * Get whether the user is anonymous
3348 public function isAnon() {
3349 return !$this->isLoggedIn();
3353 * Check if user is allowed to access a feature / make an action
3355 * @param string ... Permissions to test
3356 * @return bool True if user is allowed to perform *any* of the given actions
3358 public function isAllowedAny() {
3359 $permissions = func_get_args();
3360 foreach ( $permissions as $permission ) {
3361 if ( $this->isAllowed( $permission ) ) {
3370 * @param string ... Permissions to test
3371 * @return bool True if the user is allowed to perform *all* of the given actions
3373 public function isAllowedAll() {
3374 $permissions = func_get_args();
3375 foreach ( $permissions as $permission ) {
3376 if ( !$this->isAllowed( $permission ) ) {
3384 * Internal mechanics of testing a permission
3385 * @param string $action
3388 public function isAllowed( $action = '' ) {
3389 if ( $action === '' ) {
3390 return true; // In the spirit of DWIM
3392 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3393 // by misconfiguration: 0 == 'foo'
3394 return in_array( $action, $this->getRights(), true );
3398 * Check whether to enable recent changes patrol features for this user
3399 * @return bool True or false
3401 public function useRCPatrol() {
3402 global $wgUseRCPatrol;
3403 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3407 * Check whether to enable new pages patrol features for this user
3408 * @return bool True or false
3410 public function useNPPatrol() {
3411 global $wgUseRCPatrol, $wgUseNPPatrol;
3413 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3414 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3419 * Check whether to enable new files patrol features for this user
3420 * @return bool True or false
3422 public function useFilePatrol() {
3423 global $wgUseRCPatrol, $wgUseFilePatrol;
3425 ( $wgUseRCPatrol ||
$wgUseFilePatrol )
3426 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3431 * Get the WebRequest object to use with this object
3433 * @return WebRequest
3435 public function getRequest() {
3436 if ( $this->mRequest
) {
3437 return $this->mRequest
;
3445 * Check the watched status of an article.
3446 * @since 1.22 $checkRights parameter added
3447 * @param Title $title Title of the article to look at
3448 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3449 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3452 public function isWatched( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3453 if ( $title->isWatchable() && ( !$checkRights ||
$this->isAllowed( 'viewmywatchlist' ) ) ) {
3454 return WatchedItemStore
::getDefaultInstance()->isWatched( $this, $title );
3461 * @since 1.22 $checkRights parameter added
3462 * @param Title $title Title of the article to look at
3463 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3464 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3466 public function addWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3467 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3468 WatchedItemStore
::getDefaultInstance()->addWatchBatch( [
3469 [ $this, $title->getSubjectPage() ],
3470 [ $this, $title->getTalkPage() ],
3474 $this->invalidateCache();
3478 * Stop watching an article.
3479 * @since 1.22 $checkRights parameter added
3480 * @param Title $title Title of the article to look at
3481 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3482 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3484 public function removeWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3485 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3486 WatchedItemStore
::getDefaultInstance()->removeWatch( $this, $title->getSubjectPage() );
3487 WatchedItemStore
::getDefaultInstance()->removeWatch( $this, $title->getTalkPage() );
3489 $this->invalidateCache();
3493 * Clear the user's notification timestamp for the given title.
3494 * If e-notif e-mails are on, they will receive notification mails on
3495 * the next change of the page if it's watched etc.
3496 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3497 * @param Title $title Title of the article to look at
3498 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3500 public function clearNotification( &$title, $oldid = 0 ) {
3501 global $wgUseEnotif, $wgShowUpdatedMarker;
3503 // Do nothing if the database is locked to writes
3504 if ( wfReadOnly() ) {
3508 // Do nothing if not allowed to edit the watchlist
3509 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3513 // If we're working on user's talk page, we should update the talk page message indicator
3514 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3515 if ( !Hooks
::run( 'UserClearNewTalkNotification', [ &$this, $oldid ] ) ) {
3519 // Try to update the DB post-send and only if needed...
3520 DeferredUpdates
::addCallableUpdate( function() use ( $title, $oldid ) {
3521 if ( !$this->getNewtalk() ) {
3522 return; // no notifications to clear
3525 // Delete the last notifications (they stack up)
3526 $this->setNewtalk( false );
3528 // If there is a new, unseen, revision, use its timestamp
3530 ?
$title->getNextRevisionID( $oldid, Title
::GAID_FOR_UPDATE
)
3533 $this->setNewtalk( true, Revision
::newFromId( $nextid ) );
3538 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3542 if ( $this->isAnon() ) {
3543 // Nothing else to do...
3547 // Only update the timestamp if the page is being watched.
3548 // The query to find out if it is watched is cached both in memcached and per-invocation,
3549 // and when it does have to be executed, it can be on a slave
3550 // If this is the user's newtalk page, we always update the timestamp
3552 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3556 WatchedItemStore
::getDefaultInstance()
3557 ->resetNotificationTimestamp( $this, $title, $force, $oldid );
3561 * Resets all of the given user's page-change notification timestamps.
3562 * If e-notif e-mails are on, they will receive notification mails on
3563 * the next change of any watched page.
3564 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3566 public function clearAllNotifications() {
3567 if ( wfReadOnly() ) {
3571 // Do nothing if not allowed to edit the watchlist
3572 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3576 global $wgUseEnotif, $wgShowUpdatedMarker;
3577 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3578 $this->setNewtalk( false );
3581 $id = $this->getId();
3583 $dbw = wfGetDB( DB_MASTER
);
3584 $dbw->update( 'watchlist',
3585 [ /* SET */ 'wl_notificationtimestamp' => null ],
3586 [ /* WHERE */ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ],
3589 // We also need to clear here the "you have new message" notification for the own user_talk page;
3590 // it's cleared one page view later in WikiPage::doViewUpdates().
3595 * Set a cookie on the user's client. Wrapper for
3596 * WebResponse::setCookie
3597 * @deprecated since 1.27
3598 * @param string $name Name of the cookie to set
3599 * @param string $value Value to set
3600 * @param int $exp Expiration time, as a UNIX time value;
3601 * if 0 or not specified, use the default $wgCookieExpiration
3602 * @param bool $secure
3603 * true: Force setting the secure attribute when setting the cookie
3604 * false: Force NOT setting the secure attribute when setting the cookie
3605 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3606 * @param array $params Array of options sent passed to WebResponse::setcookie()
3607 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3610 protected function setCookie(
3611 $name, $value, $exp = 0, $secure = null, $params = [], $request = null
3613 wfDeprecated( __METHOD__
, '1.27' );
3614 if ( $request === null ) {
3615 $request = $this->getRequest();
3617 $params['secure'] = $secure;
3618 $request->response()->setCookie( $name, $value, $exp, $params );
3622 * Clear a cookie on the user's client
3623 * @deprecated since 1.27
3624 * @param string $name Name of the cookie to clear
3625 * @param bool $secure
3626 * true: Force setting the secure attribute when setting the cookie
3627 * false: Force NOT setting the secure attribute when setting the cookie
3628 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3629 * @param array $params Array of options sent passed to WebResponse::setcookie()
3631 protected function clearCookie( $name, $secure = null, $params = [] ) {
3632 wfDeprecated( __METHOD__
, '1.27' );
3633 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3637 * Set an extended login cookie on the user's client. The expiry of the cookie
3638 * is controlled by the $wgExtendedLoginCookieExpiration configuration
3641 * @see User::setCookie
3643 * @deprecated since 1.27
3644 * @param string $name Name of the cookie to set
3645 * @param string $value Value to set
3646 * @param bool $secure
3647 * true: Force setting the secure attribute when setting the cookie
3648 * false: Force NOT setting the secure attribute when setting the cookie
3649 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3651 protected function setExtendedLoginCookie( $name, $value, $secure ) {
3652 global $wgExtendedLoginCookieExpiration, $wgCookieExpiration;
3654 wfDeprecated( __METHOD__
, '1.27' );
3657 $exp +
= $wgExtendedLoginCookieExpiration !== null
3658 ?
$wgExtendedLoginCookieExpiration
3659 : $wgCookieExpiration;
3661 $this->setCookie( $name, $value, $exp, $secure );
3665 * Persist this user's session (e.g. set cookies)
3667 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3669 * @param bool $secure Whether to force secure/insecure cookies or use default
3670 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3672 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3674 if ( 0 == $this->mId
) {
3678 $session = $this->getRequest()->getSession();
3679 if ( $request && $session->getRequest() !== $request ) {
3680 $session = $session->sessionWithRequest( $request );
3682 $delay = $session->delaySave();
3684 if ( !$session->getUser()->equals( $this ) ) {
3685 if ( !$session->canSetUser() ) {
3686 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3687 ->warning( __METHOD__
.
3688 ": Cannot save user \"$this\" to a user \"{$session->getUser()}\"'s immutable session"
3692 $session->setUser( $this );
3695 $session->setRememberUser( $rememberMe );
3696 if ( $secure !== null ) {
3697 $session->setForceHTTPS( $secure );
3700 $session->persist();
3702 ScopedCallback
::consume( $delay );
3706 * Log this user out.
3708 public function logout() {
3709 if ( Hooks
::run( 'UserLogout', [ &$this ] ) ) {
3715 * Clear the user's session, and reset the instance cache.
3718 public function doLogout() {
3719 $session = $this->getRequest()->getSession();
3720 if ( !$session->canSetUser() ) {
3721 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3722 ->warning( __METHOD__
. ": Cannot log out of an immutable session" );
3723 } elseif ( !$session->getUser()->equals( $this ) ) {
3724 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3725 ->warning( __METHOD__
.
3726 ": Cannot log user \"$this\" out of a user \"{$session->getUser()}\"'s session"
3728 // But we still may as well make this user object anon
3729 $this->clearInstanceCache( 'defaults' );
3731 $this->clearInstanceCache( 'defaults' );
3732 $delay = $session->delaySave();
3733 $session->unpersist(); // Clear cookies (T127436)
3734 $session->setLoggedOutTimestamp( time() );
3735 $session->setUser( new User
);
3736 $session->set( 'wsUserID', 0 ); // Other code expects this
3737 ScopedCallback
::consume( $delay );
3742 * Save this user's settings into the database.
3743 * @todo Only rarely do all these fields need to be set!
3745 public function saveSettings() {
3746 if ( wfReadOnly() ) {
3747 // @TODO: caller should deal with this instead!
3748 // This should really just be an exception.
3749 MWExceptionHandler
::logException( new DBExpectedError(
3751 "Could not update user with ID '{$this->mId}'; DB is read-only."
3757 if ( 0 == $this->mId
) {
3761 // Get a new user_touched that is higher than the old one.
3762 // This will be used for a CAS check as a last-resort safety
3763 // check against race conditions and slave lag.
3764 $oldTouched = $this->mTouched
;
3765 $newTouched = $this->newTouchedTimestamp();
3767 $dbw = wfGetDB( DB_MASTER
);
3768 $dbw->update( 'user',
3770 'user_name' => $this->mName
,
3771 'user_real_name' => $this->mRealName
,
3772 'user_email' => $this->mEmail
,
3773 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3774 'user_touched' => $dbw->timestamp( $newTouched ),
3775 'user_token' => strval( $this->mToken
),
3776 'user_email_token' => $this->mEmailToken
,
3777 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
3779 'user_id' => $this->mId
,
3780 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
3784 if ( !$dbw->affectedRows() ) {
3785 // Maybe the problem was a missed cache update; clear it to be safe
3786 $this->clearSharedCache( 'refresh' );
3787 // User was changed in the meantime or loaded with stale data
3788 $from = ( $this->queryFlagsUsed
& self
::READ_LATEST
) ?
'master' : 'slave';
3789 throw new MWException(
3790 "CAS update failed on user_touched for user ID '{$this->mId}' (read from $from);" .
3791 " the version of the user to be saved is older than the current version."
3795 $this->mTouched
= $newTouched;
3796 $this->saveOptions();
3798 Hooks
::run( 'UserSaveSettings', [ $this ] );
3799 $this->clearSharedCache();
3800 $this->getUserPage()->invalidateCache();
3804 * If only this user's username is known, and it exists, return the user ID.
3806 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
3809 public function idForName( $flags = 0 ) {
3810 $s = trim( $this->getName() );
3815 $db = ( ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
)
3816 ?
wfGetDB( DB_MASTER
)
3817 : wfGetDB( DB_SLAVE
);
3819 $options = ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
)
3820 ?
[ 'LOCK IN SHARE MODE' ]
3823 $id = $db->selectField( 'user',
3824 'user_id', [ 'user_name' => $s ], __METHOD__
, $options );
3830 * Add a user to the database, return the user object
3832 * @param string $name Username to add
3833 * @param array $params Array of Strings Non-default parameters to save to
3834 * the database as user_* fields:
3835 * - email: The user's email address.
3836 * - email_authenticated: The email authentication timestamp.
3837 * - real_name: The user's real name.
3838 * - options: An associative array of non-default options.
3839 * - token: Random authentication token. Do not set.
3840 * - registration: Registration timestamp. Do not set.
3842 * @return User|null User object, or null if the username already exists.
3844 public static function createNew( $name, $params = [] ) {
3845 foreach ( [ 'password', 'newpassword', 'newpass_time', 'password_expires' ] as $field ) {
3846 if ( isset( $params[$field] ) ) {
3847 wfDeprecated( __METHOD__
. " with param '$field'", '1.27' );
3848 unset( $params[$field] );
3854 $user->setToken(); // init token
3855 if ( isset( $params['options'] ) ) {
3856 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
3857 unset( $params['options'] );
3859 $dbw = wfGetDB( DB_MASTER
);
3860 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3862 $noPass = PasswordFactory
::newInvalidPassword()->toString();
3865 'user_id' => $seqVal,
3866 'user_name' => $name,
3867 'user_password' => $noPass,
3868 'user_newpassword' => $noPass,
3869 'user_email' => $user->mEmail
,
3870 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
3871 'user_real_name' => $user->mRealName
,
3872 'user_token' => strval( $user->mToken
),
3873 'user_registration' => $dbw->timestamp( $user->mRegistration
),
3874 'user_editcount' => 0,
3875 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
3877 foreach ( $params as $name => $value ) {
3878 $fields["user_$name"] = $value;
3880 $dbw->insert( 'user', $fields, __METHOD__
, [ 'IGNORE' ] );
3881 if ( $dbw->affectedRows() ) {
3882 $newUser = User
::newFromId( $dbw->insertId() );
3890 * Add this existing user object to the database. If the user already
3891 * exists, a fatal status object is returned, and the user object is
3892 * initialised with the data from the database.
3894 * Previously, this function generated a DB error due to a key conflict
3895 * if the user already existed. Many extension callers use this function
3896 * in code along the lines of:
3898 * $user = User::newFromName( $name );
3899 * if ( !$user->isLoggedIn() ) {
3900 * $user->addToDatabase();
3902 * // do something with $user...
3904 * However, this was vulnerable to a race condition (bug 16020). By
3905 * initialising the user object if the user exists, we aim to support this
3906 * calling sequence as far as possible.
3908 * Note that if the user exists, this function will acquire a write lock,
3909 * so it is still advisable to make the call conditional on isLoggedIn(),
3910 * and to commit the transaction after calling.
3912 * @throws MWException
3915 public function addToDatabase() {
3917 if ( !$this->mToken
) {
3918 $this->setToken(); // init token
3921 $this->mTouched
= $this->newTouchedTimestamp();
3923 $noPass = PasswordFactory
::newInvalidPassword()->toString();
3925 $dbw = wfGetDB( DB_MASTER
);
3926 $inWrite = $dbw->writesOrCallbacksPending();
3927 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3928 $dbw->insert( 'user',
3930 'user_id' => $seqVal,
3931 'user_name' => $this->mName
,
3932 'user_password' => $noPass,
3933 'user_newpassword' => $noPass,
3934 'user_email' => $this->mEmail
,
3935 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3936 'user_real_name' => $this->mRealName
,
3937 'user_token' => strval( $this->mToken
),
3938 'user_registration' => $dbw->timestamp( $this->mRegistration
),
3939 'user_editcount' => 0,
3940 'user_touched' => $dbw->timestamp( $this->mTouched
),
3944 if ( !$dbw->affectedRows() ) {
3945 // The queries below cannot happen in the same REPEATABLE-READ snapshot.
3946 // Handle this by COMMIT, if possible, or by LOCK IN SHARE MODE otherwise.
3948 // Can't commit due to pending writes that may need atomicity.
3949 // This may cause some lock contention unlike the case below.
3950 $options = [ 'LOCK IN SHARE MODE' ];
3951 $flags = self
::READ_LOCKING
;
3953 // Often, this case happens early in views before any writes when
3954 // using CentralAuth. It's should be OK to commit and break the snapshot.
3955 $dbw->commit( __METHOD__
, 'flush' );
3957 $flags = self
::READ_LATEST
;
3959 $this->mId
= $dbw->selectField( 'user', 'user_id',
3960 [ 'user_name' => $this->mName
], __METHOD__
, $options );
3963 if ( $this->loadFromDatabase( $flags ) ) {
3968 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
3969 "to insert user '{$this->mName}' row, but it was not present in select!" );
3971 return Status
::newFatal( 'userexists' );
3973 $this->mId
= $dbw->insertId();
3974 self
::$idCacheByName[$this->mName
] = $this->mId
;
3976 // Clear instance cache other than user table data, which is already accurate
3977 $this->clearInstanceCache();
3979 $this->saveOptions();
3980 return Status
::newGood();
3984 * If this user is logged-in and blocked,
3985 * block any IP address they've successfully logged in from.
3986 * @return bool A block was spread
3988 public function spreadAnyEditBlock() {
3989 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3990 return $this->spreadBlock();
3996 * If this (non-anonymous) user is blocked,
3997 * block the IP address they've successfully logged in from.
3998 * @return bool A block was spread
4000 protected function spreadBlock() {
4001 wfDebug( __METHOD__
. "()\n" );
4003 if ( $this->mId
== 0 ) {
4007 $userblock = Block
::newFromTarget( $this->getName() );
4008 if ( !$userblock ) {
4012 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
4016 * Get whether the user is explicitly blocked from account creation.
4017 * @return bool|Block
4019 public function isBlockedFromCreateAccount() {
4020 $this->getBlockedStatus();
4021 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
4022 return $this->mBlock
;
4025 # bug 13611: if the IP address the user is trying to create an account from is
4026 # blocked with createaccount disabled, prevent new account creation there even
4027 # when the user is logged in
4028 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
4029 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
4031 return $this->mBlockedFromCreateAccount
instanceof Block
4032 && $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
4033 ?
$this->mBlockedFromCreateAccount
4038 * Get whether the user is blocked from using Special:Emailuser.
4041 public function isBlockedFromEmailuser() {
4042 $this->getBlockedStatus();
4043 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
4047 * Get whether the user is allowed to create an account.
4050 public function isAllowedToCreateAccount() {
4051 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
4055 * Get this user's personal page title.
4057 * @return Title User's personal page title
4059 public function getUserPage() {
4060 return Title
::makeTitle( NS_USER
, $this->getName() );
4064 * Get this user's talk page title.
4066 * @return Title User's talk page title
4068 public function getTalkPage() {
4069 $title = $this->getUserPage();
4070 return $title->getTalkPage();
4074 * Determine whether the user is a newbie. Newbies are either
4075 * anonymous IPs, or the most recently created accounts.
4078 public function isNewbie() {
4079 return !$this->isAllowed( 'autoconfirmed' );
4083 * Check to see if the given clear-text password is one of the accepted passwords
4084 * @deprecated since 1.27. AuthManager is coming.
4085 * @param string $password User password
4086 * @return bool True if the given password is correct, otherwise False
4088 public function checkPassword( $password ) {
4089 global $wgAuth, $wgLegacyEncoding;
4093 // Some passwords will give a fatal Status, which means there is
4094 // some sort of technical or security reason for this password to
4095 // be completely invalid and should never be checked (e.g., T64685)
4096 if ( !$this->checkPasswordValidity( $password )->isOK() ) {
4100 // Certain authentication plugins do NOT want to save
4101 // domain passwords in a mysql database, so we should
4102 // check this (in case $wgAuth->strict() is false).
4103 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
4105 } elseif ( $wgAuth->strict() ) {
4106 // Auth plugin doesn't allow local authentication
4108 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
4109 // Auth plugin doesn't allow local authentication for this user name
4113 $passwordFactory = new PasswordFactory();
4114 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4115 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
4116 ?
wfGetDB( DB_MASTER
)
4117 : wfGetDB( DB_SLAVE
);
4120 $mPassword = $passwordFactory->newFromCiphertext( $db->selectField(
4121 'user', 'user_password', [ 'user_id' => $this->getId() ], __METHOD__
4123 } catch ( PasswordError
$e ) {
4124 wfDebug( 'Invalid password hash found in database.' );
4125 $mPassword = PasswordFactory
::newInvalidPassword();
4128 if ( !$mPassword->equals( $password ) ) {
4129 if ( $wgLegacyEncoding ) {
4130 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
4131 // Check for this with iconv
4132 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
4133 if ( $cp1252Password === $password ||
!$mPassword->equals( $cp1252Password ) ) {
4141 if ( $passwordFactory->needsUpdate( $mPassword ) && !wfReadOnly() ) {
4142 $this->setPasswordInternal( $password );
4149 * Check if the given clear-text password matches the temporary password
4150 * sent by e-mail for password reset operations.
4152 * @deprecated since 1.27. AuthManager is coming.
4153 * @param string $plaintext
4154 * @return bool True if matches, false otherwise
4156 public function checkTemporaryPassword( $plaintext ) {
4157 global $wgNewPasswordExpiry;
4161 $passwordFactory = new PasswordFactory();
4162 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4163 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
4164 ?
wfGetDB( DB_MASTER
)
4165 : wfGetDB( DB_SLAVE
);
4167 $row = $db->selectRow(
4169 [ 'user_newpassword', 'user_newpass_time' ],
4170 [ 'user_id' => $this->getId() ],
4174 $newPassword = $passwordFactory->newFromCiphertext( $row->user_newpassword
);
4175 } catch ( PasswordError
$e ) {
4176 wfDebug( 'Invalid password hash found in database.' );
4177 $newPassword = PasswordFactory
::newInvalidPassword();
4180 if ( $newPassword->equals( $plaintext ) ) {
4181 if ( is_null( $row->user_newpass_time
) ) {
4184 $expiry = wfTimestamp( TS_UNIX
, $row->user_newpass_time
) +
$wgNewPasswordExpiry;
4185 return ( time() < $expiry );
4192 * Initialize (if necessary) and return a session token value
4193 * which can be used in edit forms to show that the user's
4194 * login credentials aren't being hijacked with a foreign form
4198 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4199 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4200 * @return MediaWiki\\Session\\Token The new edit token
4202 public function getEditTokenObject( $salt = '', $request = null ) {
4203 if ( $this->isAnon() ) {
4204 return new LoggedOutEditToken();
4208 $request = $this->getRequest();
4210 return $request->getSession()->getToken( $salt );
4214 * Initialize (if necessary) and return a session token value
4215 * which can be used in edit forms to show that the user's
4216 * login credentials aren't being hijacked with a foreign form
4220 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4221 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4222 * @return string The new edit token
4224 public function getEditToken( $salt = '', $request = null ) {
4225 return $this->getEditTokenObject( $salt, $request )->toString();
4229 * Get the embedded timestamp from a token.
4230 * @deprecated since 1.27, use \\MediaWiki\\Session\\Token::getTimestamp instead.
4231 * @param string $val Input token
4234 public static function getEditTokenTimestamp( $val ) {
4235 wfDeprecated( __METHOD__
, '1.27' );
4236 return MediaWiki\Session\Token
::getTimestamp( $val );
4240 * Check given value against the token value stored in the session.
4241 * A match should confirm that the form was submitted from the
4242 * user's own login session, not a form submission from a third-party
4245 * @param string $val Input value to compare
4246 * @param string $salt Optional function-specific data for hashing
4247 * @param WebRequest|null $request Object to use or null to use $wgRequest
4248 * @param int $maxage Fail tokens older than this, in seconds
4249 * @return bool Whether the token matches
4251 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4252 return $this->getEditTokenObject( $salt, $request )->match( $val, $maxage );
4256 * Check given value against the token value stored in the session,
4257 * ignoring the suffix.
4259 * @param string $val Input value to compare
4260 * @param string $salt Optional function-specific data for hashing
4261 * @param WebRequest|null $request Object to use or null to use $wgRequest
4262 * @param int $maxage Fail tokens older than this, in seconds
4263 * @return bool Whether the token matches
4265 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4266 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . self
::EDIT_TOKEN_SUFFIX
;
4267 return $this->matchEditToken( $val, $salt, $request, $maxage );
4271 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4272 * mail to the user's given address.
4274 * @param string $type Message to send, either "created", "changed" or "set"
4277 public function sendConfirmationMail( $type = 'created' ) {
4279 $expiration = null; // gets passed-by-ref and defined in next line.
4280 $token = $this->confirmationToken( $expiration );
4281 $url = $this->confirmationTokenUrl( $token );
4282 $invalidateURL = $this->invalidationTokenUrl( $token );
4283 $this->saveSettings();
4285 if ( $type == 'created' ||
$type === false ) {
4286 $message = 'confirmemail_body';
4287 } elseif ( $type === true ) {
4288 $message = 'confirmemail_body_changed';
4290 // Messages: confirmemail_body_changed, confirmemail_body_set
4291 $message = 'confirmemail_body_' . $type;
4294 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4295 wfMessage( $message,
4296 $this->getRequest()->getIP(),
4299 $wgLang->userTimeAndDate( $expiration, $this ),
4301 $wgLang->userDate( $expiration, $this ),
4302 $wgLang->userTime( $expiration, $this ) )->text() );
4306 * Send an e-mail to this user's account. Does not check for
4307 * confirmed status or validity.
4309 * @param string $subject Message subject
4310 * @param string $body Message body
4311 * @param User|null $from Optional sending user; if unspecified, default
4312 * $wgPasswordSender will be used.
4313 * @param string $replyto Reply-To address
4316 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4317 global $wgPasswordSender;
4319 if ( $from instanceof User
) {
4320 $sender = MailAddress
::newFromUser( $from );
4322 $sender = new MailAddress( $wgPasswordSender,
4323 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4325 $to = MailAddress
::newFromUser( $this );
4327 return UserMailer
::send( $to, $sender, $subject, $body, [
4328 'replyTo' => $replyto,
4333 * Generate, store, and return a new e-mail confirmation code.
4334 * A hash (unsalted, since it's used as a key) is stored.
4336 * @note Call saveSettings() after calling this function to commit
4337 * this change to the database.
4339 * @param string &$expiration Accepts the expiration time
4340 * @return string New token
4342 protected function confirmationToken( &$expiration ) {
4343 global $wgUserEmailConfirmationTokenExpiry;
4345 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4346 $expiration = wfTimestamp( TS_MW
, $expires );
4348 $token = MWCryptRand
::generateHex( 32 );
4349 $hash = md5( $token );
4350 $this->mEmailToken
= $hash;
4351 $this->mEmailTokenExpires
= $expiration;
4356 * Return a URL the user can use to confirm their email address.
4357 * @param string $token Accepts the email confirmation token
4358 * @return string New token URL
4360 protected function confirmationTokenUrl( $token ) {
4361 return $this->getTokenUrl( 'ConfirmEmail', $token );
4365 * Return a URL the user can use to invalidate their email address.
4366 * @param string $token Accepts the email confirmation token
4367 * @return string New token URL
4369 protected function invalidationTokenUrl( $token ) {
4370 return $this->getTokenUrl( 'InvalidateEmail', $token );
4374 * Internal function to format the e-mail validation/invalidation URLs.
4375 * This uses a quickie hack to use the
4376 * hardcoded English names of the Special: pages, for ASCII safety.
4378 * @note Since these URLs get dropped directly into emails, using the
4379 * short English names avoids insanely long URL-encoded links, which
4380 * also sometimes can get corrupted in some browsers/mailers
4381 * (bug 6957 with Gmail and Internet Explorer).
4383 * @param string $page Special page
4384 * @param string $token Token
4385 * @return string Formatted URL
4387 protected function getTokenUrl( $page, $token ) {
4388 // Hack to bypass localization of 'Special:'
4389 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4390 return $title->getCanonicalURL();
4394 * Mark the e-mail address confirmed.
4396 * @note Call saveSettings() after calling this function to commit the change.
4400 public function confirmEmail() {
4401 // Check if it's already confirmed, so we don't touch the database
4402 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4403 if ( !$this->isEmailConfirmed() ) {
4404 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4405 Hooks
::run( 'ConfirmEmailComplete', [ $this ] );
4411 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4412 * address if it was already confirmed.
4414 * @note Call saveSettings() after calling this function to commit the change.
4415 * @return bool Returns true
4417 public function invalidateEmail() {
4419 $this->mEmailToken
= null;
4420 $this->mEmailTokenExpires
= null;
4421 $this->setEmailAuthenticationTimestamp( null );
4423 Hooks
::run( 'InvalidateEmailComplete', [ $this ] );
4428 * Set the e-mail authentication timestamp.
4429 * @param string $timestamp TS_MW timestamp
4431 public function setEmailAuthenticationTimestamp( $timestamp ) {
4433 $this->mEmailAuthenticated
= $timestamp;
4434 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
4438 * Is this user allowed to send e-mails within limits of current
4439 * site configuration?
4442 public function canSendEmail() {
4443 global $wgEnableEmail, $wgEnableUserEmail;
4444 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4447 $canSend = $this->isEmailConfirmed();
4448 Hooks
::run( 'UserCanSendEmail', [ &$this, &$canSend ] );
4453 * Is this user allowed to receive e-mails within limits of current
4454 * site configuration?
4457 public function canReceiveEmail() {
4458 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4462 * Is this user's e-mail address valid-looking and confirmed within
4463 * limits of the current site configuration?
4465 * @note If $wgEmailAuthentication is on, this may require the user to have
4466 * confirmed their address by returning a code or using a password
4467 * sent to the address from the wiki.
4471 public function isEmailConfirmed() {
4472 global $wgEmailAuthentication;
4475 if ( Hooks
::run( 'EmailConfirmed', [ &$this, &$confirmed ] ) ) {
4476 if ( $this->isAnon() ) {
4479 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4482 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4492 * Check whether there is an outstanding request for e-mail confirmation.
4495 public function isEmailConfirmationPending() {
4496 global $wgEmailAuthentication;
4497 return $wgEmailAuthentication &&
4498 !$this->isEmailConfirmed() &&
4499 $this->mEmailToken
&&
4500 $this->mEmailTokenExpires
> wfTimestamp();
4504 * Get the timestamp of account creation.
4506 * @return string|bool|null Timestamp of account creation, false for
4507 * non-existent/anonymous user accounts, or null if existing account
4508 * but information is not in database.
4510 public function getRegistration() {
4511 if ( $this->isAnon() ) {
4515 return $this->mRegistration
;
4519 * Get the timestamp of the first edit
4521 * @return string|bool Timestamp of first edit, or false for
4522 * non-existent/anonymous user accounts.
4524 public function getFirstEditTimestamp() {
4525 if ( $this->getId() == 0 ) {
4526 return false; // anons
4528 $dbr = wfGetDB( DB_SLAVE
);
4529 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4530 [ 'rev_user' => $this->getId() ],
4532 [ 'ORDER BY' => 'rev_timestamp ASC' ]
4535 return false; // no edits
4537 return wfTimestamp( TS_MW
, $time );
4541 * Get the permissions associated with a given list of groups
4543 * @param array $groups Array of Strings List of internal group names
4544 * @return array Array of Strings List of permission key names for given groups combined
4546 public static function getGroupPermissions( $groups ) {
4547 global $wgGroupPermissions, $wgRevokePermissions;
4549 // grant every granted permission first
4550 foreach ( $groups as $group ) {
4551 if ( isset( $wgGroupPermissions[$group] ) ) {
4552 $rights = array_merge( $rights,
4553 // array_filter removes empty items
4554 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4557 // now revoke the revoked permissions
4558 foreach ( $groups as $group ) {
4559 if ( isset( $wgRevokePermissions[$group] ) ) {
4560 $rights = array_diff( $rights,
4561 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4564 return array_unique( $rights );
4568 * Get all the groups who have a given permission
4570 * @param string $role Role to check
4571 * @return array Array of Strings List of internal group names with the given permission
4573 public static function getGroupsWithPermission( $role ) {
4574 global $wgGroupPermissions;
4575 $allowedGroups = [];
4576 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4577 if ( self
::groupHasPermission( $group, $role ) ) {
4578 $allowedGroups[] = $group;
4581 return $allowedGroups;
4585 * Check, if the given group has the given permission
4587 * If you're wanting to check whether all users have a permission, use
4588 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4592 * @param string $group Group to check
4593 * @param string $role Role to check
4596 public static function groupHasPermission( $group, $role ) {
4597 global $wgGroupPermissions, $wgRevokePermissions;
4598 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4599 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4603 * Check if all users may be assumed to have the given permission
4605 * We generally assume so if the right is granted to '*' and isn't revoked
4606 * on any group. It doesn't attempt to take grants or other extension
4607 * limitations on rights into account in the general case, though, as that
4608 * would require it to always return false and defeat the purpose.
4609 * Specifically, session-based rights restrictions (such as OAuth or bot
4610 * passwords) are applied based on the current session.
4613 * @param string $right Right to check
4616 public static function isEveryoneAllowed( $right ) {
4617 global $wgGroupPermissions, $wgRevokePermissions;
4620 // Use the cached results, except in unit tests which rely on
4621 // being able change the permission mid-request
4622 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4623 return $cache[$right];
4626 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4627 $cache[$right] = false;
4631 // If it's revoked anywhere, then everyone doesn't have it
4632 foreach ( $wgRevokePermissions as $rights ) {
4633 if ( isset( $rights[$right] ) && $rights[$right] ) {
4634 $cache[$right] = false;
4639 // Remove any rights that aren't allowed to the global-session user,
4640 // unless there are no sessions for this endpoint.
4641 if ( !defined( 'MW_NO_SESSION' ) ) {
4642 $allowedRights = SessionManager
::getGlobalSession()->getAllowedUserRights();
4643 if ( $allowedRights !== null && !in_array( $right, $allowedRights, true ) ) {
4644 $cache[$right] = false;
4649 // Allow extensions to say false
4650 if ( !Hooks
::run( 'UserIsEveryoneAllowed', [ $right ] ) ) {
4651 $cache[$right] = false;
4655 $cache[$right] = true;
4660 * Get the localized descriptive name for a group, if it exists
4662 * @param string $group Internal group name
4663 * @return string Localized descriptive group name
4665 public static function getGroupName( $group ) {
4666 $msg = wfMessage( "group-$group" );
4667 return $msg->isBlank() ?
$group : $msg->text();
4671 * Get the localized descriptive name for a member of a group, if it exists
4673 * @param string $group Internal group name
4674 * @param string $username Username for gender (since 1.19)
4675 * @return string Localized name for group member
4677 public static function getGroupMember( $group, $username = '#' ) {
4678 $msg = wfMessage( "group-$group-member", $username );
4679 return $msg->isBlank() ?
$group : $msg->text();
4683 * Return the set of defined explicit groups.
4684 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4685 * are not included, as they are defined automatically, not in the database.
4686 * @return array Array of internal group names
4688 public static function getAllGroups() {
4689 global $wgGroupPermissions, $wgRevokePermissions;
4691 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4692 self
::getImplicitGroups()
4697 * Get a list of all available permissions.
4698 * @return string[] Array of permission names
4700 public static function getAllRights() {
4701 if ( self
::$mAllRights === false ) {
4702 global $wgAvailableRights;
4703 if ( count( $wgAvailableRights ) ) {
4704 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
4706 self
::$mAllRights = self
::$mCoreRights;
4708 Hooks
::run( 'UserGetAllRights', [ &self
::$mAllRights ] );
4710 return self
::$mAllRights;
4714 * Get a list of implicit groups
4715 * @return array Array of Strings Array of internal group names
4717 public static function getImplicitGroups() {
4718 global $wgImplicitGroups;
4720 $groups = $wgImplicitGroups;
4721 # Deprecated, use $wgImplicitGroups instead
4722 Hooks
::run( 'UserGetImplicitGroups', [ &$groups ], '1.25' );
4728 * Get the title of a page describing a particular group
4730 * @param string $group Internal group name
4731 * @return Title|bool Title of the page if it exists, false otherwise
4733 public static function getGroupPage( $group ) {
4734 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4735 if ( $msg->exists() ) {
4736 $title = Title
::newFromText( $msg->text() );
4737 if ( is_object( $title ) ) {
4745 * Create a link to the group in HTML, if available;
4746 * else return the group name.
4748 * @param string $group Internal name of the group
4749 * @param string $text The text of the link
4750 * @return string HTML link to the group
4752 public static function makeGroupLinkHTML( $group, $text = '' ) {
4753 if ( $text == '' ) {
4754 $text = self
::getGroupName( $group );
4756 $title = self
::getGroupPage( $group );
4758 return Linker
::link( $title, htmlspecialchars( $text ) );
4760 return htmlspecialchars( $text );
4765 * Create a link to the group in Wikitext, if available;
4766 * else return the group name.
4768 * @param string $group Internal name of the group
4769 * @param string $text The text of the link
4770 * @return string Wikilink to the group
4772 public static function makeGroupLinkWiki( $group, $text = '' ) {
4773 if ( $text == '' ) {
4774 $text = self
::getGroupName( $group );
4776 $title = self
::getGroupPage( $group );
4778 $page = $title->getFullText();
4779 return "[[$page|$text]]";
4786 * Returns an array of the groups that a particular group can add/remove.
4788 * @param string $group The group to check for whether it can add/remove
4789 * @return array Array( 'add' => array( addablegroups ),
4790 * 'remove' => array( removablegroups ),
4791 * 'add-self' => array( addablegroups to self),
4792 * 'remove-self' => array( removable groups from self) )
4794 public static function changeableByGroup( $group ) {
4795 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4804 if ( empty( $wgAddGroups[$group] ) ) {
4805 // Don't add anything to $groups
4806 } elseif ( $wgAddGroups[$group] === true ) {
4807 // You get everything
4808 $groups['add'] = self
::getAllGroups();
4809 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4810 $groups['add'] = $wgAddGroups[$group];
4813 // Same thing for remove
4814 if ( empty( $wgRemoveGroups[$group] ) ) {
4816 } elseif ( $wgRemoveGroups[$group] === true ) {
4817 $groups['remove'] = self
::getAllGroups();
4818 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4819 $groups['remove'] = $wgRemoveGroups[$group];
4822 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4823 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4824 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4825 if ( is_int( $key ) ) {
4826 $wgGroupsAddToSelf['user'][] = $value;
4831 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
4832 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4833 if ( is_int( $key ) ) {
4834 $wgGroupsRemoveFromSelf['user'][] = $value;
4839 // Now figure out what groups the user can add to him/herself
4840 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4842 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4843 // No idea WHY this would be used, but it's there
4844 $groups['add-self'] = User
::getAllGroups();
4845 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4846 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4849 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4851 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4852 $groups['remove-self'] = User
::getAllGroups();
4853 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4854 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4861 * Returns an array of groups that this user can add and remove
4862 * @return array Array( 'add' => array( addablegroups ),
4863 * 'remove' => array( removablegroups ),
4864 * 'add-self' => array( addablegroups to self),
4865 * 'remove-self' => array( removable groups from self) )
4867 public function changeableGroups() {
4868 if ( $this->isAllowed( 'userrights' ) ) {
4869 // This group gives the right to modify everything (reverse-
4870 // compatibility with old "userrights lets you change
4872 // Using array_merge to make the groups reindexed
4873 $all = array_merge( User
::getAllGroups() );
4882 // Okay, it's not so simple, we will have to go through the arrays
4889 $addergroups = $this->getEffectiveGroups();
4891 foreach ( $addergroups as $addergroup ) {
4892 $groups = array_merge_recursive(
4893 $groups, $this->changeableByGroup( $addergroup )
4895 $groups['add'] = array_unique( $groups['add'] );
4896 $groups['remove'] = array_unique( $groups['remove'] );
4897 $groups['add-self'] = array_unique( $groups['add-self'] );
4898 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4904 * Deferred version of incEditCountImmediate()
4906 public function incEditCount() {
4907 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle( function() {
4908 $this->incEditCountImmediate();
4913 * Increment the user's edit-count field.
4914 * Will have no effect for anonymous users.
4917 public function incEditCountImmediate() {
4918 if ( $this->isAnon() ) {
4922 $dbw = wfGetDB( DB_MASTER
);
4923 // No rows will be "affected" if user_editcount is NULL
4926 [ 'user_editcount=user_editcount+1' ],
4927 [ 'user_id' => $this->getId(), 'user_editcount IS NOT NULL' ],
4930 // Lazy initialization check...
4931 if ( $dbw->affectedRows() == 0 ) {
4932 // Now here's a goddamn hack...
4933 $dbr = wfGetDB( DB_SLAVE
);
4934 if ( $dbr !== $dbw ) {
4935 // If we actually have a slave server, the count is
4936 // at least one behind because the current transaction
4937 // has not been committed and replicated.
4938 $this->initEditCount( 1 );
4940 // But if DB_SLAVE is selecting the master, then the
4941 // count we just read includes the revision that was
4942 // just added in the working transaction.
4943 $this->initEditCount();
4946 // Edit count in user cache too
4947 $this->invalidateCache();
4951 * Initialize user_editcount from data out of the revision table
4953 * @param int $add Edits to add to the count from the revision table
4954 * @return int Number of edits
4956 protected function initEditCount( $add = 0 ) {
4957 // Pull from a slave to be less cruel to servers
4958 // Accuracy isn't the point anyway here
4959 $dbr = wfGetDB( DB_SLAVE
);
4960 $count = (int)$dbr->selectField(
4963 [ 'rev_user' => $this->getId() ],
4966 $count = $count +
$add;
4968 $dbw = wfGetDB( DB_MASTER
);
4971 [ 'user_editcount' => $count ],
4972 [ 'user_id' => $this->getId() ],
4980 * Get the description of a given right
4982 * @param string $right Right to query
4983 * @return string Localized description of the right
4985 public static function getRightDescription( $right ) {
4986 $key = "right-$right";
4987 $msg = wfMessage( $key );
4988 return $msg->isBlank() ?
$right : $msg->text();
4992 * Make a new-style password hash
4994 * @param string $password Plain-text password
4995 * @param bool|string $salt Optional salt, may be random or the user ID.
4996 * If unspecified or false, will generate one automatically
4997 * @return string Password hash
4998 * @deprecated since 1.24, use Password class
5000 public static function crypt( $password, $salt = false ) {
5001 wfDeprecated( __METHOD__
, '1.24' );
5002 $passwordFactory = new PasswordFactory();
5003 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
5004 $hash = $passwordFactory->newFromPlaintext( $password );
5005 return $hash->toString();
5009 * Compare a password hash with a plain-text password. Requires the user
5010 * ID if there's a chance that the hash is an old-style hash.
5012 * @param string $hash Password hash
5013 * @param string $password Plain-text password to compare
5014 * @param string|bool $userId User ID for old-style password salt
5017 * @deprecated since 1.24, use Password class
5019 public static function comparePasswords( $hash, $password, $userId = false ) {
5020 wfDeprecated( __METHOD__
, '1.24' );
5022 // Check for *really* old password hashes that don't even have a type
5023 // The old hash format was just an md5 hex hash, with no type information
5024 if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) {
5025 global $wgPasswordSalt;
5026 if ( $wgPasswordSalt ) {
5027 $password = ":B:{$userId}:{$hash}";
5029 $password = ":A:{$hash}";
5033 $passwordFactory = new PasswordFactory();
5034 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
5035 $hash = $passwordFactory->newFromCiphertext( $hash );
5036 return $hash->equals( $password );
5040 * Add a newuser log entry for this user.
5041 * Before 1.19 the return value was always true.
5043 * @param string|bool $action Account creation type.
5044 * - String, one of the following values:
5045 * - 'create' for an anonymous user creating an account for himself.
5046 * This will force the action's performer to be the created user itself,
5047 * no matter the value of $wgUser
5048 * - 'create2' for a logged in user creating an account for someone else
5049 * - 'byemail' when the created user will receive its password by e-mail
5050 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
5051 * - Boolean means whether the account was created by e-mail (deprecated):
5052 * - true will be converted to 'byemail'
5053 * - false will be converted to 'create' if this object is the same as
5054 * $wgUser and to 'create2' otherwise
5056 * @param string $reason User supplied reason
5058 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
5060 public function addNewUserLogEntry( $action = false, $reason = '' ) {
5061 global $wgUser, $wgNewUserLog;
5062 if ( empty( $wgNewUserLog ) ) {
5063 return true; // disabled
5066 if ( $action === true ) {
5067 $action = 'byemail';
5068 } elseif ( $action === false ) {
5069 if ( $this->equals( $wgUser ) ) {
5072 $action = 'create2';
5076 if ( $action === 'create' ||
$action === 'autocreate' ) {
5079 $performer = $wgUser;
5082 $logEntry = new ManualLogEntry( 'newusers', $action );
5083 $logEntry->setPerformer( $performer );
5084 $logEntry->setTarget( $this->getUserPage() );
5085 $logEntry->setComment( $reason );
5086 $logEntry->setParameters( [
5087 '4::userid' => $this->getId(),
5089 $logid = $logEntry->insert();
5091 if ( $action !== 'autocreate' ) {
5092 $logEntry->publish( $logid );
5099 * Add an autocreate newuser log entry for this user
5100 * Used by things like CentralAuth and perhaps other authplugins.
5101 * Consider calling addNewUserLogEntry() directly instead.
5105 public function addNewUserLogEntryAutoCreate() {
5106 $this->addNewUserLogEntry( 'autocreate' );
5112 * Load the user options either from cache, the database or an array
5114 * @param array $data Rows for the current user out of the user_properties table
5116 protected function loadOptions( $data = null ) {
5121 if ( $this->mOptionsLoaded
) {
5125 $this->mOptions
= self
::getDefaultOptions();
5127 if ( !$this->getId() ) {
5128 // For unlogged-in users, load language/variant options from request.
5129 // There's no need to do it for logged-in users: they can set preferences,
5130 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5131 // so don't override user's choice (especially when the user chooses site default).
5132 $variant = $wgContLang->getDefaultVariant();
5133 $this->mOptions
['variant'] = $variant;
5134 $this->mOptions
['language'] = $variant;
5135 $this->mOptionsLoaded
= true;
5139 // Maybe load from the object
5140 if ( !is_null( $this->mOptionOverrides
) ) {
5141 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5142 foreach ( $this->mOptionOverrides
as $key => $value ) {
5143 $this->mOptions
[$key] = $value;
5146 if ( !is_array( $data ) ) {
5147 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5148 // Load from database
5149 $dbr = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
5150 ?
wfGetDB( DB_MASTER
)
5151 : wfGetDB( DB_SLAVE
);
5153 $res = $dbr->select(
5155 [ 'up_property', 'up_value' ],
5156 [ 'up_user' => $this->getId() ],
5160 $this->mOptionOverrides
= [];
5162 foreach ( $res as $row ) {
5163 $data[$row->up_property
] = $row->up_value
;
5166 foreach ( $data as $property => $value ) {
5167 $this->mOptionOverrides
[$property] = $value;
5168 $this->mOptions
[$property] = $value;
5172 $this->mOptionsLoaded
= true;
5174 Hooks
::run( 'UserLoadOptions', [ $this, &$this->mOptions
] );
5178 * Saves the non-default options for this user, as previously set e.g. via
5179 * setOption(), in the database's "user_properties" (preferences) table.
5180 * Usually used via saveSettings().
5182 protected function saveOptions() {
5183 $this->loadOptions();
5185 // Not using getOptions(), to keep hidden preferences in database
5186 $saveOptions = $this->mOptions
;
5188 // Allow hooks to abort, for instance to save to a global profile.
5189 // Reset options to default state before saving.
5190 if ( !Hooks
::run( 'UserSaveOptions', [ $this, &$saveOptions ] ) ) {
5194 $userId = $this->getId();
5196 $insert_rows = []; // all the new preference rows
5197 foreach ( $saveOptions as $key => $value ) {
5198 // Don't bother storing default values
5199 $defaultOption = self
::getDefaultOption( $key );
5200 if ( ( $defaultOption === null && $value !== false && $value !== null )
5201 ||
$value != $defaultOption
5204 'up_user' => $userId,
5205 'up_property' => $key,
5206 'up_value' => $value,
5211 $dbw = wfGetDB( DB_MASTER
);
5213 $res = $dbw->select( 'user_properties',
5214 [ 'up_property', 'up_value' ], [ 'up_user' => $userId ], __METHOD__
);
5216 // Find prior rows that need to be removed or updated. These rows will
5217 // all be deleted (the later so that INSERT IGNORE applies the new values).
5219 foreach ( $res as $row ) {
5220 if ( !isset( $saveOptions[$row->up_property
] )
5221 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
5223 $keysDelete[] = $row->up_property
;
5227 if ( count( $keysDelete ) ) {
5228 // Do the DELETE by PRIMARY KEY for prior rows.
5229 // In the past a very large portion of calls to this function are for setting
5230 // 'rememberpassword' for new accounts (a preference that has since been removed).
5231 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5232 // caused gap locks on [max user ID,+infinity) which caused high contention since
5233 // updates would pile up on each other as they are for higher (newer) user IDs.
5234 // It might not be necessary these days, but it shouldn't hurt either.
5235 $dbw->delete( 'user_properties',
5236 [ 'up_user' => $userId, 'up_property' => $keysDelete ], __METHOD__
);
5238 // Insert the new preference rows
5239 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, [ 'IGNORE' ] );
5243 * Lazily instantiate and return a factory object for making passwords
5245 * @deprecated since 1.27, create a PasswordFactory directly instead
5246 * @return PasswordFactory
5248 public static function getPasswordFactory() {
5249 wfDeprecated( __METHOD__
, '1.27' );
5250 $ret = new PasswordFactory();
5251 $ret->init( RequestContext
::getMain()->getConfig() );
5256 * Provide an array of HTML5 attributes to put on an input element
5257 * intended for the user to enter a new password. This may include
5258 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
5260 * Do *not* use this when asking the user to enter his current password!
5261 * Regardless of configuration, users may have invalid passwords for whatever
5262 * reason (e.g., they were set before requirements were tightened up).
5263 * Only use it when asking for a new password, like on account creation or
5266 * Obviously, you still need to do server-side checking.
5268 * NOTE: A combination of bugs in various browsers means that this function
5269 * actually just returns array() unconditionally at the moment. May as
5270 * well keep it around for when the browser bugs get fixed, though.
5272 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
5274 * @deprecated since 1.27
5275 * @return array Array of HTML attributes suitable for feeding to
5276 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
5277 * That will get confused by the boolean attribute syntax used.)
5279 public static function passwordChangeInputAttribs() {
5280 global $wgMinimalPasswordLength;
5282 if ( $wgMinimalPasswordLength == 0 ) {
5286 # Note that the pattern requirement will always be satisfied if the
5287 # input is empty, so we need required in all cases.
5289 # @todo FIXME: Bug 23769: This needs to not claim the password is required
5290 # if e-mail confirmation is being used. Since HTML5 input validation
5291 # is b0rked anyway in some browsers, just return nothing. When it's
5292 # re-enabled, fix this code to not output required for e-mail
5294 # $ret = array( 'required' );
5297 # We can't actually do this right now, because Opera 9.6 will print out
5298 # the entered password visibly in its error message! When other
5299 # browsers add support for this attribute, or Opera fixes its support,
5300 # we can add support with a version check to avoid doing this on Opera
5301 # versions where it will be a problem. Reported to Opera as
5302 # DSK-262266, but they don't have a public bug tracker for us to follow.
5304 if ( $wgMinimalPasswordLength > 1 ) {
5305 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
5306 $ret['title'] = wfMessage( 'passwordtooshort' )
5307 ->numParams( $wgMinimalPasswordLength )->text();
5315 * Return the list of user fields that should be selected to create
5316 * a new user object.
5319 public static function selectFields() {
5327 'user_email_authenticated',
5329 'user_email_token_expires',
5330 'user_registration',
5336 * Factory function for fatal permission-denied errors
5339 * @param string $permission User right required
5342 static function newFatalPermissionDeniedStatus( $permission ) {
5345 $groups = array_map(
5346 [ 'User', 'makeGroupLinkWiki' ],
5347 User
::getGroupsWithPermission( $permission )
5351 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5353 return Status
::newFatal( 'badaccess-group0' );
5358 * Get a new instance of this user that was loaded from the master via a locking read
5360 * Use this instead of the main context User when updating that user. This avoids races
5361 * where that user was loaded from a slave or even the master but without proper locks.
5363 * @return User|null Returns null if the user was not found in the DB
5366 public function getInstanceForUpdate() {
5367 if ( !$this->getId() ) {
5368 return null; // anon
5371 $user = self
::newFromId( $this->getId() );
5372 if ( !$user->loadFromId( self
::READ_EXCLUSIVE
) ) {
5380 * Checks if two user objects point to the same user.
5386 public function equals( User
$user ) {
5387 return $this->getName() === $user->getName();