3 * Implements the User class for the %MediaWiki software.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use MediaWiki\Session\SessionManager
;
26 * String Some punctuation to prevent editing from broken text-mangling proxies.
27 * @deprecated since 1.27, use \\MediaWiki\\Session\\Token::SUFFIX
30 define( 'EDIT_TOKEN_SUFFIX', MediaWiki\Session\Token
::SUFFIX
);
33 * The User object encapsulates all of the user-specific settings (user_id,
34 * name, rights, email address, options, last login time). Client
35 * classes use the getXXX() functions to access these fields. These functions
36 * do all the work of determining whether the user is logged in,
37 * whether the requested option can be satisfied from cookies or
38 * whether a database query is needed. Most of the settings needed
39 * for rendering normal pages are set in the cookie to minimize use
42 class User
implements IDBAccessObject
{
44 * @const int Number of characters in user_token field.
46 const TOKEN_LENGTH
= 32;
49 * @const string An invalid value for user_token
51 const INVALID_TOKEN
= '*** INVALID ***';
54 * Global constant made accessible as class constants so that autoloader
56 * @deprecated since 1.27, use \\MediaWiki\\Session\\Token::SUFFIX
58 const EDIT_TOKEN_SUFFIX
= EDIT_TOKEN_SUFFIX
;
61 * @const int Serialized record version.
66 * Maximum items in $mWatchedItems
68 const MAX_WATCHED_ITEMS_CACHE
= 100;
71 * Exclude user options that are set to their default value.
74 const GETOPTIONS_EXCLUDE_DEFAULTS
= 1;
77 * Array of Strings List of member variables which are saved to the
78 * shared cache (memcached). Any operation which changes the
79 * corresponding database fields must call a cache-clearing function.
82 protected static $mCacheVars = [
90 'mEmailAuthenticated',
97 // user_properties table
102 * Array of Strings Core rights.
103 * Each of these should have a corresponding message of the form
107 protected static $mCoreRights = [
137 'editusercssjs', # deprecated
150 'move-categorypages',
151 'move-rootuserpages',
155 'override-export-depth',
178 'userrights-interwiki',
186 * String Cached results of getAllRights()
188 protected static $mAllRights = false;
190 /** Cache variables */
200 /** @var string TS_MW timestamp from the DB */
202 /** @var string TS_MW timestamp from cache */
203 protected $mQuickTouched;
207 public $mEmailAuthenticated;
209 protected $mEmailToken;
211 protected $mEmailTokenExpires;
213 protected $mRegistration;
215 protected $mEditCount;
219 protected $mOptionOverrides;
223 * Bool Whether the cache variables have been loaded.
226 public $mOptionsLoaded;
229 * Array with already loaded items or true if all items have been loaded.
231 protected $mLoadedItems = [];
235 * String Initialization data source if mLoadedItems!==true. May be one of:
236 * - 'defaults' anonymous user initialised from class defaults
237 * - 'name' initialise from mName
238 * - 'id' initialise from mId
239 * - 'session' log in from session if possible
241 * Use the User::newFrom*() family of functions to set this.
246 * Lazy-initialized variables, invalidated with clearInstanceCache
250 protected $mDatePreference;
258 protected $mBlockreason;
260 protected $mEffectiveGroups;
262 protected $mImplicitGroups;
264 protected $mFormerGroups;
266 protected $mBlockedGlobally;
283 protected $mAllowUsertalk;
286 private $mBlockedFromCreateAccount = false;
289 private $mWatchedItems = [];
291 /** @var integer User::READ_* constant bitfield used to load data */
292 protected $queryFlagsUsed = self
::READ_NORMAL
;
294 public static $idCacheByName = [];
297 * Lightweight constructor for an anonymous user.
298 * Use the User::newFrom* factory functions for other kinds of users.
302 * @see newFromConfirmationCode()
303 * @see newFromSession()
306 public function __construct() {
307 $this->clearInstanceCache( 'defaults' );
313 public function __toString() {
314 return $this->getName();
318 * Test if it's safe to load this User object.
320 * You should typically check this before using $wgUser or
321 * RequestContext::getUser in a method that might be called before the
322 * system has been fully initialized. If the object is unsafe, you should
323 * use an anonymous user:
325 * $user = $wgUser->isSafeToLoad() ? $wgUser : new User;
331 public function isSafeToLoad() {
332 global $wgFullyInitialised;
334 // The user is safe to load if:
335 // * MW_NO_SESSION is undefined AND $wgFullyInitialised is true (safe to use session data)
336 // * mLoadedItems === true (already loaded)
337 // * mFrom !== 'session' (sessions not involved at all)
339 return ( !defined( 'MW_NO_SESSION' ) && $wgFullyInitialised ) ||
340 $this->mLoadedItems
=== true ||
$this->mFrom
!== 'session';
344 * Load the user table data for this object from the source given by mFrom.
346 * @param integer $flags User::READ_* constant bitfield
348 public function load( $flags = self
::READ_NORMAL
) {
349 global $wgFullyInitialised;
351 if ( $this->mLoadedItems
=== true ) {
355 // Set it now to avoid infinite recursion in accessors
356 $oldLoadedItems = $this->mLoadedItems
;
357 $this->mLoadedItems
= true;
358 $this->queryFlagsUsed
= $flags;
360 // If this is called too early, things are likely to break.
361 if ( !$wgFullyInitialised && $this->mFrom
=== 'session' ) {
362 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
363 ->warning( 'User::loadFromSession called before the end of Setup.php', [
364 'exception' => new Exception( 'User::loadFromSession called before the end of Setup.php' ),
366 $this->loadDefaults();
367 $this->mLoadedItems
= $oldLoadedItems;
371 switch ( $this->mFrom
) {
373 $this->loadDefaults();
376 // Make sure this thread sees its own changes
377 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
378 $flags |
= self
::READ_LATEST
;
379 $this->queryFlagsUsed
= $flags;
382 $this->mId
= self
::idFromName( $this->mName
, $flags );
384 // Nonexistent user placeholder object
385 $this->loadDefaults( $this->mName
);
387 $this->loadFromId( $flags );
391 $this->loadFromId( $flags );
394 if ( !$this->loadFromSession() ) {
395 // Loading from session failed. Load defaults.
396 $this->loadDefaults();
398 Hooks
::run( 'UserLoadAfterLoadFromSession', [ $this ] );
401 throw new UnexpectedValueException(
402 "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
407 * Load user table data, given mId has already been set.
408 * @param integer $flags User::READ_* constant bitfield
409 * @return bool False if the ID does not exist, true otherwise
411 public function loadFromId( $flags = self
::READ_NORMAL
) {
412 if ( $this->mId
== 0 ) {
413 $this->loadDefaults();
417 // Try cache (unless this needs data from the master DB).
418 // NOTE: if this thread called saveSettings(), the cache was cleared.
419 $latest = DBAccessObjectUtils
::hasFlags( $flags, self
::READ_LATEST
);
420 if ( $latest ||
!$this->loadFromCache() ) {
421 wfDebug( "User: cache miss for user {$this->mId}\n" );
422 // Load from DB (make sure this thread sees its own changes)
423 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
424 $flags |
= self
::READ_LATEST
;
426 if ( !$this->loadFromDatabase( $flags ) ) {
427 // Can't load from ID, user is anonymous
430 $this->saveToCache();
433 $this->mLoadedItems
= true;
434 $this->queryFlagsUsed
= $flags;
441 * @param string $wikiId
442 * @param integer $userId
444 public static function purge( $wikiId, $userId ) {
445 $cache = ObjectCache
::getMainWANInstance();
446 $cache->delete( $cache->makeGlobalKey( 'user', 'id', $wikiId, $userId ) );
451 * @param WANObjectCache $cache
454 protected function getCacheKey( WANObjectCache
$cache ) {
455 return $cache->makeGlobalKey( 'user', 'id', wfWikiID(), $this->mId
);
459 * Load user data from shared cache, given mId has already been set.
461 * @return bool false if the ID does not exist or data is invalid, true otherwise
464 protected function loadFromCache() {
465 if ( $this->mId
== 0 ) {
466 $this->loadDefaults();
470 $cache = ObjectCache
::getMainWANInstance();
471 $data = $cache->get( $this->getCacheKey( $cache ) );
472 if ( !is_array( $data ) ||
$data['mVersion'] < self
::VERSION
) {
477 wfDebug( "User: got user {$this->mId} from cache\n" );
479 // Restore from cache
480 foreach ( self
::$mCacheVars as $name ) {
481 $this->$name = $data[$name];
488 * Save user data to the shared cache
490 * This method should not be called outside the User class
492 public function saveToCache() {
495 $this->loadOptions();
497 if ( $this->isAnon() ) {
498 // Anonymous users are uncached
503 foreach ( self
::$mCacheVars as $name ) {
504 $data[$name] = $this->$name;
506 $data['mVersion'] = self
::VERSION
;
507 $opts = Database
::getCacheSetOptions( wfGetDB( DB_SLAVE
) );
509 $cache = ObjectCache
::getMainWANInstance();
510 $key = $this->getCacheKey( $cache );
511 $cache->set( $key, $data, $cache::TTL_HOUR
, $opts );
514 /** @name newFrom*() static factory methods */
518 * Static factory method for creation from username.
520 * This is slightly less efficient than newFromId(), so use newFromId() if
521 * you have both an ID and a name handy.
523 * @param string $name Username, validated by Title::newFromText()
524 * @param string|bool $validate Validate username. Takes the same parameters as
525 * User::getCanonicalName(), except that true is accepted as an alias
526 * for 'valid', for BC.
528 * @return User|bool User object, or false if the username is invalid
529 * (e.g. if it contains illegal characters or is an IP address). If the
530 * username is not present in the database, the result will be a user object
531 * with a name, zero user ID and default settings.
533 public static function newFromName( $name, $validate = 'valid' ) {
534 if ( $validate === true ) {
537 $name = self
::getCanonicalName( $name, $validate );
538 if ( $name === false ) {
541 // Create unloaded user object
545 $u->setItemLoaded( 'name' );
551 * Static factory method for creation from a given user ID.
553 * @param int $id Valid user ID
554 * @return User The corresponding User object
556 public static function newFromId( $id ) {
560 $u->setItemLoaded( 'id' );
565 * Factory method to fetch whichever user has a given email confirmation code.
566 * This code is generated when an account is created or its e-mail address
569 * If the code is invalid or has expired, returns NULL.
571 * @param string $code Confirmation code
572 * @param int $flags User::READ_* bitfield
575 public static function newFromConfirmationCode( $code, $flags = 0 ) {
576 $db = ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
577 ?
wfGetDB( DB_MASTER
)
578 : wfGetDB( DB_SLAVE
);
580 $id = $db->selectField(
584 'user_email_token' => md5( $code ),
585 'user_email_token_expires > ' . $db->addQuotes( $db->timestamp() ),
589 return $id ? User
::newFromId( $id ) : null;
593 * Create a new user object using data from session. If the login
594 * credentials are invalid, the result is an anonymous user.
596 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
599 public static function newFromSession( WebRequest
$request = null ) {
601 $user->mFrom
= 'session';
602 $user->mRequest
= $request;
607 * Create a new user object from a user row.
608 * The row should have the following fields from the user table in it:
609 * - either user_name or user_id to load further data if needed (or both)
611 * - all other fields (email, etc.)
612 * It is useless to provide the remaining fields if either user_id,
613 * user_name and user_real_name are not provided because the whole row
614 * will be loaded once more from the database when accessing them.
616 * @param stdClass $row A row from the user table
617 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
620 public static function newFromRow( $row, $data = null ) {
622 $user->loadFromRow( $row, $data );
627 * Static factory method for creation of a "system" user from username.
629 * A "system" user is an account that's used to attribute logged actions
630 * taken by MediaWiki itself, as opposed to a bot or human user. Examples
631 * might include the 'Maintenance script' or 'Conversion script' accounts
632 * used by various scripts in the maintenance/ directory or accounts such
633 * as 'MediaWiki message delivery' used by the MassMessage extension.
635 * This can optionally create the user if it doesn't exist, and "steal" the
636 * account if it does exist.
638 * @param string $name Username
639 * @param array $options Options are:
640 * - validate: As for User::getCanonicalName(), default 'valid'
641 * - create: Whether to create the user if it doesn't already exist, default true
642 * - steal: Whether to reset the account's password and email if it
643 * already exists, default false
646 public static function newSystemUser( $name, $options = [] ) {
648 'validate' => 'valid',
653 $name = self
::getCanonicalName( $name, $options['validate'] );
654 if ( $name === false ) {
658 $dbw = wfGetDB( DB_MASTER
);
659 $row = $dbw->selectRow(
662 self
::selectFields(),
663 [ 'user_password', 'user_newpassword' ]
665 [ 'user_name' => $name ],
669 // No user. Create it?
670 return $options['create'] ? self
::createNew( $name ) : null;
672 $user = self
::newFromRow( $row );
674 // A user is considered to exist as a non-system user if it has a
675 // password set, or a temporary password set, or an email set, or a
676 // non-invalid token.
677 $passwordFactory = new PasswordFactory();
678 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
680 $password = $passwordFactory->newFromCiphertext( $row->user_password
);
681 } catch ( PasswordError
$e ) {
682 wfDebug( 'Invalid password hash found in database.' );
683 $password = PasswordFactory
::newInvalidPassword();
686 $newpassword = $passwordFactory->newFromCiphertext( $row->user_newpassword
);
687 } catch ( PasswordError
$e ) {
688 wfDebug( 'Invalid password hash found in database.' );
689 $newpassword = PasswordFactory
::newInvalidPassword();
691 if ( !$password instanceof InvalidPassword ||
!$newpassword instanceof InvalidPassword
692 ||
$user->mEmail ||
$user->mToken
!== self
::INVALID_TOKEN
694 // User exists. Steal it?
695 if ( !$options['steal'] ) {
699 $nopass = PasswordFactory
::newInvalidPassword()->toString();
704 'user_password' => $nopass,
705 'user_newpassword' => $nopass,
706 'user_newpass_time' => null,
708 [ 'user_id' => $user->getId() ],
711 $user->invalidateEmail();
712 $user->mToken
= self
::INVALID_TOKEN
;
713 $user->saveSettings();
714 SessionManager
::singleton()->preventSessionsForUser( $user->getName() );
723 * Get the username corresponding to a given user ID
724 * @param int $id User ID
725 * @return string|bool The corresponding username
727 public static function whoIs( $id ) {
728 return UserCache
::singleton()->getProp( $id, 'name' );
732 * Get the real name of a user given their user ID
734 * @param int $id User ID
735 * @return string|bool The corresponding user's real name
737 public static function whoIsReal( $id ) {
738 return UserCache
::singleton()->getProp( $id, 'real_name' );
742 * Get database id given a user name
743 * @param string $name Username
744 * @param integer $flags User::READ_* constant bitfield
745 * @return int|null The corresponding user's ID, or null if user is nonexistent
747 public static function idFromName( $name, $flags = self
::READ_NORMAL
) {
748 $nt = Title
::makeTitleSafe( NS_USER
, $name );
749 if ( is_null( $nt ) ) {
754 if ( !( $flags & self
::READ_LATEST
) && isset( self
::$idCacheByName[$name] ) ) {
755 return self
::$idCacheByName[$name];
758 $db = ( $flags & self
::READ_LATEST
)
759 ?
wfGetDB( DB_MASTER
)
760 : wfGetDB( DB_SLAVE
);
765 [ 'user_name' => $nt->getText() ],
769 if ( $s === false ) {
772 $result = $s->user_id
;
775 self
::$idCacheByName[$name] = $result;
777 if ( count( self
::$idCacheByName ) > 1000 ) {
778 self
::$idCacheByName = [];
785 * Reset the cache used in idFromName(). For use in tests.
787 public static function resetIdByNameCache() {
788 self
::$idCacheByName = [];
792 * Does the string match an anonymous IPv4 address?
794 * This function exists for username validation, in order to reject
795 * usernames which are similar in form to IP addresses. Strings such
796 * as 300.300.300.300 will return true because it looks like an IP
797 * address, despite not being strictly valid.
799 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
800 * address because the usemod software would "cloak" anonymous IP
801 * addresses like this, if we allowed accounts like this to be created
802 * new users could get the old edits of these anonymous users.
804 * @param string $name Name to match
807 public static function isIP( $name ) {
808 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
809 || IP
::isIPv6( $name );
813 * Is the input a valid username?
815 * Checks if the input is a valid username, we don't want an empty string,
816 * an IP address, anything that contains slashes (would mess up subpages),
817 * is longer than the maximum allowed username size or doesn't begin with
820 * @param string $name Name to match
823 public static function isValidUserName( $name ) {
824 global $wgContLang, $wgMaxNameChars;
827 || User
::isIP( $name )
828 ||
strpos( $name, '/' ) !== false
829 ||
strlen( $name ) > $wgMaxNameChars
830 ||
$name != $wgContLang->ucfirst( $name )
832 wfDebugLog( 'username', __METHOD__
.
833 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
837 // Ensure that the name can't be misresolved as a different title,
838 // such as with extra namespace keys at the start.
839 $parsed = Title
::newFromText( $name );
840 if ( is_null( $parsed )
841 ||
$parsed->getNamespace()
842 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
843 wfDebugLog( 'username', __METHOD__
.
844 ": '$name' invalid due to ambiguous prefixes" );
848 // Check an additional blacklist of troublemaker characters.
849 // Should these be merged into the title char list?
850 $unicodeBlacklist = '/[' .
851 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
852 '\x{00a0}' . # non-breaking space
853 '\x{2000}-\x{200f}' . # various whitespace
854 '\x{2028}-\x{202f}' . # breaks and control chars
855 '\x{3000}' . # ideographic space
856 '\x{e000}-\x{f8ff}' . # private use
858 if ( preg_match( $unicodeBlacklist, $name ) ) {
859 wfDebugLog( 'username', __METHOD__
.
860 ": '$name' invalid due to blacklisted characters" );
868 * Usernames which fail to pass this function will be blocked
869 * from user login and new account registrations, but may be used
870 * internally by batch processes.
872 * If an account already exists in this form, login will be blocked
873 * by a failure to pass this function.
875 * @param string $name Name to match
878 public static function isUsableName( $name ) {
879 global $wgReservedUsernames;
880 // Must be a valid username, obviously ;)
881 if ( !self
::isValidUserName( $name ) ) {
885 static $reservedUsernames = false;
886 if ( !$reservedUsernames ) {
887 $reservedUsernames = $wgReservedUsernames;
888 Hooks
::run( 'UserGetReservedNames', [ &$reservedUsernames ] );
891 // Certain names may be reserved for batch processes.
892 foreach ( $reservedUsernames as $reserved ) {
893 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
894 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
896 if ( $reserved == $name ) {
904 * Usernames which fail to pass this function will be blocked
905 * from new account registrations, but may be used internally
906 * either by batch processes or by user accounts which have
907 * already been created.
909 * Additional blacklisting may be added here rather than in
910 * isValidUserName() to avoid disrupting existing accounts.
912 * @param string $name String to match
915 public static function isCreatableName( $name ) {
916 global $wgInvalidUsernameCharacters;
918 // Ensure that the username isn't longer than 235 bytes, so that
919 // (at least for the builtin skins) user javascript and css files
920 // will work. (bug 23080)
921 if ( strlen( $name ) > 235 ) {
922 wfDebugLog( 'username', __METHOD__
.
923 ": '$name' invalid due to length" );
927 // Preg yells if you try to give it an empty string
928 if ( $wgInvalidUsernameCharacters !== '' ) {
929 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
930 wfDebugLog( 'username', __METHOD__
.
931 ": '$name' invalid due to wgInvalidUsernameCharacters" );
936 return self
::isUsableName( $name );
940 * Is the input a valid password for this user?
942 * @param string $password Desired password
945 public function isValidPassword( $password ) {
946 // simple boolean wrapper for getPasswordValidity
947 return $this->getPasswordValidity( $password ) === true;
951 * Given unvalidated password input, return error message on failure.
953 * @param string $password Desired password
954 * @return bool|string|array True on success, string or array of error message on failure
956 public function getPasswordValidity( $password ) {
957 $result = $this->checkPasswordValidity( $password );
958 if ( $result->isGood() ) {
962 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
963 $messages[] = $error['message'];
965 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
966 $messages[] = $warning['message'];
968 if ( count( $messages ) === 1 ) {
976 * Check if this is a valid password for this user
978 * Create a Status object based on the password's validity.
979 * The Status should be set to fatal if the user should not
980 * be allowed to log in, and should have any errors that
981 * would block changing the password.
983 * If the return value of this is not OK, the password
984 * should not be checked. If the return value is not Good,
985 * the password can be checked, but the user should not be
986 * able to set their password to this.
988 * @param string $password Desired password
989 * @param string $purpose one of 'login', 'create', 'reset'
993 public function checkPasswordValidity( $password, $purpose = 'login' ) {
994 global $wgPasswordPolicy;
996 $upp = new UserPasswordPolicy(
997 $wgPasswordPolicy['policies'],
998 $wgPasswordPolicy['checks']
1001 $status = Status
::newGood();
1002 $result = false; // init $result to false for the internal checks
1004 if ( !Hooks
::run( 'isValidPassword', [ $password, &$result, $this ] ) ) {
1005 $status->error( $result );
1009 if ( $result === false ) {
1010 $status->merge( $upp->checkUserPassword( $this, $password, $purpose ) );
1012 } elseif ( $result === true ) {
1015 $status->error( $result );
1016 return $status; // the isValidPassword hook set a string $result and returned true
1021 * Given unvalidated user input, return a canonical username, or false if
1022 * the username is invalid.
1023 * @param string $name User input
1024 * @param string|bool $validate Type of validation to use:
1025 * - false No validation
1026 * - 'valid' Valid for batch processes
1027 * - 'usable' Valid for batch processes and login
1028 * - 'creatable' Valid for batch processes, login and account creation
1030 * @throws InvalidArgumentException
1031 * @return bool|string
1033 public static function getCanonicalName( $name, $validate = 'valid' ) {
1034 // Force usernames to capital
1036 $name = $wgContLang->ucfirst( $name );
1038 # Reject names containing '#'; these will be cleaned up
1039 # with title normalisation, but then it's too late to
1041 if ( strpos( $name, '#' ) !== false ) {
1045 // Clean up name according to title rules,
1046 // but only when validation is requested (bug 12654)
1047 $t = ( $validate !== false ) ?
1048 Title
::newFromText( $name ) : Title
::makeTitle( NS_USER
, $name );
1049 // Check for invalid titles
1050 if ( is_null( $t ) ) {
1054 // Reject various classes of invalid names
1056 $name = $wgAuth->getCanonicalName( $t->getText() );
1058 switch ( $validate ) {
1062 if ( !User
::isValidUserName( $name ) ) {
1067 if ( !User
::isUsableName( $name ) ) {
1072 if ( !User
::isCreatableName( $name ) ) {
1077 throw new InvalidArgumentException(
1078 'Invalid parameter value for $validate in ' . __METHOD__
);
1084 * Count the number of edits of a user
1086 * @param int $uid User ID to check
1087 * @return int The user's edit count
1089 * @deprecated since 1.21 in favour of User::getEditCount
1091 public static function edits( $uid ) {
1092 wfDeprecated( __METHOD__
, '1.21' );
1093 $user = self
::newFromId( $uid );
1094 return $user->getEditCount();
1098 * Return a random password.
1100 * @deprecated since 1.27, use PasswordFactory::generateRandomPasswordString()
1101 * @return string New random password
1103 public static function randomPassword() {
1104 global $wgMinimalPasswordLength;
1105 return PasswordFactory
::generateRandomPasswordString( $wgMinimalPasswordLength );
1109 * Set cached properties to default.
1111 * @note This no longer clears uncached lazy-initialised properties;
1112 * the constructor does that instead.
1114 * @param string|bool $name
1116 public function loadDefaults( $name = false ) {
1118 $this->mName
= $name;
1119 $this->mRealName
= '';
1121 $this->mOptionOverrides
= null;
1122 $this->mOptionsLoaded
= false;
1124 $loggedOut = $this->mRequest
&& !defined( 'MW_NO_SESSION' )
1125 ?
$this->mRequest
->getSession()->getLoggedOutTimestamp() : 0;
1126 if ( $loggedOut !== 0 ) {
1127 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1129 $this->mTouched
= '1'; # Allow any pages to be cached
1132 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1133 $this->mEmailAuthenticated
= null;
1134 $this->mEmailToken
= '';
1135 $this->mEmailTokenExpires
= null;
1136 $this->mRegistration
= wfTimestamp( TS_MW
);
1137 $this->mGroups
= [];
1139 Hooks
::run( 'UserLoadDefaults', [ $this, $name ] );
1143 * Return whether an item has been loaded.
1145 * @param string $item Item to check. Current possibilities:
1149 * @param string $all 'all' to check if the whole object has been loaded
1150 * or any other string to check if only the item is available (e.g.
1154 public function isItemLoaded( $item, $all = 'all' ) {
1155 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1156 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1160 * Set that an item has been loaded
1162 * @param string $item
1164 protected function setItemLoaded( $item ) {
1165 if ( is_array( $this->mLoadedItems
) ) {
1166 $this->mLoadedItems
[$item] = true;
1171 * Load user data from the session.
1173 * @return bool True if the user is logged in, false otherwise.
1175 private function loadFromSession() {
1178 Hooks
::run( 'UserLoadFromSession', [ $this, &$result ], '1.27' );
1179 if ( $result !== null ) {
1183 // MediaWiki\Session\Session already did the necessary authentication of the user
1184 // returned here, so just use it if applicable.
1185 $session = $this->getRequest()->getSession();
1186 $user = $session->getUser();
1187 if ( $user->isLoggedIn() ) {
1188 $this->loadFromUserObject( $user );
1189 // Other code expects these to be set in the session, so set them.
1190 $session->set( 'wsUserID', $this->getId() );
1191 $session->set( 'wsUserName', $this->getName() );
1192 $session->set( 'wsToken', $this->getToken() );
1200 * Load user and user_group data from the database.
1201 * $this->mId must be set, this is how the user is identified.
1203 * @param integer $flags User::READ_* constant bitfield
1204 * @return bool True if the user exists, false if the user is anonymous
1206 public function loadFromDatabase( $flags = self
::READ_LATEST
) {
1208 $this->mId
= intval( $this->mId
);
1211 if ( !$this->mId
) {
1212 $this->loadDefaults();
1216 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
1217 $db = wfGetDB( $index );
1219 $s = $db->selectRow(
1221 self
::selectFields(),
1222 [ 'user_id' => $this->mId
],
1227 $this->queryFlagsUsed
= $flags;
1228 Hooks
::run( 'UserLoadFromDatabase', [ $this, &$s ] );
1230 if ( $s !== false ) {
1231 // Initialise user table data
1232 $this->loadFromRow( $s );
1233 $this->mGroups
= null; // deferred
1234 $this->getEditCount(); // revalidation for nulls
1239 $this->loadDefaults();
1245 * Initialize this object from a row from the user table.
1247 * @param stdClass $row Row from the user table to load.
1248 * @param array $data Further user data to load into the object
1250 * user_groups Array with groups out of the user_groups table
1251 * user_properties Array with properties out of the user_properties table
1253 protected function loadFromRow( $row, $data = null ) {
1256 $this->mGroups
= null; // deferred
1258 if ( isset( $row->user_name
) ) {
1259 $this->mName
= $row->user_name
;
1260 $this->mFrom
= 'name';
1261 $this->setItemLoaded( 'name' );
1266 if ( isset( $row->user_real_name
) ) {
1267 $this->mRealName
= $row->user_real_name
;
1268 $this->setItemLoaded( 'realname' );
1273 if ( isset( $row->user_id
) ) {
1274 $this->mId
= intval( $row->user_id
);
1275 $this->mFrom
= 'id';
1276 $this->setItemLoaded( 'id' );
1281 if ( isset( $row->user_id
) && isset( $row->user_name
) ) {
1282 self
::$idCacheByName[$row->user_name
] = $row->user_id
;
1285 if ( isset( $row->user_editcount
) ) {
1286 $this->mEditCount
= $row->user_editcount
;
1291 if ( isset( $row->user_touched
) ) {
1292 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1297 if ( isset( $row->user_token
) ) {
1298 // The definition for the column is binary(32), so trim the NULs
1299 // that appends. The previous definition was char(32), so trim
1301 $this->mToken
= rtrim( $row->user_token
, " \0" );
1302 if ( $this->mToken
=== '' ) {
1303 $this->mToken
= null;
1309 if ( isset( $row->user_email
) ) {
1310 $this->mEmail
= $row->user_email
;
1311 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1312 $this->mEmailToken
= $row->user_email_token
;
1313 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1314 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1320 $this->mLoadedItems
= true;
1323 if ( is_array( $data ) ) {
1324 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1325 $this->mGroups
= $data['user_groups'];
1327 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1328 $this->loadOptions( $data['user_properties'] );
1334 * Load the data for this user object from another user object.
1338 protected function loadFromUserObject( $user ) {
1340 $user->loadGroups();
1341 $user->loadOptions();
1342 foreach ( self
::$mCacheVars as $var ) {
1343 $this->$var = $user->$var;
1348 * Load the groups from the database if they aren't already loaded.
1350 private function loadGroups() {
1351 if ( is_null( $this->mGroups
) ) {
1352 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
1353 ?
wfGetDB( DB_MASTER
)
1354 : wfGetDB( DB_SLAVE
);
1355 $res = $db->select( 'user_groups',
1357 [ 'ug_user' => $this->mId
],
1359 $this->mGroups
= [];
1360 foreach ( $res as $row ) {
1361 $this->mGroups
[] = $row->ug_group
;
1367 * Add the user to the group if he/she meets given criteria.
1369 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1370 * possible to remove manually via Special:UserRights. In such case it
1371 * will not be re-added automatically. The user will also not lose the
1372 * group if they no longer meet the criteria.
1374 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1376 * @return array Array of groups the user has been promoted to.
1378 * @see $wgAutopromoteOnce
1380 public function addAutopromoteOnceGroups( $event ) {
1381 global $wgAutopromoteOnceLogInRC, $wgAuth;
1383 if ( wfReadOnly() ||
!$this->getId() ) {
1387 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1388 if ( !count( $toPromote ) ) {
1392 if ( !$this->checkAndSetTouched() ) {
1393 return []; // raced out (bug T48834)
1396 $oldGroups = $this->getGroups(); // previous groups
1397 foreach ( $toPromote as $group ) {
1398 $this->addGroup( $group );
1400 // update groups in external authentication database
1401 Hooks
::run( 'UserGroupsChanged', [ $this, $toPromote, [], false, false ] );
1402 $wgAuth->updateExternalDBGroups( $this, $toPromote );
1404 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1406 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1407 $logEntry->setPerformer( $this );
1408 $logEntry->setTarget( $this->getUserPage() );
1409 $logEntry->setParameters( [
1410 '4::oldgroups' => $oldGroups,
1411 '5::newgroups' => $newGroups,
1413 $logid = $logEntry->insert();
1414 if ( $wgAutopromoteOnceLogInRC ) {
1415 $logEntry->publish( $logid );
1422 * Bump user_touched if it didn't change since this object was loaded
1424 * On success, the mTouched field is updated.
1425 * The user serialization cache is always cleared.
1427 * @return bool Whether user_touched was actually updated
1430 protected function checkAndSetTouched() {
1433 if ( !$this->mId
) {
1434 return false; // anon
1437 // Get a new user_touched that is higher than the old one
1438 $oldTouched = $this->mTouched
;
1439 $newTouched = $this->newTouchedTimestamp();
1441 $dbw = wfGetDB( DB_MASTER
);
1442 $dbw->update( 'user',
1443 [ 'user_touched' => $dbw->timestamp( $newTouched ) ],
1445 'user_id' => $this->mId
,
1446 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
1450 $success = ( $dbw->affectedRows() > 0 );
1453 $this->mTouched
= $newTouched;
1454 $this->clearSharedCache();
1456 // Clears on failure too since that is desired if the cache is stale
1457 $this->clearSharedCache( 'refresh' );
1464 * Clear various cached data stored in this object. The cache of the user table
1465 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1467 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1468 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1470 public function clearInstanceCache( $reloadFrom = false ) {
1471 $this->mNewtalk
= -1;
1472 $this->mDatePreference
= null;
1473 $this->mBlockedby
= -1; # Unset
1474 $this->mHash
= false;
1475 $this->mRights
= null;
1476 $this->mEffectiveGroups
= null;
1477 $this->mImplicitGroups
= null;
1478 $this->mGroups
= null;
1479 $this->mOptions
= null;
1480 $this->mOptionsLoaded
= false;
1481 $this->mEditCount
= null;
1483 if ( $reloadFrom ) {
1484 $this->mLoadedItems
= [];
1485 $this->mFrom
= $reloadFrom;
1490 * Combine the language default options with any site-specific options
1491 * and add the default language variants.
1493 * @return array Array of String options
1495 public static function getDefaultOptions() {
1496 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1498 static $defOpt = null;
1499 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1500 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1501 // mid-request and see that change reflected in the return value of this function.
1502 // Which is insane and would never happen during normal MW operation
1506 $defOpt = $wgDefaultUserOptions;
1507 // Default language setting
1508 $defOpt['language'] = $wgContLang->getCode();
1509 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1510 $defOpt[$langCode == $wgContLang->getCode() ?
'variant' : "variant-$langCode"] = $langCode;
1512 foreach ( SearchEngine
::searchableNamespaces() as $nsnum => $nsname ) {
1513 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1515 $defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1517 Hooks
::run( 'UserGetDefaultOptions', [ &$defOpt ] );
1523 * Get a given default option value.
1525 * @param string $opt Name of option to retrieve
1526 * @return string Default option value
1528 public static function getDefaultOption( $opt ) {
1529 $defOpts = self
::getDefaultOptions();
1530 if ( isset( $defOpts[$opt] ) ) {
1531 return $defOpts[$opt];
1538 * Get blocking information
1539 * @param bool $bFromSlave Whether to check the slave database first.
1540 * To improve performance, non-critical checks are done against slaves.
1541 * Check when actually saving should be done against master.
1543 private function getBlockedStatus( $bFromSlave = true ) {
1544 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1546 if ( -1 != $this->mBlockedby
) {
1550 wfDebug( __METHOD__
. ": checking...\n" );
1552 // Initialize data...
1553 // Otherwise something ends up stomping on $this->mBlockedby when
1554 // things get lazy-loaded later, causing false positive block hits
1555 // due to -1 !== 0. Probably session-related... Nothing should be
1556 // overwriting mBlockedby, surely?
1559 # We only need to worry about passing the IP address to the Block generator if the
1560 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1561 # know which IP address they're actually coming from
1563 if ( !$this->isAllowed( 'ipblock-exempt' ) ) {
1564 // $wgUser->getName() only works after the end of Setup.php. Until
1565 // then, assume it's a logged-out user.
1566 $globalUserName = $wgUser->isSafeToLoad()
1567 ?
$wgUser->getName()
1568 : IP
::sanitizeIP( $wgUser->getRequest()->getIP() );
1569 if ( $this->getName() === $globalUserName ) {
1570 $ip = $this->getRequest()->getIP();
1575 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1578 if ( !$block instanceof Block
&& $ip !== null && !in_array( $ip, $wgProxyWhitelist ) ) {
1580 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1582 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1583 $block->mReason
= wfMessage( 'proxyblockreason' )->text();
1584 $block->setTarget( $ip );
1585 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1587 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1588 $block->mReason
= wfMessage( 'sorbsreason' )->text();
1589 $block->setTarget( $ip );
1593 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1594 if ( !$block instanceof Block
1595 && $wgApplyIpBlocksToXff
1597 && !in_array( $ip, $wgProxyWhitelist )
1599 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1600 $xff = array_map( 'trim', explode( ',', $xff ) );
1601 $xff = array_diff( $xff, [ $ip ] );
1602 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1603 $block = Block
::chooseBlock( $xffblocks, $xff );
1604 if ( $block instanceof Block
) {
1605 # Mangle the reason to alert the user that the block
1606 # originated from matching the X-Forwarded-For header.
1607 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->text();
1611 if ( $block instanceof Block
) {
1612 wfDebug( __METHOD__
. ": Found block.\n" );
1613 $this->mBlock
= $block;
1614 $this->mBlockedby
= $block->getByName();
1615 $this->mBlockreason
= $block->mReason
;
1616 $this->mHideName
= $block->mHideName
;
1617 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1619 $this->mBlockedby
= '';
1620 $this->mHideName
= 0;
1621 $this->mAllowUsertalk
= false;
1625 Hooks
::run( 'GetBlockedStatus', [ &$this ] );
1630 * Whether the given IP is in a DNS blacklist.
1632 * @param string $ip IP to check
1633 * @param bool $checkWhitelist Whether to check the whitelist first
1634 * @return bool True if blacklisted.
1636 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1637 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1639 if ( !$wgEnableDnsBlacklist ) {
1643 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1647 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1651 * Whether the given IP is in a given DNS blacklist.
1653 * @param string $ip IP to check
1654 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1655 * @return bool True if blacklisted.
1657 public function inDnsBlacklist( $ip, $bases ) {
1660 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1661 if ( IP
::isIPv4( $ip ) ) {
1662 // Reverse IP, bug 21255
1663 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1665 foreach ( (array)$bases as $base ) {
1667 // If we have an access key, use that too (ProjectHoneypot, etc.)
1669 if ( is_array( $base ) ) {
1670 if ( count( $base ) >= 2 ) {
1671 // Access key is 1, base URL is 0
1672 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1674 $host = "$ipReversed.{$base[0]}";
1676 $basename = $base[0];
1678 $host = "$ipReversed.$base";
1682 $ipList = gethostbynamel( $host );
1685 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
1689 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
1698 * Check if an IP address is in the local proxy list
1704 public static function isLocallyBlockedProxy( $ip ) {
1705 global $wgProxyList;
1707 if ( !$wgProxyList ) {
1711 if ( !is_array( $wgProxyList ) ) {
1712 // Load from the specified file
1713 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1716 if ( !is_array( $wgProxyList ) ) {
1718 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1720 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1721 // Old-style flipped proxy list
1730 * Is this user subject to rate limiting?
1732 * @return bool True if rate limited
1734 public function isPingLimitable() {
1735 global $wgRateLimitsExcludedIPs;
1736 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1737 // No other good way currently to disable rate limits
1738 // for specific IPs. :P
1739 // But this is a crappy hack and should die.
1742 return !$this->isAllowed( 'noratelimit' );
1746 * Primitive rate limits: enforce maximum actions per time period
1747 * to put a brake on flooding.
1749 * The method generates both a generic profiling point and a per action one
1750 * (suffix being "-$action".
1752 * @note When using a shared cache like memcached, IP-address
1753 * last-hit counters will be shared across wikis.
1755 * @param string $action Action to enforce; 'edit' if unspecified
1756 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1757 * @return bool True if a rate limiter was tripped
1759 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1760 // Call the 'PingLimiter' hook
1762 if ( !Hooks
::run( 'PingLimiter', [ &$this, $action, &$result, $incrBy ] ) ) {
1766 global $wgRateLimits;
1767 if ( !isset( $wgRateLimits[$action] ) ) {
1771 // Some groups shouldn't trigger the ping limiter, ever
1772 if ( !$this->isPingLimitable() ) {
1776 $limits = $wgRateLimits[$action];
1778 $id = $this->getId();
1780 $isNewbie = $this->isNewbie();
1784 if ( isset( $limits['anon'] ) ) {
1785 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1788 // limits for logged-in users
1789 if ( isset( $limits['user'] ) ) {
1790 $userLimit = $limits['user'];
1792 // limits for newbie logged-in users
1793 if ( $isNewbie && isset( $limits['newbie'] ) ) {
1794 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1798 // limits for anons and for newbie logged-in users
1801 if ( isset( $limits['ip'] ) ) {
1802 $ip = $this->getRequest()->getIP();
1803 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1805 // subnet-based limits
1806 if ( isset( $limits['subnet'] ) ) {
1807 $ip = $this->getRequest()->getIP();
1808 $subnet = IP
::getSubnet( $ip );
1809 if ( $subnet !== false ) {
1810 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1815 // Check for group-specific permissions
1816 // If more than one group applies, use the group with the highest limit ratio (max/period)
1817 foreach ( $this->getGroups() as $group ) {
1818 if ( isset( $limits[$group] ) ) {
1819 if ( $userLimit === false
1820 ||
$limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1822 $userLimit = $limits[$group];
1827 // Set the user limit key
1828 if ( $userLimit !== false ) {
1829 list( $max, $period ) = $userLimit;
1830 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
1831 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1834 // ip-based limits for all ping-limitable users
1835 if ( isset( $limits['ip-all'] ) ) {
1836 $ip = $this->getRequest()->getIP();
1837 // ignore if user limit is more permissive
1838 if ( $isNewbie ||
$userLimit === false
1839 ||
$limits['ip-all'][0] / $limits['ip-all'][1] > $userLimit[0] / $userLimit[1] ) {
1840 $keys["mediawiki:limiter:$action:ip-all:$ip"] = $limits['ip-all'];
1844 // subnet-based limits for all ping-limitable users
1845 if ( isset( $limits['subnet-all'] ) ) {
1846 $ip = $this->getRequest()->getIP();
1847 $subnet = IP
::getSubnet( $ip );
1848 if ( $subnet !== false ) {
1849 // ignore if user limit is more permissive
1850 if ( $isNewbie ||
$userLimit === false
1851 ||
$limits['ip-all'][0] / $limits['ip-all'][1]
1852 > $userLimit[0] / $userLimit[1] ) {
1853 $keys["mediawiki:limiter:$action:subnet-all:$subnet"] = $limits['subnet-all'];
1858 $cache = ObjectCache
::getLocalClusterInstance();
1861 foreach ( $keys as $key => $limit ) {
1862 list( $max, $period ) = $limit;
1863 $summary = "(limit $max in {$period}s)";
1864 $count = $cache->get( $key );
1867 if ( $count >= $max ) {
1868 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1869 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1872 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1875 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1876 if ( $incrBy > 0 ) {
1877 $cache->add( $key, 0, intval( $period ) ); // first ping
1880 if ( $incrBy > 0 ) {
1881 $cache->incr( $key, $incrBy );
1889 * Check if user is blocked
1891 * @param bool $bFromSlave Whether to check the slave database instead of
1892 * the master. Hacked from false due to horrible probs on site.
1893 * @return bool True if blocked, false otherwise
1895 public function isBlocked( $bFromSlave = true ) {
1896 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
1900 * Get the block affecting the user, or null if the user is not blocked
1902 * @param bool $bFromSlave Whether to check the slave database instead of the master
1903 * @return Block|null
1905 public function getBlock( $bFromSlave = true ) {
1906 $this->getBlockedStatus( $bFromSlave );
1907 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
1911 * Check if user is blocked from editing a particular article
1913 * @param Title $title Title to check
1914 * @param bool $bFromSlave Whether to check the slave database instead of the master
1917 public function isBlockedFrom( $title, $bFromSlave = false ) {
1918 global $wgBlockAllowsUTEdit;
1920 $blocked = $this->isBlocked( $bFromSlave );
1921 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
1922 // If a user's name is suppressed, they cannot make edits anywhere
1923 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName()
1924 && $title->getNamespace() == NS_USER_TALK
) {
1926 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
1929 Hooks
::run( 'UserIsBlockedFrom', [ $this, $title, &$blocked, &$allowUsertalk ] );
1935 * If user is blocked, return the name of the user who placed the block
1936 * @return string Name of blocker
1938 public function blockedBy() {
1939 $this->getBlockedStatus();
1940 return $this->mBlockedby
;
1944 * If user is blocked, return the specified reason for the block
1945 * @return string Blocking reason
1947 public function blockedFor() {
1948 $this->getBlockedStatus();
1949 return $this->mBlockreason
;
1953 * If user is blocked, return the ID for the block
1954 * @return int Block ID
1956 public function getBlockId() {
1957 $this->getBlockedStatus();
1958 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
1962 * Check if user is blocked on all wikis.
1963 * Do not use for actual edit permission checks!
1964 * This is intended for quick UI checks.
1966 * @param string $ip IP address, uses current client if none given
1967 * @return bool True if blocked, false otherwise
1969 public function isBlockedGlobally( $ip = '' ) {
1970 if ( $this->mBlockedGlobally
!== null ) {
1971 return $this->mBlockedGlobally
;
1973 // User is already an IP?
1974 if ( IP
::isIPAddress( $this->getName() ) ) {
1975 $ip = $this->getName();
1977 $ip = $this->getRequest()->getIP();
1980 Hooks
::run( 'UserIsBlockedGlobally', [ &$this, $ip, &$blocked ] );
1981 $this->mBlockedGlobally
= (bool)$blocked;
1982 return $this->mBlockedGlobally
;
1986 * Check if user account is locked
1988 * @return bool True if locked, false otherwise
1990 public function isLocked() {
1991 if ( $this->mLocked
!== null ) {
1992 return $this->mLocked
;
1995 $authUser = $wgAuth->getUserInstance( $this );
1996 $this->mLocked
= (bool)$authUser->isLocked();
1997 Hooks
::run( 'UserIsLocked', [ $this, &$this->mLocked
] );
1998 return $this->mLocked
;
2002 * Check if user account is hidden
2004 * @return bool True if hidden, false otherwise
2006 public function isHidden() {
2007 if ( $this->mHideName
!== null ) {
2008 return $this->mHideName
;
2010 $this->getBlockedStatus();
2011 if ( !$this->mHideName
) {
2013 $authUser = $wgAuth->getUserInstance( $this );
2014 $this->mHideName
= (bool)$authUser->isHidden();
2015 Hooks
::run( 'UserIsHidden', [ $this, &$this->mHideName
] );
2017 return $this->mHideName
;
2021 * Get the user's ID.
2022 * @return int The user's ID; 0 if the user is anonymous or nonexistent
2024 public function getId() {
2025 if ( $this->mId
=== null && $this->mName
!== null && User
::isIP( $this->mName
) ) {
2026 // Special case, we know the user is anonymous
2028 } elseif ( !$this->isItemLoaded( 'id' ) ) {
2029 // Don't load if this was initialized from an ID
2036 * Set the user and reload all fields according to a given ID
2037 * @param int $v User ID to reload
2039 public function setId( $v ) {
2041 $this->clearInstanceCache( 'id' );
2045 * Get the user name, or the IP of an anonymous user
2046 * @return string User's name or IP address
2048 public function getName() {
2049 if ( $this->isItemLoaded( 'name', 'only' ) ) {
2050 // Special case optimisation
2051 return $this->mName
;
2054 if ( $this->mName
=== false ) {
2056 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
2058 return $this->mName
;
2063 * Set the user name.
2065 * This does not reload fields from the database according to the given
2066 * name. Rather, it is used to create a temporary "nonexistent user" for
2067 * later addition to the database. It can also be used to set the IP
2068 * address for an anonymous user to something other than the current
2071 * @note User::newFromName() has roughly the same function, when the named user
2073 * @param string $str New user name to set
2075 public function setName( $str ) {
2077 $this->mName
= $str;
2081 * Get the user's name escaped by underscores.
2082 * @return string Username escaped by underscores.
2084 public function getTitleKey() {
2085 return str_replace( ' ', '_', $this->getName() );
2089 * Check if the user has new messages.
2090 * @return bool True if the user has new messages
2092 public function getNewtalk() {
2095 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2096 if ( $this->mNewtalk
=== -1 ) {
2097 $this->mNewtalk
= false; # reset talk page status
2099 // Check memcached separately for anons, who have no
2100 // entire User object stored in there.
2101 if ( !$this->mId
) {
2102 global $wgDisableAnonTalk;
2103 if ( $wgDisableAnonTalk ) {
2104 // Anon newtalk disabled by configuration.
2105 $this->mNewtalk
= false;
2107 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
2110 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2114 return (bool)$this->mNewtalk
;
2118 * Return the data needed to construct links for new talk page message
2119 * alerts. If there are new messages, this will return an associative array
2120 * with the following data:
2121 * wiki: The database name of the wiki
2122 * link: Root-relative link to the user's talk page
2123 * rev: The last talk page revision that the user has seen or null. This
2124 * is useful for building diff links.
2125 * If there are no new messages, it returns an empty array.
2126 * @note This function was designed to accomodate multiple talk pages, but
2127 * currently only returns a single link and revision.
2130 public function getNewMessageLinks() {
2132 if ( !Hooks
::run( 'UserRetrieveNewTalks', [ &$this, &$talks ] ) ) {
2134 } elseif ( !$this->getNewtalk() ) {
2137 $utp = $this->getTalkPage();
2138 $dbr = wfGetDB( DB_SLAVE
);
2139 // Get the "last viewed rev" timestamp from the oldest message notification
2140 $timestamp = $dbr->selectField( 'user_newtalk',
2141 'MIN(user_last_timestamp)',
2142 $this->isAnon() ?
[ 'user_ip' => $this->getName() ] : [ 'user_id' => $this->getID() ],
2144 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2145 return [ [ 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ] ];
2149 * Get the revision ID for the last talk page revision viewed by the talk
2151 * @return int|null Revision ID or null
2153 public function getNewMessageRevisionId() {
2154 $newMessageRevisionId = null;
2155 $newMessageLinks = $this->getNewMessageLinks();
2156 if ( $newMessageLinks ) {
2157 // Note: getNewMessageLinks() never returns more than a single link
2158 // and it is always for the same wiki, but we double-check here in
2159 // case that changes some time in the future.
2160 if ( count( $newMessageLinks ) === 1
2161 && $newMessageLinks[0]['wiki'] === wfWikiID()
2162 && $newMessageLinks[0]['rev']
2164 /** @var Revision $newMessageRevision */
2165 $newMessageRevision = $newMessageLinks[0]['rev'];
2166 $newMessageRevisionId = $newMessageRevision->getId();
2169 return $newMessageRevisionId;
2173 * Internal uncached check for new messages
2176 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2177 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2178 * @return bool True if the user has new messages
2180 protected function checkNewtalk( $field, $id ) {
2181 $dbr = wfGetDB( DB_SLAVE
);
2183 $ok = $dbr->selectField( 'user_newtalk', $field, [ $field => $id ], __METHOD__
);
2185 return $ok !== false;
2189 * Add or update the new messages flag
2190 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2191 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2192 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2193 * @return bool True if successful, false otherwise
2195 protected function updateNewtalk( $field, $id, $curRev = null ) {
2196 // Get timestamp of the talk page revision prior to the current one
2197 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2198 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2199 // Mark the user as having new messages since this revision
2200 $dbw = wfGetDB( DB_MASTER
);
2201 $dbw->insert( 'user_newtalk',
2202 [ $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ],
2205 if ( $dbw->affectedRows() ) {
2206 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2209 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2215 * Clear the new messages flag for the given user
2216 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2217 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2218 * @return bool True if successful, false otherwise
2220 protected function deleteNewtalk( $field, $id ) {
2221 $dbw = wfGetDB( DB_MASTER
);
2222 $dbw->delete( 'user_newtalk',
2225 if ( $dbw->affectedRows() ) {
2226 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2229 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2235 * Update the 'You have new messages!' status.
2236 * @param bool $val Whether the user has new messages
2237 * @param Revision $curRev New, as yet unseen revision of the user talk
2238 * page. Ignored if null or !$val.
2240 public function setNewtalk( $val, $curRev = null ) {
2241 if ( wfReadOnly() ) {
2246 $this->mNewtalk
= $val;
2248 if ( $this->isAnon() ) {
2250 $id = $this->getName();
2253 $id = $this->getId();
2257 $changed = $this->updateNewtalk( $field, $id, $curRev );
2259 $changed = $this->deleteNewtalk( $field, $id );
2263 $this->invalidateCache();
2268 * Generate a current or new-future timestamp to be stored in the
2269 * user_touched field when we update things.
2270 * @return string Timestamp in TS_MW format
2272 private function newTouchedTimestamp() {
2273 global $wgClockSkewFudge;
2275 $time = wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2276 if ( $this->mTouched
&& $time <= $this->mTouched
) {
2277 $time = wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $this->mTouched
) +
1 );
2284 * Clear user data from memcached
2286 * Use after applying updates to the database; caller's
2287 * responsibility to update user_touched if appropriate.
2289 * Called implicitly from invalidateCache() and saveSettings().
2291 * @param string $mode Use 'refresh' to clear now; otherwise before DB commit
2293 public function clearSharedCache( $mode = 'changed' ) {
2294 if ( !$this->getId() ) {
2298 $cache = ObjectCache
::getMainWANInstance();
2299 $key = $this->getCacheKey( $cache );
2300 if ( $mode === 'refresh' ) {
2301 $cache->delete( $key, 1 );
2303 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle( function() use ( $cache, $key ) {
2304 $cache->delete( $key );
2310 * Immediately touch the user data cache for this account
2312 * Calls touch() and removes account data from memcached
2314 public function invalidateCache() {
2316 $this->clearSharedCache();
2320 * Update the "touched" timestamp for the user
2322 * This is useful on various login/logout events when making sure that
2323 * a browser or proxy that has multiple tenants does not suffer cache
2324 * pollution where the new user sees the old users content. The value
2325 * of getTouched() is checked when determining 304 vs 200 responses.
2326 * Unlike invalidateCache(), this preserves the User object cache and
2327 * avoids database writes.
2331 public function touch() {
2332 $id = $this->getId();
2334 $key = wfMemcKey( 'user-quicktouched', 'id', $id );
2335 ObjectCache
::getMainWANInstance()->touchCheckKey( $key );
2336 $this->mQuickTouched
= null;
2341 * Validate the cache for this account.
2342 * @param string $timestamp A timestamp in TS_MW format
2345 public function validateCache( $timestamp ) {
2346 return ( $timestamp >= $this->getTouched() );
2350 * Get the user touched timestamp
2352 * Use this value only to validate caches via inequalities
2353 * such as in the case of HTTP If-Modified-Since response logic
2355 * @return string TS_MW Timestamp
2357 public function getTouched() {
2361 if ( $this->mQuickTouched
=== null ) {
2362 $key = wfMemcKey( 'user-quicktouched', 'id', $this->mId
);
2363 $cache = ObjectCache
::getMainWANInstance();
2365 $this->mQuickTouched
= wfTimestamp( TS_MW
, $cache->getCheckKeyTime( $key ) );
2368 return max( $this->mTouched
, $this->mQuickTouched
);
2371 return $this->mTouched
;
2375 * Get the user_touched timestamp field (time of last DB updates)
2376 * @return string TS_MW Timestamp
2379 public function getDBTouched() {
2382 return $this->mTouched
;
2386 * @deprecated Removed in 1.27.
2390 public function getPassword() {
2391 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2395 * @deprecated Removed in 1.27.
2399 public function getTemporaryPassword() {
2400 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2404 * Set the password and reset the random token.
2405 * Calls through to authentication plugin if necessary;
2406 * will have no effect if the auth plugin refuses to
2407 * pass the change through or if the legal password
2410 * As a special case, setting the password to null
2411 * wipes it, so the account cannot be logged in until
2412 * a new password is set, for instance via e-mail.
2414 * @deprecated since 1.27. AuthManager is coming.
2415 * @param string $str New password to set
2416 * @throws PasswordError On failure
2419 public function setPassword( $str ) {
2422 if ( $str !== null ) {
2423 if ( !$wgAuth->allowPasswordChange() ) {
2424 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2427 $status = $this->checkPasswordValidity( $str );
2428 if ( !$status->isGood() ) {
2429 throw new PasswordError( $status->getMessage()->text() );
2433 if ( !$wgAuth->setPassword( $this, $str ) ) {
2434 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2438 $this->setOption( 'watchlisttoken', false );
2439 $this->setPasswordInternal( $str );
2445 * Set the password and reset the random token unconditionally.
2447 * @deprecated since 1.27. AuthManager is coming.
2448 * @param string|null $str New password to set or null to set an invalid
2449 * password hash meaning that the user will not be able to log in
2450 * through the web interface.
2452 public function setInternalPassword( $str ) {
2455 if ( $wgAuth->allowSetLocalPassword() ) {
2457 $this->setOption( 'watchlisttoken', false );
2458 $this->setPasswordInternal( $str );
2463 * Actually set the password and such
2464 * @since 1.27 cannot set a password for a user not in the database
2465 * @param string|null $str New password to set or null to set an invalid
2466 * password hash meaning that the user will not be able to log in
2467 * through the web interface.
2469 private function setPasswordInternal( $str ) {
2470 $id = self
::idFromName( $this->getName(), self
::READ_LATEST
);
2472 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2475 $passwordFactory = new PasswordFactory();
2476 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
2477 $dbw = wfGetDB( DB_MASTER
);
2481 'user_password' => $passwordFactory->newFromPlaintext( $str )->toString(),
2482 'user_newpassword' => PasswordFactory
::newInvalidPassword()->toString(),
2483 'user_newpass_time' => $dbw->timestampOrNull( null ),
2491 // When the main password is changed, invalidate all bot passwords too
2492 BotPassword
::invalidateAllPasswordsForUser( $this->getName() );
2496 * Get the user's current token.
2497 * @param bool $forceCreation Force the generation of a new token if the
2498 * user doesn't have one (default=true for backwards compatibility).
2499 * @return string|null Token
2501 public function getToken( $forceCreation = true ) {
2502 global $wgAuthenticationTokenVersion;
2505 if ( !$this->mToken
&& $forceCreation ) {
2509 if ( !$this->mToken
) {
2510 // The user doesn't have a token, return null to indicate that.
2512 } elseif ( $this->mToken
=== self
::INVALID_TOKEN
) {
2513 // We return a random value here so existing token checks are very
2515 return MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2516 } elseif ( $wgAuthenticationTokenVersion === null ) {
2517 // $wgAuthenticationTokenVersion not in use, so return the raw secret
2518 return $this->mToken
;
2520 // $wgAuthenticationTokenVersion in use, so hmac it.
2521 $ret = MWCryptHash
::hmac( $wgAuthenticationTokenVersion, $this->mToken
, false );
2523 // The raw hash can be overly long. Shorten it up.
2524 $len = max( 32, self
::TOKEN_LENGTH
);
2525 if ( strlen( $ret ) < $len ) {
2526 // Should never happen, even md5 is 128 bits
2527 throw new \
UnexpectedValueException( 'Hmac returned less than 128 bits' );
2529 return substr( $ret, -$len );
2534 * Set the random token (used for persistent authentication)
2535 * Called from loadDefaults() among other places.
2537 * @param string|bool $token If specified, set the token to this value
2539 public function setToken( $token = false ) {
2541 if ( $this->mToken
=== self
::INVALID_TOKEN
) {
2542 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
2543 ->debug( __METHOD__
. ": Ignoring attempt to set token for system user \"$this\"" );
2544 } elseif ( !$token ) {
2545 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2547 $this->mToken
= $token;
2552 * Set the password for a password reminder or new account email
2554 * @deprecated since 1.27, AuthManager is coming
2555 * @param string $str New password to set or null to set an invalid
2556 * password hash meaning that the user will not be able to use it
2557 * @param bool $throttle If true, reset the throttle timestamp to the present
2559 public function setNewpassword( $str, $throttle = true ) {
2560 $id = $this->getId();
2562 throw new LogicException( 'Cannot set new password for a user that is not in the database.' );
2565 $dbw = wfGetDB( DB_MASTER
);
2567 $passwordFactory = new PasswordFactory();
2568 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
2570 'user_newpassword' => $passwordFactory->newFromPlaintext( $str )->toString(),
2573 if ( $str === null ) {
2574 $update['user_newpass_time'] = null;
2575 } elseif ( $throttle ) {
2576 $update['user_newpass_time'] = $dbw->timestamp();
2579 $dbw->update( 'user', $update, [ 'user_id' => $id ], __METHOD__
);
2583 * Has password reminder email been sent within the last
2584 * $wgPasswordReminderResendTime hours?
2587 public function isPasswordReminderThrottled() {
2588 global $wgPasswordReminderResendTime;
2590 if ( !$wgPasswordReminderResendTime ) {
2596 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
2597 ?
wfGetDB( DB_MASTER
)
2598 : wfGetDB( DB_SLAVE
);
2599 $newpassTime = $db->selectField(
2601 'user_newpass_time',
2602 [ 'user_id' => $this->getId() ],
2606 if ( $newpassTime === null ) {
2609 $expiry = wfTimestamp( TS_UNIX
, $newpassTime ) +
$wgPasswordReminderResendTime * 3600;
2610 return time() < $expiry;
2614 * Get the user's e-mail address
2615 * @return string User's email address
2617 public function getEmail() {
2619 Hooks
::run( 'UserGetEmail', [ $this, &$this->mEmail
] );
2620 return $this->mEmail
;
2624 * Get the timestamp of the user's e-mail authentication
2625 * @return string TS_MW timestamp
2627 public function getEmailAuthenticationTimestamp() {
2629 Hooks
::run( 'UserGetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
2630 return $this->mEmailAuthenticated
;
2634 * Set the user's e-mail address
2635 * @param string $str New e-mail address
2637 public function setEmail( $str ) {
2639 if ( $str == $this->mEmail
) {
2642 $this->invalidateEmail();
2643 $this->mEmail
= $str;
2644 Hooks
::run( 'UserSetEmail', [ $this, &$this->mEmail
] );
2648 * Set the user's e-mail address and a confirmation mail if needed.
2651 * @param string $str New e-mail address
2654 public function setEmailWithConfirmation( $str ) {
2655 global $wgEnableEmail, $wgEmailAuthentication;
2657 if ( !$wgEnableEmail ) {
2658 return Status
::newFatal( 'emaildisabled' );
2661 $oldaddr = $this->getEmail();
2662 if ( $str === $oldaddr ) {
2663 return Status
::newGood( true );
2666 $this->setEmail( $str );
2668 if ( $str !== '' && $wgEmailAuthentication ) {
2669 // Send a confirmation request to the new address if needed
2670 $type = $oldaddr != '' ?
'changed' : 'set';
2671 $result = $this->sendConfirmationMail( $type );
2672 if ( $result->isGood() ) {
2673 // Say to the caller that a confirmation mail has been sent
2674 $result->value
= 'eauth';
2677 $result = Status
::newGood( true );
2684 * Get the user's real name
2685 * @return string User's real name
2687 public function getRealName() {
2688 if ( !$this->isItemLoaded( 'realname' ) ) {
2692 return $this->mRealName
;
2696 * Set the user's real name
2697 * @param string $str New real name
2699 public function setRealName( $str ) {
2701 $this->mRealName
= $str;
2705 * Get the user's current setting for a given option.
2707 * @param string $oname The option to check
2708 * @param string $defaultOverride A default value returned if the option does not exist
2709 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2710 * @return string User's current value for the option
2711 * @see getBoolOption()
2712 * @see getIntOption()
2714 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2715 global $wgHiddenPrefs;
2716 $this->loadOptions();
2718 # We want 'disabled' preferences to always behave as the default value for
2719 # users, even if they have set the option explicitly in their settings (ie they
2720 # set it, and then it was disabled removing their ability to change it). But
2721 # we don't want to erase the preferences in the database in case the preference
2722 # is re-enabled again. So don't touch $mOptions, just override the returned value
2723 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2724 return self
::getDefaultOption( $oname );
2727 if ( array_key_exists( $oname, $this->mOptions
) ) {
2728 return $this->mOptions
[$oname];
2730 return $defaultOverride;
2735 * Get all user's options
2737 * @param int $flags Bitwise combination of:
2738 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2739 * to the default value. (Since 1.25)
2742 public function getOptions( $flags = 0 ) {
2743 global $wgHiddenPrefs;
2744 $this->loadOptions();
2745 $options = $this->mOptions
;
2747 # We want 'disabled' preferences to always behave as the default value for
2748 # users, even if they have set the option explicitly in their settings (ie they
2749 # set it, and then it was disabled removing their ability to change it). But
2750 # we don't want to erase the preferences in the database in case the preference
2751 # is re-enabled again. So don't touch $mOptions, just override the returned value
2752 foreach ( $wgHiddenPrefs as $pref ) {
2753 $default = self
::getDefaultOption( $pref );
2754 if ( $default !== null ) {
2755 $options[$pref] = $default;
2759 if ( $flags & self
::GETOPTIONS_EXCLUDE_DEFAULTS
) {
2760 $options = array_diff_assoc( $options, self
::getDefaultOptions() );
2767 * Get the user's current setting for a given option, as a boolean value.
2769 * @param string $oname The option to check
2770 * @return bool User's current value for the option
2773 public function getBoolOption( $oname ) {
2774 return (bool)$this->getOption( $oname );
2778 * Get the user's current setting for a given option, as an integer value.
2780 * @param string $oname The option to check
2781 * @param int $defaultOverride A default value returned if the option does not exist
2782 * @return int User's current value for the option
2785 public function getIntOption( $oname, $defaultOverride = 0 ) {
2786 $val = $this->getOption( $oname );
2788 $val = $defaultOverride;
2790 return intval( $val );
2794 * Set the given option for a user.
2796 * You need to call saveSettings() to actually write to the database.
2798 * @param string $oname The option to set
2799 * @param mixed $val New value to set
2801 public function setOption( $oname, $val ) {
2802 $this->loadOptions();
2804 // Explicitly NULL values should refer to defaults
2805 if ( is_null( $val ) ) {
2806 $val = self
::getDefaultOption( $oname );
2809 $this->mOptions
[$oname] = $val;
2813 * Get a token stored in the preferences (like the watchlist one),
2814 * resetting it if it's empty (and saving changes).
2816 * @param string $oname The option name to retrieve the token from
2817 * @return string|bool User's current value for the option, or false if this option is disabled.
2818 * @see resetTokenFromOption()
2820 * @deprecated 1.26 Applications should use the OAuth extension
2822 public function getTokenFromOption( $oname ) {
2823 global $wgHiddenPrefs;
2825 $id = $this->getId();
2826 if ( !$id ||
in_array( $oname, $wgHiddenPrefs ) ) {
2830 $token = $this->getOption( $oname );
2832 // Default to a value based on the user token to avoid space
2833 // wasted on storing tokens for all users. When this option
2834 // is set manually by the user, only then is it stored.
2835 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
2842 * Reset a token stored in the preferences (like the watchlist one).
2843 * *Does not* save user's preferences (similarly to setOption()).
2845 * @param string $oname The option name to reset the token in
2846 * @return string|bool New token value, or false if this option is disabled.
2847 * @see getTokenFromOption()
2850 public function resetTokenFromOption( $oname ) {
2851 global $wgHiddenPrefs;
2852 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2856 $token = MWCryptRand
::generateHex( 40 );
2857 $this->setOption( $oname, $token );
2862 * Return a list of the types of user options currently returned by
2863 * User::getOptionKinds().
2865 * Currently, the option kinds are:
2866 * - 'registered' - preferences which are registered in core MediaWiki or
2867 * by extensions using the UserGetDefaultOptions hook.
2868 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2869 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2870 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2871 * be used by user scripts.
2872 * - 'special' - "preferences" that are not accessible via User::getOptions
2873 * or User::setOptions.
2874 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2875 * These are usually legacy options, removed in newer versions.
2877 * The API (and possibly others) use this function to determine the possible
2878 * option types for validation purposes, so make sure to update this when a
2879 * new option kind is added.
2881 * @see User::getOptionKinds
2882 * @return array Option kinds
2884 public static function listOptionKinds() {
2887 'registered-multiselect',
2888 'registered-checkmatrix',
2896 * Return an associative array mapping preferences keys to the kind of a preference they're
2897 * used for. Different kinds are handled differently when setting or reading preferences.
2899 * See User::listOptionKinds for the list of valid option types that can be provided.
2901 * @see User::listOptionKinds
2902 * @param IContextSource $context
2903 * @param array $options Assoc. array with options keys to check as keys.
2904 * Defaults to $this->mOptions.
2905 * @return array The key => kind mapping data
2907 public function getOptionKinds( IContextSource
$context, $options = null ) {
2908 $this->loadOptions();
2909 if ( $options === null ) {
2910 $options = $this->mOptions
;
2913 $prefs = Preferences
::getPreferences( $this, $context );
2916 // Pull out the "special" options, so they don't get converted as
2917 // multiselect or checkmatrix.
2918 $specialOptions = array_fill_keys( Preferences
::getSaveBlacklist(), true );
2919 foreach ( $specialOptions as $name => $value ) {
2920 unset( $prefs[$name] );
2923 // Multiselect and checkmatrix options are stored in the database with
2924 // one key per option, each having a boolean value. Extract those keys.
2925 $multiselectOptions = [];
2926 foreach ( $prefs as $name => $info ) {
2927 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2928 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2929 $opts = HTMLFormField
::flattenOptions( $info['options'] );
2930 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2932 foreach ( $opts as $value ) {
2933 $multiselectOptions["$prefix$value"] = true;
2936 unset( $prefs[$name] );
2939 $checkmatrixOptions = [];
2940 foreach ( $prefs as $name => $info ) {
2941 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2942 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2943 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
2944 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
2945 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2947 foreach ( $columns as $column ) {
2948 foreach ( $rows as $row ) {
2949 $checkmatrixOptions["$prefix$column-$row"] = true;
2953 unset( $prefs[$name] );
2957 // $value is ignored
2958 foreach ( $options as $key => $value ) {
2959 if ( isset( $prefs[$key] ) ) {
2960 $mapping[$key] = 'registered';
2961 } elseif ( isset( $multiselectOptions[$key] ) ) {
2962 $mapping[$key] = 'registered-multiselect';
2963 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2964 $mapping[$key] = 'registered-checkmatrix';
2965 } elseif ( isset( $specialOptions[$key] ) ) {
2966 $mapping[$key] = 'special';
2967 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2968 $mapping[$key] = 'userjs';
2970 $mapping[$key] = 'unused';
2978 * Reset certain (or all) options to the site defaults
2980 * The optional parameter determines which kinds of preferences will be reset.
2981 * Supported values are everything that can be reported by getOptionKinds()
2982 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2984 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
2985 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2986 * for backwards-compatibility.
2987 * @param IContextSource|null $context Context source used when $resetKinds
2988 * does not contain 'all', passed to getOptionKinds().
2989 * Defaults to RequestContext::getMain() when null.
2991 public function resetOptions(
2992 $resetKinds = [ 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ],
2993 IContextSource
$context = null
2996 $defaultOptions = self
::getDefaultOptions();
2998 if ( !is_array( $resetKinds ) ) {
2999 $resetKinds = [ $resetKinds ];
3002 if ( in_array( 'all', $resetKinds ) ) {
3003 $newOptions = $defaultOptions;
3005 if ( $context === null ) {
3006 $context = RequestContext
::getMain();
3009 $optionKinds = $this->getOptionKinds( $context );
3010 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
3013 // Use default values for the options that should be deleted, and
3014 // copy old values for the ones that shouldn't.
3015 foreach ( $this->mOptions
as $key => $value ) {
3016 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
3017 if ( array_key_exists( $key, $defaultOptions ) ) {
3018 $newOptions[$key] = $defaultOptions[$key];
3021 $newOptions[$key] = $value;
3026 Hooks
::run( 'UserResetAllOptions', [ $this, &$newOptions, $this->mOptions
, $resetKinds ] );
3028 $this->mOptions
= $newOptions;
3029 $this->mOptionsLoaded
= true;
3033 * Get the user's preferred date format.
3034 * @return string User's preferred date format
3036 public function getDatePreference() {
3037 // Important migration for old data rows
3038 if ( is_null( $this->mDatePreference
) ) {
3040 $value = $this->getOption( 'date' );
3041 $map = $wgLang->getDatePreferenceMigrationMap();
3042 if ( isset( $map[$value] ) ) {
3043 $value = $map[$value];
3045 $this->mDatePreference
= $value;
3047 return $this->mDatePreference
;
3051 * Determine based on the wiki configuration and the user's options,
3052 * whether this user must be over HTTPS no matter what.
3056 public function requiresHTTPS() {
3057 global $wgSecureLogin;
3058 if ( !$wgSecureLogin ) {
3061 $https = $this->getBoolOption( 'prefershttps' );
3062 Hooks
::run( 'UserRequiresHTTPS', [ $this, &$https ] );
3064 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
3071 * Get the user preferred stub threshold
3075 public function getStubThreshold() {
3076 global $wgMaxArticleSize; # Maximum article size, in Kb
3077 $threshold = $this->getIntOption( 'stubthreshold' );
3078 if ( $threshold > $wgMaxArticleSize * 1024 ) {
3079 // If they have set an impossible value, disable the preference
3080 // so we can use the parser cache again.
3087 * Get the permissions this user has.
3088 * @return array Array of String permission names
3090 public function getRights() {
3091 if ( is_null( $this->mRights
) ) {
3092 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
3094 // Deny any rights denied by the user's session, unless this
3095 // endpoint has no sessions.
3096 if ( !defined( 'MW_NO_SESSION' ) ) {
3097 $allowedRights = $this->getRequest()->getSession()->getAllowedUserRights();
3098 if ( $allowedRights !== null ) {
3099 $this->mRights
= array_intersect( $this->mRights
, $allowedRights );
3103 Hooks
::run( 'UserGetRights', [ $this, &$this->mRights
] );
3104 // Force reindexation of rights when a hook has unset one of them
3105 $this->mRights
= array_values( array_unique( $this->mRights
) );
3107 return $this->mRights
;
3111 * Get the list of explicit group memberships this user has.
3112 * The implicit * and user groups are not included.
3113 * @return array Array of String internal group names
3115 public function getGroups() {
3117 $this->loadGroups();
3118 return $this->mGroups
;
3122 * Get the list of implicit group memberships this user has.
3123 * This includes all explicit groups, plus 'user' if logged in,
3124 * '*' for all accounts, and autopromoted groups
3125 * @param bool $recache Whether to avoid the cache
3126 * @return array Array of String internal group names
3128 public function getEffectiveGroups( $recache = false ) {
3129 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
3130 $this->mEffectiveGroups
= array_unique( array_merge(
3131 $this->getGroups(), // explicit groups
3132 $this->getAutomaticGroups( $recache ) // implicit groups
3134 // Hook for additional groups
3135 Hooks
::run( 'UserEffectiveGroups', [ &$this, &$this->mEffectiveGroups
] );
3136 // Force reindexation of groups when a hook has unset one of them
3137 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
3139 return $this->mEffectiveGroups
;
3143 * Get the list of implicit group memberships this user has.
3144 * This includes 'user' if logged in, '*' for all accounts,
3145 * and autopromoted groups
3146 * @param bool $recache Whether to avoid the cache
3147 * @return array Array of String internal group names
3149 public function getAutomaticGroups( $recache = false ) {
3150 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
3151 $this->mImplicitGroups
= [ '*' ];
3152 if ( $this->getId() ) {
3153 $this->mImplicitGroups
[] = 'user';
3155 $this->mImplicitGroups
= array_unique( array_merge(
3156 $this->mImplicitGroups
,
3157 Autopromote
::getAutopromoteGroups( $this )
3161 // Assure data consistency with rights/groups,
3162 // as getEffectiveGroups() depends on this function
3163 $this->mEffectiveGroups
= null;
3166 return $this->mImplicitGroups
;
3170 * Returns the groups the user has belonged to.
3172 * The user may still belong to the returned groups. Compare with getGroups().
3174 * The function will not return groups the user had belonged to before MW 1.17
3176 * @return array Names of the groups the user has belonged to.
3178 public function getFormerGroups() {
3181 if ( is_null( $this->mFormerGroups
) ) {
3182 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3183 ?
wfGetDB( DB_MASTER
)
3184 : wfGetDB( DB_SLAVE
);
3185 $res = $db->select( 'user_former_groups',
3187 [ 'ufg_user' => $this->mId
],
3189 $this->mFormerGroups
= [];
3190 foreach ( $res as $row ) {
3191 $this->mFormerGroups
[] = $row->ufg_group
;
3195 return $this->mFormerGroups
;
3199 * Get the user's edit count.
3200 * @return int|null Null for anonymous users
3202 public function getEditCount() {
3203 if ( !$this->getId() ) {
3207 if ( $this->mEditCount
=== null ) {
3208 /* Populate the count, if it has not been populated yet */
3209 $dbr = wfGetDB( DB_SLAVE
);
3210 // check if the user_editcount field has been initialized
3211 $count = $dbr->selectField(
3212 'user', 'user_editcount',
3213 [ 'user_id' => $this->mId
],
3217 if ( $count === null ) {
3218 // it has not been initialized. do so.
3219 $count = $this->initEditCount();
3221 $this->mEditCount
= $count;
3223 return (int)$this->mEditCount
;
3227 * Add the user to the given group.
3228 * This takes immediate effect.
3229 * @param string $group Name of the group to add
3232 public function addGroup( $group ) {
3235 if ( !Hooks
::run( 'UserAddGroup', [ $this, &$group ] ) ) {
3239 $dbw = wfGetDB( DB_MASTER
);
3240 if ( $this->getId() ) {
3241 $dbw->insert( 'user_groups',
3243 'ug_user' => $this->getID(),
3244 'ug_group' => $group,
3250 $this->loadGroups();
3251 $this->mGroups
[] = $group;
3252 // In case loadGroups was not called before, we now have the right twice.
3253 // Get rid of the duplicate.
3254 $this->mGroups
= array_unique( $this->mGroups
);
3256 // Refresh the groups caches, and clear the rights cache so it will be
3257 // refreshed on the next call to $this->getRights().
3258 $this->getEffectiveGroups( true );
3259 $this->mRights
= null;
3261 $this->invalidateCache();
3267 * Remove the user from the given group.
3268 * This takes immediate effect.
3269 * @param string $group Name of the group to remove
3272 public function removeGroup( $group ) {
3274 if ( !Hooks
::run( 'UserRemoveGroup', [ $this, &$group ] ) ) {
3278 $dbw = wfGetDB( DB_MASTER
);
3279 $dbw->delete( 'user_groups',
3281 'ug_user' => $this->getID(),
3282 'ug_group' => $group,
3285 // Remember that the user was in this group
3286 $dbw->insert( 'user_former_groups',
3288 'ufg_user' => $this->getID(),
3289 'ufg_group' => $group,
3295 $this->loadGroups();
3296 $this->mGroups
= array_diff( $this->mGroups
, [ $group ] );
3298 // Refresh the groups caches, and clear the rights cache so it will be
3299 // refreshed on the next call to $this->getRights().
3300 $this->getEffectiveGroups( true );
3301 $this->mRights
= null;
3303 $this->invalidateCache();
3309 * Get whether the user is logged in
3312 public function isLoggedIn() {
3313 return $this->getID() != 0;
3317 * Get whether the user is anonymous
3320 public function isAnon() {
3321 return !$this->isLoggedIn();
3325 * Check if user is allowed to access a feature / make an action
3327 * @param string ... Permissions to test
3328 * @return bool True if user is allowed to perform *any* of the given actions
3330 public function isAllowedAny() {
3331 $permissions = func_get_args();
3332 foreach ( $permissions as $permission ) {
3333 if ( $this->isAllowed( $permission ) ) {
3342 * @param string ... Permissions to test
3343 * @return bool True if the user is allowed to perform *all* of the given actions
3345 public function isAllowedAll() {
3346 $permissions = func_get_args();
3347 foreach ( $permissions as $permission ) {
3348 if ( !$this->isAllowed( $permission ) ) {
3356 * Internal mechanics of testing a permission
3357 * @param string $action
3360 public function isAllowed( $action = '' ) {
3361 if ( $action === '' ) {
3362 return true; // In the spirit of DWIM
3364 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3365 // by misconfiguration: 0 == 'foo'
3366 return in_array( $action, $this->getRights(), true );
3370 * Check whether to enable recent changes patrol features for this user
3371 * @return bool True or false
3373 public function useRCPatrol() {
3374 global $wgUseRCPatrol;
3375 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3379 * Check whether to enable new pages patrol features for this user
3380 * @return bool True or false
3382 public function useNPPatrol() {
3383 global $wgUseRCPatrol, $wgUseNPPatrol;
3385 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3386 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3391 * Check whether to enable new files patrol features for this user
3392 * @return bool True or false
3394 public function useFilePatrol() {
3395 global $wgUseRCPatrol, $wgUseFilePatrol;
3397 ( $wgUseRCPatrol ||
$wgUseFilePatrol )
3398 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3403 * Get the WebRequest object to use with this object
3405 * @return WebRequest
3407 public function getRequest() {
3408 if ( $this->mRequest
) {
3409 return $this->mRequest
;
3417 * Get a WatchedItem for this user and $title.
3419 * @since 1.22 $checkRights parameter added
3420 * @param Title $title
3421 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3422 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3423 * @return WatchedItem
3425 public function getWatchedItem( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3426 $key = $checkRights . ':' . $title->getNamespace() . ':' . $title->getDBkey();
3428 if ( isset( $this->mWatchedItems
[$key] ) ) {
3429 return $this->mWatchedItems
[$key];
3432 if ( count( $this->mWatchedItems
) >= self
::MAX_WATCHED_ITEMS_CACHE
) {
3433 $this->mWatchedItems
= [];
3436 $this->mWatchedItems
[$key] = WatchedItem
::fromUserTitle( $this, $title, $checkRights );
3437 return $this->mWatchedItems
[$key];
3441 * Check the watched status of an article.
3442 * @since 1.22 $checkRights parameter added
3443 * @param Title $title Title of the article to look at
3444 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3445 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3448 public function isWatched( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3449 return $this->getWatchedItem( $title, $checkRights )->isWatched();
3454 * @since 1.22 $checkRights parameter added
3455 * @param Title $title Title of the article to look at
3456 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3457 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3459 public function addWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3460 $this->getWatchedItem( $title, $checkRights )->addWatch();
3461 $this->invalidateCache();
3465 * Stop watching an article.
3466 * @since 1.22 $checkRights parameter added
3467 * @param Title $title Title of the article to look at
3468 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3469 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3471 public function removeWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3472 $this->getWatchedItem( $title, $checkRights )->removeWatch();
3473 $this->invalidateCache();
3477 * Clear the user's notification timestamp for the given title.
3478 * If e-notif e-mails are on, they will receive notification mails on
3479 * the next change of the page if it's watched etc.
3480 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3481 * @param Title $title Title of the article to look at
3482 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3484 public function clearNotification( &$title, $oldid = 0 ) {
3485 global $wgUseEnotif, $wgShowUpdatedMarker;
3487 // Do nothing if the database is locked to writes
3488 if ( wfReadOnly() ) {
3492 // Do nothing if not allowed to edit the watchlist
3493 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3497 // If we're working on user's talk page, we should update the talk page message indicator
3498 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3499 if ( !Hooks
::run( 'UserClearNewTalkNotification', [ &$this, $oldid ] ) ) {
3503 // Try to update the DB post-send and only if needed...
3504 DeferredUpdates
::addCallableUpdate( function() use ( $title, $oldid ) {
3505 if ( !$this->getNewtalk() ) {
3506 return; // no notifications to clear
3509 // Delete the last notifications (they stack up)
3510 $this->setNewtalk( false );
3512 // If there is a new, unseen, revision, use its timestamp
3514 ?
$title->getNextRevisionID( $oldid, Title
::GAID_FOR_UPDATE
)
3517 $this->setNewtalk( true, Revision
::newFromId( $nextid ) );
3522 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3526 if ( $this->isAnon() ) {
3527 // Nothing else to do...
3531 // Only update the timestamp if the page is being watched.
3532 // The query to find out if it is watched is cached both in memcached and per-invocation,
3533 // and when it does have to be executed, it can be on a slave
3534 // If this is the user's newtalk page, we always update the timestamp
3536 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3540 $this->getWatchedItem( $title )->resetNotificationTimestamp(
3546 * Resets all of the given user's page-change notification timestamps.
3547 * If e-notif e-mails are on, they will receive notification mails on
3548 * the next change of any watched page.
3549 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3551 public function clearAllNotifications() {
3552 if ( wfReadOnly() ) {
3556 // Do nothing if not allowed to edit the watchlist
3557 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3561 global $wgUseEnotif, $wgShowUpdatedMarker;
3562 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3563 $this->setNewtalk( false );
3566 $id = $this->getId();
3568 $dbw = wfGetDB( DB_MASTER
);
3569 $dbw->update( 'watchlist',
3570 [ /* SET */ 'wl_notificationtimestamp' => null ],
3571 [ /* WHERE */ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ],
3574 // We also need to clear here the "you have new message" notification for the own user_talk page;
3575 // it's cleared one page view later in WikiPage::doViewUpdates().
3580 * Set a cookie on the user's client. Wrapper for
3581 * WebResponse::setCookie
3582 * @deprecated since 1.27
3583 * @param string $name Name of the cookie to set
3584 * @param string $value Value to set
3585 * @param int $exp Expiration time, as a UNIX time value;
3586 * if 0 or not specified, use the default $wgCookieExpiration
3587 * @param bool $secure
3588 * true: Force setting the secure attribute when setting the cookie
3589 * false: Force NOT setting the secure attribute when setting the cookie
3590 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3591 * @param array $params Array of options sent passed to WebResponse::setcookie()
3592 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3595 protected function setCookie(
3596 $name, $value, $exp = 0, $secure = null, $params = [], $request = null
3598 wfDeprecated( __METHOD__
, '1.27' );
3599 if ( $request === null ) {
3600 $request = $this->getRequest();
3602 $params['secure'] = $secure;
3603 $request->response()->setCookie( $name, $value, $exp, $params );
3607 * Clear a cookie on the user's client
3608 * @deprecated since 1.27
3609 * @param string $name Name of the cookie to clear
3610 * @param bool $secure
3611 * true: Force setting the secure attribute when setting the cookie
3612 * false: Force NOT setting the secure attribute when setting the cookie
3613 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3614 * @param array $params Array of options sent passed to WebResponse::setcookie()
3616 protected function clearCookie( $name, $secure = null, $params = [] ) {
3617 wfDeprecated( __METHOD__
, '1.27' );
3618 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3622 * Set an extended login cookie on the user's client. The expiry of the cookie
3623 * is controlled by the $wgExtendedLoginCookieExpiration configuration
3626 * @see User::setCookie
3628 * @deprecated since 1.27
3629 * @param string $name Name of the cookie to set
3630 * @param string $value Value to set
3631 * @param bool $secure
3632 * true: Force setting the secure attribute when setting the cookie
3633 * false: Force NOT setting the secure attribute when setting the cookie
3634 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3636 protected function setExtendedLoginCookie( $name, $value, $secure ) {
3637 global $wgExtendedLoginCookieExpiration, $wgCookieExpiration;
3639 wfDeprecated( __METHOD__
, '1.27' );
3642 $exp +
= $wgExtendedLoginCookieExpiration !== null
3643 ?
$wgExtendedLoginCookieExpiration
3644 : $wgCookieExpiration;
3646 $this->setCookie( $name, $value, $exp, $secure );
3650 * Persist this user's session (e.g. set cookies)
3652 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3654 * @param bool $secure Whether to force secure/insecure cookies or use default
3655 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3657 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3659 if ( 0 == $this->mId
) {
3663 $session = $this->getRequest()->getSession();
3664 if ( $request && $session->getRequest() !== $request ) {
3665 $session = $session->sessionWithRequest( $request );
3667 $delay = $session->delaySave();
3669 if ( !$session->getUser()->equals( $this ) ) {
3670 if ( !$session->canSetUser() ) {
3671 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3672 ->warning( __METHOD__
.
3673 ": Cannot save user \"$this\" to a user \"{$session->getUser()}\"'s immutable session"
3677 $session->setUser( $this );
3680 $session->setRememberUser( $rememberMe );
3681 if ( $secure !== null ) {
3682 $session->setForceHTTPS( $secure );
3685 $session->persist();
3687 ScopedCallback
::consume( $delay );
3691 * Log this user out.
3693 public function logout() {
3694 if ( Hooks
::run( 'UserLogout', [ &$this ] ) ) {
3700 * Clear the user's session, and reset the instance cache.
3703 public function doLogout() {
3704 $session = $this->getRequest()->getSession();
3705 if ( !$session->canSetUser() ) {
3706 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3707 ->warning( __METHOD__
. ": Cannot log out of an immutable session" );
3708 } elseif ( !$session->getUser()->equals( $this ) ) {
3709 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3710 ->warning( __METHOD__
.
3711 ": Cannot log user \"$this\" out of a user \"{$session->getUser()}\"'s session"
3713 // But we still may as well make this user object anon
3714 $this->clearInstanceCache( 'defaults' );
3716 $this->clearInstanceCache( 'defaults' );
3717 $delay = $session->delaySave();
3718 $session->setLoggedOutTimestamp( time() );
3719 $session->setUser( new User
);
3720 $session->set( 'wsUserID', 0 ); // Other code expects this
3721 ScopedCallback
::consume( $delay );
3726 * Save this user's settings into the database.
3727 * @todo Only rarely do all these fields need to be set!
3729 public function saveSettings() {
3730 if ( wfReadOnly() ) {
3731 // @TODO: caller should deal with this instead!
3732 // This should really just be an exception.
3733 MWExceptionHandler
::logException( new DBExpectedError(
3735 "Could not update user with ID '{$this->mId}'; DB is read-only."
3741 if ( 0 == $this->mId
) {
3745 // Get a new user_touched that is higher than the old one.
3746 // This will be used for a CAS check as a last-resort safety
3747 // check against race conditions and slave lag.
3748 $oldTouched = $this->mTouched
;
3749 $newTouched = $this->newTouchedTimestamp();
3751 $dbw = wfGetDB( DB_MASTER
);
3752 $dbw->update( 'user',
3754 'user_name' => $this->mName
,
3755 'user_real_name' => $this->mRealName
,
3756 'user_email' => $this->mEmail
,
3757 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3758 'user_touched' => $dbw->timestamp( $newTouched ),
3759 'user_token' => strval( $this->mToken
),
3760 'user_email_token' => $this->mEmailToken
,
3761 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
3763 'user_id' => $this->mId
,
3764 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
3768 if ( !$dbw->affectedRows() ) {
3769 // Maybe the problem was a missed cache update; clear it to be safe
3770 $this->clearSharedCache( 'refresh' );
3771 // User was changed in the meantime or loaded with stale data
3772 $from = ( $this->queryFlagsUsed
& self
::READ_LATEST
) ?
'master' : 'slave';
3773 throw new MWException(
3774 "CAS update failed on user_touched for user ID '{$this->mId}' (read from $from);" .
3775 " the version of the user to be saved is older than the current version."
3779 $this->mTouched
= $newTouched;
3780 $this->saveOptions();
3782 Hooks
::run( 'UserSaveSettings', [ $this ] );
3783 $this->clearSharedCache();
3784 $this->getUserPage()->invalidateCache();
3788 * If only this user's username is known, and it exists, return the user ID.
3790 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
3793 public function idForName( $flags = 0 ) {
3794 $s = trim( $this->getName() );
3799 $db = ( ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
)
3800 ?
wfGetDB( DB_MASTER
)
3801 : wfGetDB( DB_SLAVE
);
3803 $options = ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
)
3804 ?
[ 'LOCK IN SHARE MODE' ]
3807 $id = $db->selectField( 'user',
3808 'user_id', [ 'user_name' => $s ], __METHOD__
, $options );
3814 * Add a user to the database, return the user object
3816 * @param string $name Username to add
3817 * @param array $params Array of Strings Non-default parameters to save to
3818 * the database as user_* fields:
3819 * - email: The user's email address.
3820 * - email_authenticated: The email authentication timestamp.
3821 * - real_name: The user's real name.
3822 * - options: An associative array of non-default options.
3823 * - token: Random authentication token. Do not set.
3824 * - registration: Registration timestamp. Do not set.
3826 * @return User|null User object, or null if the username already exists.
3828 public static function createNew( $name, $params = [] ) {
3829 foreach ( [ 'password', 'newpassword', 'newpass_time', 'password_expires' ] as $field ) {
3830 if ( isset( $params[$field] ) ) {
3831 wfDeprecated( __METHOD__
. " with param '$field'", '1.27' );
3832 unset( $params[$field] );
3838 $user->setToken(); // init token
3839 if ( isset( $params['options'] ) ) {
3840 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
3841 unset( $params['options'] );
3843 $dbw = wfGetDB( DB_MASTER
);
3844 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3846 $noPass = PasswordFactory
::newInvalidPassword()->toString();
3849 'user_id' => $seqVal,
3850 'user_name' => $name,
3851 'user_password' => $noPass,
3852 'user_newpassword' => $noPass,
3853 'user_email' => $user->mEmail
,
3854 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
3855 'user_real_name' => $user->mRealName
,
3856 'user_token' => strval( $user->mToken
),
3857 'user_registration' => $dbw->timestamp( $user->mRegistration
),
3858 'user_editcount' => 0,
3859 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
3861 foreach ( $params as $name => $value ) {
3862 $fields["user_$name"] = $value;
3864 $dbw->insert( 'user', $fields, __METHOD__
, [ 'IGNORE' ] );
3865 if ( $dbw->affectedRows() ) {
3866 $newUser = User
::newFromId( $dbw->insertId() );
3874 * Add this existing user object to the database. If the user already
3875 * exists, a fatal status object is returned, and the user object is
3876 * initialised with the data from the database.
3878 * Previously, this function generated a DB error due to a key conflict
3879 * if the user already existed. Many extension callers use this function
3880 * in code along the lines of:
3882 * $user = User::newFromName( $name );
3883 * if ( !$user->isLoggedIn() ) {
3884 * $user->addToDatabase();
3886 * // do something with $user...
3888 * However, this was vulnerable to a race condition (bug 16020). By
3889 * initialising the user object if the user exists, we aim to support this
3890 * calling sequence as far as possible.
3892 * Note that if the user exists, this function will acquire a write lock,
3893 * so it is still advisable to make the call conditional on isLoggedIn(),
3894 * and to commit the transaction after calling.
3896 * @throws MWException
3899 public function addToDatabase() {
3901 if ( !$this->mToken
) {
3902 $this->setToken(); // init token
3905 $this->mTouched
= $this->newTouchedTimestamp();
3907 $noPass = PasswordFactory
::newInvalidPassword()->toString();
3909 $dbw = wfGetDB( DB_MASTER
);
3910 $inWrite = $dbw->writesOrCallbacksPending();
3911 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3912 $dbw->insert( 'user',
3914 'user_id' => $seqVal,
3915 'user_name' => $this->mName
,
3916 'user_password' => $noPass,
3917 'user_newpassword' => $noPass,
3918 'user_email' => $this->mEmail
,
3919 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3920 'user_real_name' => $this->mRealName
,
3921 'user_token' => strval( $this->mToken
),
3922 'user_registration' => $dbw->timestamp( $this->mRegistration
),
3923 'user_editcount' => 0,
3924 'user_touched' => $dbw->timestamp( $this->mTouched
),
3928 if ( !$dbw->affectedRows() ) {
3929 // The queries below cannot happen in the same REPEATABLE-READ snapshot.
3930 // Handle this by COMMIT, if possible, or by LOCK IN SHARE MODE otherwise.
3932 // Can't commit due to pending writes that may need atomicity.
3933 // This may cause some lock contention unlike the case below.
3934 $options = [ 'LOCK IN SHARE MODE' ];
3935 $flags = self
::READ_LOCKING
;
3937 // Often, this case happens early in views before any writes when
3938 // using CentralAuth. It's should be OK to commit and break the snapshot.
3939 $dbw->commit( __METHOD__
, 'flush' );
3941 $flags = self
::READ_LATEST
;
3943 $this->mId
= $dbw->selectField( 'user', 'user_id',
3944 [ 'user_name' => $this->mName
], __METHOD__
, $options );
3947 if ( $this->loadFromDatabase( $flags ) ) {
3952 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
3953 "to insert user '{$this->mName}' row, but it was not present in select!" );
3955 return Status
::newFatal( 'userexists' );
3957 $this->mId
= $dbw->insertId();
3958 self
::$idCacheByName[$this->mName
] = $this->mId
;
3960 // Clear instance cache other than user table data, which is already accurate
3961 $this->clearInstanceCache();
3963 $this->saveOptions();
3964 return Status
::newGood();
3968 * If this user is logged-in and blocked,
3969 * block any IP address they've successfully logged in from.
3970 * @return bool A block was spread
3972 public function spreadAnyEditBlock() {
3973 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3974 return $this->spreadBlock();
3980 * If this (non-anonymous) user is blocked,
3981 * block the IP address they've successfully logged in from.
3982 * @return bool A block was spread
3984 protected function spreadBlock() {
3985 wfDebug( __METHOD__
. "()\n" );
3987 if ( $this->mId
== 0 ) {
3991 $userblock = Block
::newFromTarget( $this->getName() );
3992 if ( !$userblock ) {
3996 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
4000 * Get whether the user is explicitly blocked from account creation.
4001 * @return bool|Block
4003 public function isBlockedFromCreateAccount() {
4004 $this->getBlockedStatus();
4005 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
4006 return $this->mBlock
;
4009 # bug 13611: if the IP address the user is trying to create an account from is
4010 # blocked with createaccount disabled, prevent new account creation there even
4011 # when the user is logged in
4012 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
4013 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
4015 return $this->mBlockedFromCreateAccount
instanceof Block
4016 && $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
4017 ?
$this->mBlockedFromCreateAccount
4022 * Get whether the user is blocked from using Special:Emailuser.
4025 public function isBlockedFromEmailuser() {
4026 $this->getBlockedStatus();
4027 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
4031 * Get whether the user is allowed to create an account.
4034 public function isAllowedToCreateAccount() {
4035 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
4039 * Get this user's personal page title.
4041 * @return Title User's personal page title
4043 public function getUserPage() {
4044 return Title
::makeTitle( NS_USER
, $this->getName() );
4048 * Get this user's talk page title.
4050 * @return Title User's talk page title
4052 public function getTalkPage() {
4053 $title = $this->getUserPage();
4054 return $title->getTalkPage();
4058 * Determine whether the user is a newbie. Newbies are either
4059 * anonymous IPs, or the most recently created accounts.
4062 public function isNewbie() {
4063 return !$this->isAllowed( 'autoconfirmed' );
4067 * Check to see if the given clear-text password is one of the accepted passwords
4068 * @deprecated since 1.27. AuthManager is coming.
4069 * @param string $password User password
4070 * @return bool True if the given password is correct, otherwise False
4072 public function checkPassword( $password ) {
4073 global $wgAuth, $wgLegacyEncoding;
4077 // Some passwords will give a fatal Status, which means there is
4078 // some sort of technical or security reason for this password to
4079 // be completely invalid and should never be checked (e.g., T64685)
4080 if ( !$this->checkPasswordValidity( $password )->isOK() ) {
4084 // Certain authentication plugins do NOT want to save
4085 // domain passwords in a mysql database, so we should
4086 // check this (in case $wgAuth->strict() is false).
4087 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
4089 } elseif ( $wgAuth->strict() ) {
4090 // Auth plugin doesn't allow local authentication
4092 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
4093 // Auth plugin doesn't allow local authentication for this user name
4097 $passwordFactory = new PasswordFactory();
4098 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4099 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
4100 ?
wfGetDB( DB_MASTER
)
4101 : wfGetDB( DB_SLAVE
);
4104 $mPassword = $passwordFactory->newFromCiphertext( $db->selectField(
4105 'user', 'user_password', [ 'user_id' => $this->getId() ], __METHOD__
4107 } catch ( PasswordError
$e ) {
4108 wfDebug( 'Invalid password hash found in database.' );
4109 $mPassword = PasswordFactory
::newInvalidPassword();
4112 if ( !$mPassword->equals( $password ) ) {
4113 if ( $wgLegacyEncoding ) {
4114 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
4115 // Check for this with iconv
4116 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
4117 if ( $cp1252Password === $password ||
!$mPassword->equals( $cp1252Password ) ) {
4125 if ( $passwordFactory->needsUpdate( $mPassword ) && !wfReadOnly() ) {
4126 $this->setPasswordInternal( $password );
4133 * Check if the given clear-text password matches the temporary password
4134 * sent by e-mail for password reset operations.
4136 * @deprecated since 1.27. AuthManager is coming.
4137 * @param string $plaintext
4138 * @return bool True if matches, false otherwise
4140 public function checkTemporaryPassword( $plaintext ) {
4141 global $wgNewPasswordExpiry;
4145 $passwordFactory = new PasswordFactory();
4146 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4147 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
4148 ?
wfGetDB( DB_MASTER
)
4149 : wfGetDB( DB_SLAVE
);
4151 $row = $db->selectRow(
4153 [ 'user_newpassword', 'user_newpass_time' ],
4154 [ 'user_id' => $this->getId() ],
4158 $newPassword = $passwordFactory->newFromCiphertext( $row->user_newpassword
);
4159 } catch ( PasswordError
$e ) {
4160 wfDebug( 'Invalid password hash found in database.' );
4161 $newPassword = PasswordFactory
::newInvalidPassword();
4164 if ( $newPassword->equals( $plaintext ) ) {
4165 if ( is_null( $row->user_newpass_time
) ) {
4168 $expiry = wfTimestamp( TS_UNIX
, $row->user_newpass_time
) +
$wgNewPasswordExpiry;
4169 return ( time() < $expiry );
4176 * Initialize (if necessary) and return a session token value
4177 * which can be used in edit forms to show that the user's
4178 * login credentials aren't being hijacked with a foreign form
4182 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4183 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4184 * @return MediaWiki\\Session\\Token The new edit token
4186 public function getEditTokenObject( $salt = '', $request = null ) {
4187 if ( $this->isAnon() ) {
4188 return new LoggedOutEditToken();
4192 $request = $this->getRequest();
4194 return $request->getSession()->getToken( $salt );
4198 * Initialize (if necessary) and return a session token value
4199 * which can be used in edit forms to show that the user's
4200 * login credentials aren't being hijacked with a foreign form
4204 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4205 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4206 * @return string The new edit token
4208 public function getEditToken( $salt = '', $request = null ) {
4209 return $this->getEditTokenObject( $salt, $request )->toString();
4213 * Get the embedded timestamp from a token.
4214 * @deprecated since 1.27, use \\MediaWiki\\Session\\Token::getTimestamp instead.
4215 * @param string $val Input token
4218 public static function getEditTokenTimestamp( $val ) {
4219 wfDeprecated( __METHOD__
, '1.27' );
4220 return MediaWiki\Session\Token
::getTimestamp( $val );
4224 * Check given value against the token value stored in the session.
4225 * A match should confirm that the form was submitted from the
4226 * user's own login session, not a form submission from a third-party
4229 * @param string $val Input value to compare
4230 * @param string $salt Optional function-specific data for hashing
4231 * @param WebRequest|null $request Object to use or null to use $wgRequest
4232 * @param int $maxage Fail tokens older than this, in seconds
4233 * @return bool Whether the token matches
4235 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4236 return $this->getEditTokenObject( $salt, $request )->match( $val, $maxage );
4240 * Check given value against the token value stored in the session,
4241 * ignoring the suffix.
4243 * @param string $val Input value to compare
4244 * @param string $salt Optional function-specific data for hashing
4245 * @param WebRequest|null $request Object to use or null to use $wgRequest
4246 * @param int $maxage Fail tokens older than this, in seconds
4247 * @return bool Whether the token matches
4249 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4250 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . self
::EDIT_TOKEN_SUFFIX
;
4251 return $this->matchEditToken( $val, $salt, $request, $maxage );
4255 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4256 * mail to the user's given address.
4258 * @param string $type Message to send, either "created", "changed" or "set"
4261 public function sendConfirmationMail( $type = 'created' ) {
4263 $expiration = null; // gets passed-by-ref and defined in next line.
4264 $token = $this->confirmationToken( $expiration );
4265 $url = $this->confirmationTokenUrl( $token );
4266 $invalidateURL = $this->invalidationTokenUrl( $token );
4267 $this->saveSettings();
4269 if ( $type == 'created' ||
$type === false ) {
4270 $message = 'confirmemail_body';
4271 } elseif ( $type === true ) {
4272 $message = 'confirmemail_body_changed';
4274 // Messages: confirmemail_body_changed, confirmemail_body_set
4275 $message = 'confirmemail_body_' . $type;
4278 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4279 wfMessage( $message,
4280 $this->getRequest()->getIP(),
4283 $wgLang->userTimeAndDate( $expiration, $this ),
4285 $wgLang->userDate( $expiration, $this ),
4286 $wgLang->userTime( $expiration, $this ) )->text() );
4290 * Send an e-mail to this user's account. Does not check for
4291 * confirmed status or validity.
4293 * @param string $subject Message subject
4294 * @param string $body Message body
4295 * @param User|null $from Optional sending user; if unspecified, default
4296 * $wgPasswordSender will be used.
4297 * @param string $replyto Reply-To address
4300 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4301 global $wgPasswordSender;
4303 if ( $from instanceof User
) {
4304 $sender = MailAddress
::newFromUser( $from );
4306 $sender = new MailAddress( $wgPasswordSender,
4307 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4309 $to = MailAddress
::newFromUser( $this );
4311 return UserMailer
::send( $to, $sender, $subject, $body, [
4312 'replyTo' => $replyto,
4317 * Generate, store, and return a new e-mail confirmation code.
4318 * A hash (unsalted, since it's used as a key) is stored.
4320 * @note Call saveSettings() after calling this function to commit
4321 * this change to the database.
4323 * @param string &$expiration Accepts the expiration time
4324 * @return string New token
4326 protected function confirmationToken( &$expiration ) {
4327 global $wgUserEmailConfirmationTokenExpiry;
4329 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4330 $expiration = wfTimestamp( TS_MW
, $expires );
4332 $token = MWCryptRand
::generateHex( 32 );
4333 $hash = md5( $token );
4334 $this->mEmailToken
= $hash;
4335 $this->mEmailTokenExpires
= $expiration;
4340 * Return a URL the user can use to confirm their email address.
4341 * @param string $token Accepts the email confirmation token
4342 * @return string New token URL
4344 protected function confirmationTokenUrl( $token ) {
4345 return $this->getTokenUrl( 'ConfirmEmail', $token );
4349 * Return a URL the user can use to invalidate their email address.
4350 * @param string $token Accepts the email confirmation token
4351 * @return string New token URL
4353 protected function invalidationTokenUrl( $token ) {
4354 return $this->getTokenUrl( 'InvalidateEmail', $token );
4358 * Internal function to format the e-mail validation/invalidation URLs.
4359 * This uses a quickie hack to use the
4360 * hardcoded English names of the Special: pages, for ASCII safety.
4362 * @note Since these URLs get dropped directly into emails, using the
4363 * short English names avoids insanely long URL-encoded links, which
4364 * also sometimes can get corrupted in some browsers/mailers
4365 * (bug 6957 with Gmail and Internet Explorer).
4367 * @param string $page Special page
4368 * @param string $token Token
4369 * @return string Formatted URL
4371 protected function getTokenUrl( $page, $token ) {
4372 // Hack to bypass localization of 'Special:'
4373 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4374 return $title->getCanonicalURL();
4378 * Mark the e-mail address confirmed.
4380 * @note Call saveSettings() after calling this function to commit the change.
4384 public function confirmEmail() {
4385 // Check if it's already confirmed, so we don't touch the database
4386 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4387 if ( !$this->isEmailConfirmed() ) {
4388 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4389 Hooks
::run( 'ConfirmEmailComplete', [ $this ] );
4395 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4396 * address if it was already confirmed.
4398 * @note Call saveSettings() after calling this function to commit the change.
4399 * @return bool Returns true
4401 public function invalidateEmail() {
4403 $this->mEmailToken
= null;
4404 $this->mEmailTokenExpires
= null;
4405 $this->setEmailAuthenticationTimestamp( null );
4407 Hooks
::run( 'InvalidateEmailComplete', [ $this ] );
4412 * Set the e-mail authentication timestamp.
4413 * @param string $timestamp TS_MW timestamp
4415 public function setEmailAuthenticationTimestamp( $timestamp ) {
4417 $this->mEmailAuthenticated
= $timestamp;
4418 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
4422 * Is this user allowed to send e-mails within limits of current
4423 * site configuration?
4426 public function canSendEmail() {
4427 global $wgEnableEmail, $wgEnableUserEmail;
4428 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4431 $canSend = $this->isEmailConfirmed();
4432 Hooks
::run( 'UserCanSendEmail', [ &$this, &$canSend ] );
4437 * Is this user allowed to receive e-mails within limits of current
4438 * site configuration?
4441 public function canReceiveEmail() {
4442 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4446 * Is this user's e-mail address valid-looking and confirmed within
4447 * limits of the current site configuration?
4449 * @note If $wgEmailAuthentication is on, this may require the user to have
4450 * confirmed their address by returning a code or using a password
4451 * sent to the address from the wiki.
4455 public function isEmailConfirmed() {
4456 global $wgEmailAuthentication;
4459 if ( Hooks
::run( 'EmailConfirmed', [ &$this, &$confirmed ] ) ) {
4460 if ( $this->isAnon() ) {
4463 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4466 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4476 * Check whether there is an outstanding request for e-mail confirmation.
4479 public function isEmailConfirmationPending() {
4480 global $wgEmailAuthentication;
4481 return $wgEmailAuthentication &&
4482 !$this->isEmailConfirmed() &&
4483 $this->mEmailToken
&&
4484 $this->mEmailTokenExpires
> wfTimestamp();
4488 * Get the timestamp of account creation.
4490 * @return string|bool|null Timestamp of account creation, false for
4491 * non-existent/anonymous user accounts, or null if existing account
4492 * but information is not in database.
4494 public function getRegistration() {
4495 if ( $this->isAnon() ) {
4499 return $this->mRegistration
;
4503 * Get the timestamp of the first edit
4505 * @return string|bool Timestamp of first edit, or false for
4506 * non-existent/anonymous user accounts.
4508 public function getFirstEditTimestamp() {
4509 if ( $this->getId() == 0 ) {
4510 return false; // anons
4512 $dbr = wfGetDB( DB_SLAVE
);
4513 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4514 [ 'rev_user' => $this->getId() ],
4516 [ 'ORDER BY' => 'rev_timestamp ASC' ]
4519 return false; // no edits
4521 return wfTimestamp( TS_MW
, $time );
4525 * Get the permissions associated with a given list of groups
4527 * @param array $groups Array of Strings List of internal group names
4528 * @return array Array of Strings List of permission key names for given groups combined
4530 public static function getGroupPermissions( $groups ) {
4531 global $wgGroupPermissions, $wgRevokePermissions;
4533 // grant every granted permission first
4534 foreach ( $groups as $group ) {
4535 if ( isset( $wgGroupPermissions[$group] ) ) {
4536 $rights = array_merge( $rights,
4537 // array_filter removes empty items
4538 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4541 // now revoke the revoked permissions
4542 foreach ( $groups as $group ) {
4543 if ( isset( $wgRevokePermissions[$group] ) ) {
4544 $rights = array_diff( $rights,
4545 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4548 return array_unique( $rights );
4552 * Get all the groups who have a given permission
4554 * @param string $role Role to check
4555 * @return array Array of Strings List of internal group names with the given permission
4557 public static function getGroupsWithPermission( $role ) {
4558 global $wgGroupPermissions;
4559 $allowedGroups = [];
4560 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4561 if ( self
::groupHasPermission( $group, $role ) ) {
4562 $allowedGroups[] = $group;
4565 return $allowedGroups;
4569 * Check, if the given group has the given permission
4571 * If you're wanting to check whether all users have a permission, use
4572 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4576 * @param string $group Group to check
4577 * @param string $role Role to check
4580 public static function groupHasPermission( $group, $role ) {
4581 global $wgGroupPermissions, $wgRevokePermissions;
4582 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4583 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4587 * Check if all users may be assumed to have the given permission
4589 * We generally assume so if the right is granted to '*' and isn't revoked
4590 * on any group. It doesn't attempt to take grants or other extension
4591 * limitations on rights into account in the general case, though, as that
4592 * would require it to always return false and defeat the purpose.
4593 * Specifically, session-based rights restrictions (such as OAuth or bot
4594 * passwords) are applied based on the current session.
4597 * @param string $right Right to check
4600 public static function isEveryoneAllowed( $right ) {
4601 global $wgGroupPermissions, $wgRevokePermissions;
4604 // Use the cached results, except in unit tests which rely on
4605 // being able change the permission mid-request
4606 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4607 return $cache[$right];
4610 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4611 $cache[$right] = false;
4615 // If it's revoked anywhere, then everyone doesn't have it
4616 foreach ( $wgRevokePermissions as $rights ) {
4617 if ( isset( $rights[$right] ) && $rights[$right] ) {
4618 $cache[$right] = false;
4623 // Remove any rights that aren't allowed to the global-session user,
4624 // unless there are no sessions for this endpoint.
4625 if ( !defined( 'MW_NO_SESSION' ) ) {
4626 $allowedRights = SessionManager
::getGlobalSession()->getAllowedUserRights();
4627 if ( $allowedRights !== null && !in_array( $right, $allowedRights, true ) ) {
4628 $cache[$right] = false;
4633 // Allow extensions to say false
4634 if ( !Hooks
::run( 'UserIsEveryoneAllowed', [ $right ] ) ) {
4635 $cache[$right] = false;
4639 $cache[$right] = true;
4644 * Get the localized descriptive name for a group, if it exists
4646 * @param string $group Internal group name
4647 * @return string Localized descriptive group name
4649 public static function getGroupName( $group ) {
4650 $msg = wfMessage( "group-$group" );
4651 return $msg->isBlank() ?
$group : $msg->text();
4655 * Get the localized descriptive name for a member of a group, if it exists
4657 * @param string $group Internal group name
4658 * @param string $username Username for gender (since 1.19)
4659 * @return string Localized name for group member
4661 public static function getGroupMember( $group, $username = '#' ) {
4662 $msg = wfMessage( "group-$group-member", $username );
4663 return $msg->isBlank() ?
$group : $msg->text();
4667 * Return the set of defined explicit groups.
4668 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4669 * are not included, as they are defined automatically, not in the database.
4670 * @return array Array of internal group names
4672 public static function getAllGroups() {
4673 global $wgGroupPermissions, $wgRevokePermissions;
4675 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4676 self
::getImplicitGroups()
4681 * Get a list of all available permissions.
4682 * @return string[] Array of permission names
4684 public static function getAllRights() {
4685 if ( self
::$mAllRights === false ) {
4686 global $wgAvailableRights;
4687 if ( count( $wgAvailableRights ) ) {
4688 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
4690 self
::$mAllRights = self
::$mCoreRights;
4692 Hooks
::run( 'UserGetAllRights', [ &self
::$mAllRights ] );
4694 return self
::$mAllRights;
4698 * Get a list of implicit groups
4699 * @return array Array of Strings Array of internal group names
4701 public static function getImplicitGroups() {
4702 global $wgImplicitGroups;
4704 $groups = $wgImplicitGroups;
4705 # Deprecated, use $wgImplicitGroups instead
4706 Hooks
::run( 'UserGetImplicitGroups', [ &$groups ], '1.25' );
4712 * Get the title of a page describing a particular group
4714 * @param string $group Internal group name
4715 * @return Title|bool Title of the page if it exists, false otherwise
4717 public static function getGroupPage( $group ) {
4718 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4719 if ( $msg->exists() ) {
4720 $title = Title
::newFromText( $msg->text() );
4721 if ( is_object( $title ) ) {
4729 * Create a link to the group in HTML, if available;
4730 * else return the group name.
4732 * @param string $group Internal name of the group
4733 * @param string $text The text of the link
4734 * @return string HTML link to the group
4736 public static function makeGroupLinkHTML( $group, $text = '' ) {
4737 if ( $text == '' ) {
4738 $text = self
::getGroupName( $group );
4740 $title = self
::getGroupPage( $group );
4742 return Linker
::link( $title, htmlspecialchars( $text ) );
4744 return htmlspecialchars( $text );
4749 * Create a link to the group in Wikitext, if available;
4750 * else return the group name.
4752 * @param string $group Internal name of the group
4753 * @param string $text The text of the link
4754 * @return string Wikilink to the group
4756 public static function makeGroupLinkWiki( $group, $text = '' ) {
4757 if ( $text == '' ) {
4758 $text = self
::getGroupName( $group );
4760 $title = self
::getGroupPage( $group );
4762 $page = $title->getFullText();
4763 return "[[$page|$text]]";
4770 * Returns an array of the groups that a particular group can add/remove.
4772 * @param string $group The group to check for whether it can add/remove
4773 * @return array Array( 'add' => array( addablegroups ),
4774 * 'remove' => array( removablegroups ),
4775 * 'add-self' => array( addablegroups to self),
4776 * 'remove-self' => array( removable groups from self) )
4778 public static function changeableByGroup( $group ) {
4779 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4788 if ( empty( $wgAddGroups[$group] ) ) {
4789 // Don't add anything to $groups
4790 } elseif ( $wgAddGroups[$group] === true ) {
4791 // You get everything
4792 $groups['add'] = self
::getAllGroups();
4793 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4794 $groups['add'] = $wgAddGroups[$group];
4797 // Same thing for remove
4798 if ( empty( $wgRemoveGroups[$group] ) ) {
4800 } elseif ( $wgRemoveGroups[$group] === true ) {
4801 $groups['remove'] = self
::getAllGroups();
4802 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4803 $groups['remove'] = $wgRemoveGroups[$group];
4806 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4807 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4808 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4809 if ( is_int( $key ) ) {
4810 $wgGroupsAddToSelf['user'][] = $value;
4815 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
4816 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4817 if ( is_int( $key ) ) {
4818 $wgGroupsRemoveFromSelf['user'][] = $value;
4823 // Now figure out what groups the user can add to him/herself
4824 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4826 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4827 // No idea WHY this would be used, but it's there
4828 $groups['add-self'] = User
::getAllGroups();
4829 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4830 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4833 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4835 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4836 $groups['remove-self'] = User
::getAllGroups();
4837 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4838 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4845 * Returns an array of groups that this user can add and remove
4846 * @return array Array( 'add' => array( addablegroups ),
4847 * 'remove' => array( removablegroups ),
4848 * 'add-self' => array( addablegroups to self),
4849 * 'remove-self' => array( removable groups from self) )
4851 public function changeableGroups() {
4852 if ( $this->isAllowed( 'userrights' ) ) {
4853 // This group gives the right to modify everything (reverse-
4854 // compatibility with old "userrights lets you change
4856 // Using array_merge to make the groups reindexed
4857 $all = array_merge( User
::getAllGroups() );
4866 // Okay, it's not so simple, we will have to go through the arrays
4873 $addergroups = $this->getEffectiveGroups();
4875 foreach ( $addergroups as $addergroup ) {
4876 $groups = array_merge_recursive(
4877 $groups, $this->changeableByGroup( $addergroup )
4879 $groups['add'] = array_unique( $groups['add'] );
4880 $groups['remove'] = array_unique( $groups['remove'] );
4881 $groups['add-self'] = array_unique( $groups['add-self'] );
4882 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4888 * Deferred version of incEditCountImmediate()
4890 public function incEditCount() {
4891 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle( function() {
4892 $this->incEditCountImmediate();
4897 * Increment the user's edit-count field.
4898 * Will have no effect for anonymous users.
4901 public function incEditCountImmediate() {
4902 if ( $this->isAnon() ) {
4906 $dbw = wfGetDB( DB_MASTER
);
4907 // No rows will be "affected" if user_editcount is NULL
4910 [ 'user_editcount=user_editcount+1' ],
4911 [ 'user_id' => $this->getId(), 'user_editcount IS NOT NULL' ],
4914 // Lazy initialization check...
4915 if ( $dbw->affectedRows() == 0 ) {
4916 // Now here's a goddamn hack...
4917 $dbr = wfGetDB( DB_SLAVE
);
4918 if ( $dbr !== $dbw ) {
4919 // If we actually have a slave server, the count is
4920 // at least one behind because the current transaction
4921 // has not been committed and replicated.
4922 $this->initEditCount( 1 );
4924 // But if DB_SLAVE is selecting the master, then the
4925 // count we just read includes the revision that was
4926 // just added in the working transaction.
4927 $this->initEditCount();
4930 // Edit count in user cache too
4931 $this->invalidateCache();
4935 * Initialize user_editcount from data out of the revision table
4937 * @param int $add Edits to add to the count from the revision table
4938 * @return int Number of edits
4940 protected function initEditCount( $add = 0 ) {
4941 // Pull from a slave to be less cruel to servers
4942 // Accuracy isn't the point anyway here
4943 $dbr = wfGetDB( DB_SLAVE
);
4944 $count = (int)$dbr->selectField(
4947 [ 'rev_user' => $this->getId() ],
4950 $count = $count +
$add;
4952 $dbw = wfGetDB( DB_MASTER
);
4955 [ 'user_editcount' => $count ],
4956 [ 'user_id' => $this->getId() ],
4964 * Get the description of a given right
4966 * @param string $right Right to query
4967 * @return string Localized description of the right
4969 public static function getRightDescription( $right ) {
4970 $key = "right-$right";
4971 $msg = wfMessage( $key );
4972 return $msg->isBlank() ?
$right : $msg->text();
4976 * Make a new-style password hash
4978 * @param string $password Plain-text password
4979 * @param bool|string $salt Optional salt, may be random or the user ID.
4980 * If unspecified or false, will generate one automatically
4981 * @return string Password hash
4982 * @deprecated since 1.24, use Password class
4984 public static function crypt( $password, $salt = false ) {
4985 wfDeprecated( __METHOD__
, '1.24' );
4986 $passwordFactory = new PasswordFactory();
4987 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4988 $hash = $passwordFactory->newFromPlaintext( $password );
4989 return $hash->toString();
4993 * Compare a password hash with a plain-text password. Requires the user
4994 * ID if there's a chance that the hash is an old-style hash.
4996 * @param string $hash Password hash
4997 * @param string $password Plain-text password to compare
4998 * @param string|bool $userId User ID for old-style password salt
5001 * @deprecated since 1.24, use Password class
5003 public static function comparePasswords( $hash, $password, $userId = false ) {
5004 wfDeprecated( __METHOD__
, '1.24' );
5006 // Check for *really* old password hashes that don't even have a type
5007 // The old hash format was just an md5 hex hash, with no type information
5008 if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) {
5009 global $wgPasswordSalt;
5010 if ( $wgPasswordSalt ) {
5011 $password = ":B:{$userId}:{$hash}";
5013 $password = ":A:{$hash}";
5017 $passwordFactory = new PasswordFactory();
5018 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
5019 $hash = $passwordFactory->newFromCiphertext( $hash );
5020 return $hash->equals( $password );
5024 * Add a newuser log entry for this user.
5025 * Before 1.19 the return value was always true.
5027 * @param string|bool $action Account creation type.
5028 * - String, one of the following values:
5029 * - 'create' for an anonymous user creating an account for himself.
5030 * This will force the action's performer to be the created user itself,
5031 * no matter the value of $wgUser
5032 * - 'create2' for a logged in user creating an account for someone else
5033 * - 'byemail' when the created user will receive its password by e-mail
5034 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
5035 * - Boolean means whether the account was created by e-mail (deprecated):
5036 * - true will be converted to 'byemail'
5037 * - false will be converted to 'create' if this object is the same as
5038 * $wgUser and to 'create2' otherwise
5040 * @param string $reason User supplied reason
5042 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
5044 public function addNewUserLogEntry( $action = false, $reason = '' ) {
5045 global $wgUser, $wgNewUserLog;
5046 if ( empty( $wgNewUserLog ) ) {
5047 return true; // disabled
5050 if ( $action === true ) {
5051 $action = 'byemail';
5052 } elseif ( $action === false ) {
5053 if ( $this->equals( $wgUser ) ) {
5056 $action = 'create2';
5060 if ( $action === 'create' ||
$action === 'autocreate' ) {
5063 $performer = $wgUser;
5066 $logEntry = new ManualLogEntry( 'newusers', $action );
5067 $logEntry->setPerformer( $performer );
5068 $logEntry->setTarget( $this->getUserPage() );
5069 $logEntry->setComment( $reason );
5070 $logEntry->setParameters( [
5071 '4::userid' => $this->getId(),
5073 $logid = $logEntry->insert();
5075 if ( $action !== 'autocreate' ) {
5076 $logEntry->publish( $logid );
5083 * Add an autocreate newuser log entry for this user
5084 * Used by things like CentralAuth and perhaps other authplugins.
5085 * Consider calling addNewUserLogEntry() directly instead.
5089 public function addNewUserLogEntryAutoCreate() {
5090 $this->addNewUserLogEntry( 'autocreate' );
5096 * Load the user options either from cache, the database or an array
5098 * @param array $data Rows for the current user out of the user_properties table
5100 protected function loadOptions( $data = null ) {
5105 if ( $this->mOptionsLoaded
) {
5109 $this->mOptions
= self
::getDefaultOptions();
5111 if ( !$this->getId() ) {
5112 // For unlogged-in users, load language/variant options from request.
5113 // There's no need to do it for logged-in users: they can set preferences,
5114 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5115 // so don't override user's choice (especially when the user chooses site default).
5116 $variant = $wgContLang->getDefaultVariant();
5117 $this->mOptions
['variant'] = $variant;
5118 $this->mOptions
['language'] = $variant;
5119 $this->mOptionsLoaded
= true;
5123 // Maybe load from the object
5124 if ( !is_null( $this->mOptionOverrides
) ) {
5125 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5126 foreach ( $this->mOptionOverrides
as $key => $value ) {
5127 $this->mOptions
[$key] = $value;
5130 if ( !is_array( $data ) ) {
5131 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5132 // Load from database
5133 $dbr = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
5134 ?
wfGetDB( DB_MASTER
)
5135 : wfGetDB( DB_SLAVE
);
5137 $res = $dbr->select(
5139 [ 'up_property', 'up_value' ],
5140 [ 'up_user' => $this->getId() ],
5144 $this->mOptionOverrides
= [];
5146 foreach ( $res as $row ) {
5147 $data[$row->up_property
] = $row->up_value
;
5150 foreach ( $data as $property => $value ) {
5151 $this->mOptionOverrides
[$property] = $value;
5152 $this->mOptions
[$property] = $value;
5156 $this->mOptionsLoaded
= true;
5158 Hooks
::run( 'UserLoadOptions', [ $this, &$this->mOptions
] );
5162 * Saves the non-default options for this user, as previously set e.g. via
5163 * setOption(), in the database's "user_properties" (preferences) table.
5164 * Usually used via saveSettings().
5166 protected function saveOptions() {
5167 $this->loadOptions();
5169 // Not using getOptions(), to keep hidden preferences in database
5170 $saveOptions = $this->mOptions
;
5172 // Allow hooks to abort, for instance to save to a global profile.
5173 // Reset options to default state before saving.
5174 if ( !Hooks
::run( 'UserSaveOptions', [ $this, &$saveOptions ] ) ) {
5178 $userId = $this->getId();
5180 $insert_rows = []; // all the new preference rows
5181 foreach ( $saveOptions as $key => $value ) {
5182 // Don't bother storing default values
5183 $defaultOption = self
::getDefaultOption( $key );
5184 if ( ( $defaultOption === null && $value !== false && $value !== null )
5185 ||
$value != $defaultOption
5188 'up_user' => $userId,
5189 'up_property' => $key,
5190 'up_value' => $value,
5195 $dbw = wfGetDB( DB_MASTER
);
5197 $res = $dbw->select( 'user_properties',
5198 [ 'up_property', 'up_value' ], [ 'up_user' => $userId ], __METHOD__
);
5200 // Find prior rows that need to be removed or updated. These rows will
5201 // all be deleted (the later so that INSERT IGNORE applies the new values).
5203 foreach ( $res as $row ) {
5204 if ( !isset( $saveOptions[$row->up_property
] )
5205 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
5207 $keysDelete[] = $row->up_property
;
5211 if ( count( $keysDelete ) ) {
5212 // Do the DELETE by PRIMARY KEY for prior rows.
5213 // In the past a very large portion of calls to this function are for setting
5214 // 'rememberpassword' for new accounts (a preference that has since been removed).
5215 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5216 // caused gap locks on [max user ID,+infinity) which caused high contention since
5217 // updates would pile up on each other as they are for higher (newer) user IDs.
5218 // It might not be necessary these days, but it shouldn't hurt either.
5219 $dbw->delete( 'user_properties',
5220 [ 'up_user' => $userId, 'up_property' => $keysDelete ], __METHOD__
);
5222 // Insert the new preference rows
5223 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, [ 'IGNORE' ] );
5227 * Lazily instantiate and return a factory object for making passwords
5229 * @deprecated since 1.27, create a PasswordFactory directly instead
5230 * @return PasswordFactory
5232 public static function getPasswordFactory() {
5233 wfDeprecated( __METHOD__
, '1.27' );
5234 $ret = new PasswordFactory();
5235 $ret->init( RequestContext
::getMain()->getConfig() );
5240 * Provide an array of HTML5 attributes to put on an input element
5241 * intended for the user to enter a new password. This may include
5242 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
5244 * Do *not* use this when asking the user to enter his current password!
5245 * Regardless of configuration, users may have invalid passwords for whatever
5246 * reason (e.g., they were set before requirements were tightened up).
5247 * Only use it when asking for a new password, like on account creation or
5250 * Obviously, you still need to do server-side checking.
5252 * NOTE: A combination of bugs in various browsers means that this function
5253 * actually just returns array() unconditionally at the moment. May as
5254 * well keep it around for when the browser bugs get fixed, though.
5256 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
5258 * @deprecated since 1.27
5259 * @return array Array of HTML attributes suitable for feeding to
5260 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
5261 * That will get confused by the boolean attribute syntax used.)
5263 public static function passwordChangeInputAttribs() {
5264 global $wgMinimalPasswordLength;
5266 if ( $wgMinimalPasswordLength == 0 ) {
5270 # Note that the pattern requirement will always be satisfied if the
5271 # input is empty, so we need required in all cases.
5273 # @todo FIXME: Bug 23769: This needs to not claim the password is required
5274 # if e-mail confirmation is being used. Since HTML5 input validation
5275 # is b0rked anyway in some browsers, just return nothing. When it's
5276 # re-enabled, fix this code to not output required for e-mail
5278 # $ret = array( 'required' );
5281 # We can't actually do this right now, because Opera 9.6 will print out
5282 # the entered password visibly in its error message! When other
5283 # browsers add support for this attribute, or Opera fixes its support,
5284 # we can add support with a version check to avoid doing this on Opera
5285 # versions where it will be a problem. Reported to Opera as
5286 # DSK-262266, but they don't have a public bug tracker for us to follow.
5288 if ( $wgMinimalPasswordLength > 1 ) {
5289 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
5290 $ret['title'] = wfMessage( 'passwordtooshort' )
5291 ->numParams( $wgMinimalPasswordLength )->text();
5299 * Return the list of user fields that should be selected to create
5300 * a new user object.
5303 public static function selectFields() {
5311 'user_email_authenticated',
5313 'user_email_token_expires',
5314 'user_registration',
5320 * Factory function for fatal permission-denied errors
5323 * @param string $permission User right required
5326 static function newFatalPermissionDeniedStatus( $permission ) {
5329 $groups = array_map(
5330 [ 'User', 'makeGroupLinkWiki' ],
5331 User
::getGroupsWithPermission( $permission )
5335 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5337 return Status
::newFatal( 'badaccess-group0' );
5342 * Get a new instance of this user that was loaded from the master via a locking read
5344 * Use this instead of the main context User when updating that user. This avoids races
5345 * where that user was loaded from a slave or even the master but without proper locks.
5347 * @return User|null Returns null if the user was not found in the DB
5350 public function getInstanceForUpdate() {
5351 if ( !$this->getId() ) {
5352 return null; // anon
5355 $user = self
::newFromId( $this->getId() );
5356 if ( !$user->loadFromId( self
::READ_EXCLUSIVE
) ) {
5364 * Checks if two user objects point to the same user.
5370 public function equals( User
$user ) {
5371 return $this->getName() === $user->getName();