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\MediaWikiServices
;
24 use MediaWiki\Session\SessionManager
;
25 use MediaWiki\Session\Token
;
28 * String Some punctuation to prevent editing from broken text-mangling proxies.
29 * @deprecated since 1.27, use \MediaWiki\Session\Token::SUFFIX
32 define( 'EDIT_TOKEN_SUFFIX', Token
::SUFFIX
);
35 * The User object encapsulates all of the user-specific settings (user_id,
36 * name, rights, email address, options, last login time). Client
37 * classes use the getXXX() functions to access these fields. These functions
38 * do all the work of determining whether the user is logged in,
39 * whether the requested option can be satisfied from cookies or
40 * whether a database query is needed. Most of the settings needed
41 * for rendering normal pages are set in the cookie to minimize use
44 class User
implements IDBAccessObject
{
46 * @const int Number of characters in user_token field.
48 const TOKEN_LENGTH
= 32;
51 * @const string An invalid value for user_token
53 const INVALID_TOKEN
= '*** INVALID ***';
56 * Global constant made accessible as class constants so that autoloader
58 * @deprecated since 1.27, use \MediaWiki\Session\Token::SUFFIX
60 const EDIT_TOKEN_SUFFIX
= EDIT_TOKEN_SUFFIX
;
63 * @const int Serialized record version.
68 * Exclude user options that are set to their default value.
71 const GETOPTIONS_EXCLUDE_DEFAULTS
= 1;
76 const CHECK_USER_RIGHTS
= true;
81 const IGNORE_USER_RIGHTS
= false;
84 * Array of Strings List of member variables which are saved to the
85 * shared cache (memcached). Any operation which changes the
86 * corresponding database fields must call a cache-clearing function.
89 protected static $mCacheVars = [
97 'mEmailAuthenticated',
104 // user_properties table
109 * Array of Strings Core rights.
110 * Each of these should have a corresponding message of the form
114 protected static $mCoreRights = [
145 'editusercssjs', # deprecated
158 'move-categorypages',
159 'move-rootuserpages',
163 'override-export-depth',
186 'userrights-interwiki',
194 * String Cached results of getAllRights()
196 protected static $mAllRights = false;
199 * An in-process cache for user data lookup
202 protected static $inProcessCache;
204 /** Cache variables */
215 /** @var string TS_MW timestamp from the DB */
217 /** @var string TS_MW timestamp from cache */
218 protected $mQuickTouched;
222 public $mEmailAuthenticated;
224 protected $mEmailToken;
226 protected $mEmailTokenExpires;
228 protected $mRegistration;
230 protected $mEditCount;
234 protected $mOptionOverrides;
238 * Bool Whether the cache variables have been loaded.
241 public $mOptionsLoaded;
244 * Array with already loaded items or true if all items have been loaded.
246 protected $mLoadedItems = [];
250 * String Initialization data source if mLoadedItems!==true. May be one of:
251 * - 'defaults' anonymous user initialised from class defaults
252 * - 'name' initialise from mName
253 * - 'id' initialise from mId
254 * - 'session' log in from session if possible
256 * Use the User::newFrom*() family of functions to set this.
261 * Lazy-initialized variables, invalidated with clearInstanceCache
265 protected $mDatePreference;
273 protected $mBlockreason;
275 protected $mEffectiveGroups;
277 protected $mImplicitGroups;
279 protected $mFormerGroups;
281 protected $mGlobalBlock;
298 protected $mAllowUsertalk;
301 private $mBlockedFromCreateAccount = false;
303 /** @var integer User::READ_* constant bitfield used to load data */
304 protected $queryFlagsUsed = self
::READ_NORMAL
;
306 public static $idCacheByName = [];
309 * Lightweight constructor for an anonymous user.
310 * Use the User::newFrom* factory functions for other kinds of users.
314 * @see newFromConfirmationCode()
315 * @see newFromSession()
318 public function __construct() {
319 $this->clearInstanceCache( 'defaults' );
325 public function __toString() {
326 return $this->getName();
330 * Test if it's safe to load this User object.
332 * You should typically check this before using $wgUser or
333 * RequestContext::getUser in a method that might be called before the
334 * system has been fully initialized. If the object is unsafe, you should
335 * use an anonymous user:
337 * $user = $wgUser->isSafeToLoad() ? $wgUser : new User;
343 public function isSafeToLoad() {
344 global $wgFullyInitialised;
346 // The user is safe to load if:
347 // * MW_NO_SESSION is undefined AND $wgFullyInitialised is true (safe to use session data)
348 // * mLoadedItems === true (already loaded)
349 // * mFrom !== 'session' (sessions not involved at all)
351 return ( !defined( 'MW_NO_SESSION' ) && $wgFullyInitialised ) ||
352 $this->mLoadedItems
=== true ||
$this->mFrom
!== 'session';
356 * Load the user table data for this object from the source given by mFrom.
358 * @param integer $flags User::READ_* constant bitfield
360 public function load( $flags = self
::READ_NORMAL
) {
361 global $wgFullyInitialised;
363 if ( $this->mLoadedItems
=== true ) {
367 // Set it now to avoid infinite recursion in accessors
368 $oldLoadedItems = $this->mLoadedItems
;
369 $this->mLoadedItems
= true;
370 $this->queryFlagsUsed
= $flags;
372 // If this is called too early, things are likely to break.
373 if ( !$wgFullyInitialised && $this->mFrom
=== 'session' ) {
374 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
375 ->warning( 'User::loadFromSession called before the end of Setup.php', [
376 'exception' => new Exception( 'User::loadFromSession called before the end of Setup.php' ),
378 $this->loadDefaults();
379 $this->mLoadedItems
= $oldLoadedItems;
383 switch ( $this->mFrom
) {
385 $this->loadDefaults();
388 // Make sure this thread sees its own changes
389 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
390 $flags |
= self
::READ_LATEST
;
391 $this->queryFlagsUsed
= $flags;
394 $this->mId
= self
::idFromName( $this->mName
, $flags );
396 // Nonexistent user placeholder object
397 $this->loadDefaults( $this->mName
);
399 $this->loadFromId( $flags );
403 $this->loadFromId( $flags );
406 if ( !$this->loadFromSession() ) {
407 // Loading from session failed. Load defaults.
408 $this->loadDefaults();
410 Hooks
::run( 'UserLoadAfterLoadFromSession', [ $this ] );
413 throw new UnexpectedValueException(
414 "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
419 * Load user table data, given mId has already been set.
420 * @param integer $flags User::READ_* constant bitfield
421 * @return bool False if the ID does not exist, true otherwise
423 public function loadFromId( $flags = self
::READ_NORMAL
) {
424 if ( $this->mId
== 0 ) {
425 $this->loadDefaults();
429 // Try cache (unless this needs data from the master DB).
430 // NOTE: if this thread called saveSettings(), the cache was cleared.
431 $latest = DBAccessObjectUtils
::hasFlags( $flags, self
::READ_LATEST
);
432 if ( $latest ||
!$this->loadFromCache() ) {
433 wfDebug( "User: cache miss for user {$this->mId}\n" );
434 // Load from DB (make sure this thread sees its own changes)
435 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
436 $flags |
= self
::READ_LATEST
;
438 if ( !$this->loadFromDatabase( $flags ) ) {
439 // Can't load from ID, user is anonymous
442 $this->saveToCache();
445 $this->mLoadedItems
= true;
446 $this->queryFlagsUsed
= $flags;
453 * @param string $wikiId
454 * @param integer $userId
456 public static function purge( $wikiId, $userId ) {
457 $cache = ObjectCache
::getMainWANInstance();
458 $processCache = self
::getInProcessCache();
459 $key = $cache->makeGlobalKey( 'user', 'id', $wikiId, $userId );
460 $cache->delete( $key );
461 $processCache->delete( $key );
466 * @param WANObjectCache $cache
469 protected function getCacheKey( WANObjectCache
$cache ) {
470 return $cache->makeGlobalKey( 'user', 'id', wfWikiID(), $this->mId
);
475 * @return HashBagOStuff
477 protected static function getInProcessCache() {
478 if ( !self
::$inProcessCache ) {
479 self
::$inProcessCache = new HashBagOStuff( [ 'maxKeys' => 10 ] );
481 return self
::$inProcessCache;
485 * Load user data from shared cache, given mId has already been set.
487 * @return bool false if the ID does not exist or data is invalid, true otherwise
490 protected function loadFromCache() {
491 if ( $this->mId
== 0 ) {
492 $this->loadDefaults();
496 $cache = ObjectCache
::getMainWANInstance();
497 $processCache = self
::getInProcessCache();
498 $key = $this->getCacheKey( $cache );
499 $data = $processCache->get( $key );
500 if ( !is_array( $data ) ) {
501 $data = $cache->get( $key );
502 if ( !is_array( $data )
503 ||
!isset( $data['mVersion'] )
504 ||
$data['mVersion'] < self
::VERSION
509 $processCache->set( $key, $data );
511 wfDebug( "User: got user {$this->mId} from cache\n" );
513 // Restore from cache
514 foreach ( self
::$mCacheVars as $name ) {
515 $this->$name = $data[$name];
522 * Save user data to the shared cache
524 * This method should not be called outside the User class
526 public function saveToCache() {
529 $this->loadOptions();
531 if ( $this->isAnon() ) {
532 // Anonymous users are uncached
537 foreach ( self
::$mCacheVars as $name ) {
538 $data[$name] = $this->$name;
540 $data['mVersion'] = self
::VERSION
;
541 $opts = Database
::getCacheSetOptions( wfGetDB( DB_SLAVE
) );
543 $cache = ObjectCache
::getMainWANInstance();
544 $processCache = self
::getInProcessCache();
545 $key = $this->getCacheKey( $cache );
546 $cache->set( $key, $data, $cache::TTL_HOUR
, $opts );
547 $processCache->set( $key, $data );
550 /** @name newFrom*() static factory methods */
554 * Static factory method for creation from username.
556 * This is slightly less efficient than newFromId(), so use newFromId() if
557 * you have both an ID and a name handy.
559 * @param string $name Username, validated by Title::newFromText()
560 * @param string|bool $validate Validate username. Takes the same parameters as
561 * User::getCanonicalName(), except that true is accepted as an alias
562 * for 'valid', for BC.
564 * @return User|bool User object, or false if the username is invalid
565 * (e.g. if it contains illegal characters or is an IP address). If the
566 * username is not present in the database, the result will be a user object
567 * with a name, zero user ID and default settings.
569 public static function newFromName( $name, $validate = 'valid' ) {
570 if ( $validate === true ) {
573 $name = self
::getCanonicalName( $name, $validate );
574 if ( $name === false ) {
577 // Create unloaded user object
581 $u->setItemLoaded( 'name' );
587 * Static factory method for creation from a given user ID.
589 * @param int $id Valid user ID
590 * @return User The corresponding User object
592 public static function newFromId( $id ) {
596 $u->setItemLoaded( 'id' );
601 * Factory method to fetch whichever user has a given email confirmation code.
602 * This code is generated when an account is created or its e-mail address
605 * If the code is invalid or has expired, returns NULL.
607 * @param string $code Confirmation code
608 * @param int $flags User::READ_* bitfield
611 public static function newFromConfirmationCode( $code, $flags = 0 ) {
612 $db = ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
613 ?
wfGetDB( DB_MASTER
)
614 : wfGetDB( DB_SLAVE
);
616 $id = $db->selectField(
620 'user_email_token' => md5( $code ),
621 'user_email_token_expires > ' . $db->addQuotes( $db->timestamp() ),
625 return $id ? User
::newFromId( $id ) : null;
629 * Create a new user object using data from session. If the login
630 * credentials are invalid, the result is an anonymous user.
632 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
635 public static function newFromSession( WebRequest
$request = null ) {
637 $user->mFrom
= 'session';
638 $user->mRequest
= $request;
643 * Create a new user object from a user row.
644 * The row should have the following fields from the user table in it:
645 * - either user_name or user_id to load further data if needed (or both)
647 * - all other fields (email, etc.)
648 * It is useless to provide the remaining fields if either user_id,
649 * user_name and user_real_name are not provided because the whole row
650 * will be loaded once more from the database when accessing them.
652 * @param stdClass $row A row from the user table
653 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
656 public static function newFromRow( $row, $data = null ) {
658 $user->loadFromRow( $row, $data );
663 * Static factory method for creation of a "system" user from username.
665 * A "system" user is an account that's used to attribute logged actions
666 * taken by MediaWiki itself, as opposed to a bot or human user. Examples
667 * might include the 'Maintenance script' or 'Conversion script' accounts
668 * used by various scripts in the maintenance/ directory or accounts such
669 * as 'MediaWiki message delivery' used by the MassMessage extension.
671 * This can optionally create the user if it doesn't exist, and "steal" the
672 * account if it does exist.
674 * @param string $name Username
675 * @param array $options Options are:
676 * - validate: As for User::getCanonicalName(), default 'valid'
677 * - create: Whether to create the user if it doesn't already exist, default true
678 * - steal: Whether to reset the account's password and email if it
679 * already exists, default false
682 public static function newSystemUser( $name, $options = [] ) {
684 'validate' => 'valid',
689 $name = self
::getCanonicalName( $name, $options['validate'] );
690 if ( $name === false ) {
694 $dbw = wfGetDB( DB_MASTER
);
695 $row = $dbw->selectRow(
698 self
::selectFields(),
699 [ 'user_password', 'user_newpassword' ]
701 [ 'user_name' => $name ],
705 // No user. Create it?
706 return $options['create'] ? self
::createNew( $name ) : null;
708 $user = self
::newFromRow( $row );
710 // A user is considered to exist as a non-system user if it has a
711 // password set, or a temporary password set, or an email set, or a
712 // non-invalid token.
713 $passwordFactory = new PasswordFactory();
714 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
716 $password = $passwordFactory->newFromCiphertext( $row->user_password
);
717 } catch ( PasswordError
$e ) {
718 wfDebug( 'Invalid password hash found in database.' );
719 $password = PasswordFactory
::newInvalidPassword();
722 $newpassword = $passwordFactory->newFromCiphertext( $row->user_newpassword
);
723 } catch ( PasswordError
$e ) {
724 wfDebug( 'Invalid password hash found in database.' );
725 $newpassword = PasswordFactory
::newInvalidPassword();
727 if ( !$password instanceof InvalidPassword ||
!$newpassword instanceof InvalidPassword
728 ||
$user->mEmail ||
$user->mToken
!== self
::INVALID_TOKEN
730 // User exists. Steal it?
731 if ( !$options['steal'] ) {
735 $nopass = PasswordFactory
::newInvalidPassword()->toString();
740 'user_password' => $nopass,
741 'user_newpassword' => $nopass,
742 'user_newpass_time' => null,
744 [ 'user_id' => $user->getId() ],
747 $user->invalidateEmail();
748 $user->mToken
= self
::INVALID_TOKEN
;
749 $user->saveSettings();
750 SessionManager
::singleton()->preventSessionsForUser( $user->getName() );
759 * Get the username corresponding to a given user ID
760 * @param int $id User ID
761 * @return string|bool The corresponding username
763 public static function whoIs( $id ) {
764 return UserCache
::singleton()->getProp( $id, 'name' );
768 * Get the real name of a user given their user ID
770 * @param int $id User ID
771 * @return string|bool The corresponding user's real name
773 public static function whoIsReal( $id ) {
774 return UserCache
::singleton()->getProp( $id, 'real_name' );
778 * Get database id given a user name
779 * @param string $name Username
780 * @param integer $flags User::READ_* constant bitfield
781 * @return int|null The corresponding user's ID, or null if user is nonexistent
783 public static function idFromName( $name, $flags = self
::READ_NORMAL
) {
784 $nt = Title
::makeTitleSafe( NS_USER
, $name );
785 if ( is_null( $nt ) ) {
790 if ( !( $flags & self
::READ_LATEST
) && isset( self
::$idCacheByName[$name] ) ) {
791 return self
::$idCacheByName[$name];
794 $db = ( $flags & self
::READ_LATEST
)
795 ?
wfGetDB( DB_MASTER
)
796 : wfGetDB( DB_SLAVE
);
801 [ 'user_name' => $nt->getText() ],
805 if ( $s === false ) {
808 $result = $s->user_id
;
811 self
::$idCacheByName[$name] = $result;
813 if ( count( self
::$idCacheByName ) > 1000 ) {
814 self
::$idCacheByName = [];
821 * Reset the cache used in idFromName(). For use in tests.
823 public static function resetIdByNameCache() {
824 self
::$idCacheByName = [];
828 * Does the string match an anonymous IPv4 address?
830 * This function exists for username validation, in order to reject
831 * usernames which are similar in form to IP addresses. Strings such
832 * as 300.300.300.300 will return true because it looks like an IP
833 * address, despite not being strictly valid.
835 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
836 * address because the usemod software would "cloak" anonymous IP
837 * addresses like this, if we allowed accounts like this to be created
838 * new users could get the old edits of these anonymous users.
840 * @param string $name Name to match
843 public static function isIP( $name ) {
844 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
845 || IP
::isIPv6( $name );
849 * Is the input a valid username?
851 * Checks if the input is a valid username, we don't want an empty string,
852 * an IP address, anything that contains slashes (would mess up subpages),
853 * is longer than the maximum allowed username size or doesn't begin with
856 * @param string $name Name to match
859 public static function isValidUserName( $name ) {
860 global $wgContLang, $wgMaxNameChars;
863 || User
::isIP( $name )
864 ||
strpos( $name, '/' ) !== false
865 ||
strlen( $name ) > $wgMaxNameChars
866 ||
$name != $wgContLang->ucfirst( $name )
871 // Ensure that the name can't be misresolved as a different title,
872 // such as with extra namespace keys at the start.
873 $parsed = Title
::newFromText( $name );
874 if ( is_null( $parsed )
875 ||
$parsed->getNamespace()
876 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
880 // Check an additional blacklist of troublemaker characters.
881 // Should these be merged into the title char list?
882 $unicodeBlacklist = '/[' .
883 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
884 '\x{00a0}' . # non-breaking space
885 '\x{2000}-\x{200f}' . # various whitespace
886 '\x{2028}-\x{202f}' . # breaks and control chars
887 '\x{3000}' . # ideographic space
888 '\x{e000}-\x{f8ff}' . # private use
890 if ( preg_match( $unicodeBlacklist, $name ) ) {
898 * Usernames which fail to pass this function will be blocked
899 * from user login and new account registrations, but may be used
900 * internally by batch processes.
902 * If an account already exists in this form, login will be blocked
903 * by a failure to pass this function.
905 * @param string $name Name to match
908 public static function isUsableName( $name ) {
909 global $wgReservedUsernames;
910 // Must be a valid username, obviously ;)
911 if ( !self
::isValidUserName( $name ) ) {
915 static $reservedUsernames = false;
916 if ( !$reservedUsernames ) {
917 $reservedUsernames = $wgReservedUsernames;
918 Hooks
::run( 'UserGetReservedNames', [ &$reservedUsernames ] );
921 // Certain names may be reserved for batch processes.
922 foreach ( $reservedUsernames as $reserved ) {
923 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
924 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
926 if ( $reserved == $name ) {
934 * Usernames which fail to pass this function will be blocked
935 * from new account registrations, but may be used internally
936 * either by batch processes or by user accounts which have
937 * already been created.
939 * Additional blacklisting may be added here rather than in
940 * isValidUserName() to avoid disrupting existing accounts.
942 * @param string $name String to match
945 public static function isCreatableName( $name ) {
946 global $wgInvalidUsernameCharacters;
948 // Ensure that the username isn't longer than 235 bytes, so that
949 // (at least for the builtin skins) user javascript and css files
950 // will work. (bug 23080)
951 if ( strlen( $name ) > 235 ) {
952 wfDebugLog( 'username', __METHOD__
.
953 ": '$name' invalid due to length" );
957 // Preg yells if you try to give it an empty string
958 if ( $wgInvalidUsernameCharacters !== '' ) {
959 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
960 wfDebugLog( 'username', __METHOD__
.
961 ": '$name' invalid due to wgInvalidUsernameCharacters" );
966 return self
::isUsableName( $name );
970 * Is the input a valid password for this user?
972 * @param string $password Desired password
975 public function isValidPassword( $password ) {
976 // simple boolean wrapper for getPasswordValidity
977 return $this->getPasswordValidity( $password ) === true;
981 * Given unvalidated password input, return error message on failure.
983 * @param string $password Desired password
984 * @return bool|string|array True on success, string or array of error message on failure
986 public function getPasswordValidity( $password ) {
987 $result = $this->checkPasswordValidity( $password );
988 if ( $result->isGood() ) {
992 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
993 $messages[] = $error['message'];
995 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
996 $messages[] = $warning['message'];
998 if ( count( $messages ) === 1 ) {
1006 * Check if this is a valid password for this user
1008 * Create a Status object based on the password's validity.
1009 * The Status should be set to fatal if the user should not
1010 * be allowed to log in, and should have any errors that
1011 * would block changing the password.
1013 * If the return value of this is not OK, the password
1014 * should not be checked. If the return value is not Good,
1015 * the password can be checked, but the user should not be
1016 * able to set their password to this.
1018 * @param string $password Desired password
1019 * @param string $purpose one of 'login', 'create', 'reset'
1023 public function checkPasswordValidity( $password, $purpose = 'login' ) {
1024 global $wgPasswordPolicy;
1026 $upp = new UserPasswordPolicy(
1027 $wgPasswordPolicy['policies'],
1028 $wgPasswordPolicy['checks']
1031 $status = Status
::newGood();
1032 $result = false; // init $result to false for the internal checks
1034 if ( !Hooks
::run( 'isValidPassword', [ $password, &$result, $this ] ) ) {
1035 $status->error( $result );
1039 if ( $result === false ) {
1040 $status->merge( $upp->checkUserPassword( $this, $password, $purpose ) );
1042 } elseif ( $result === true ) {
1045 $status->error( $result );
1046 return $status; // the isValidPassword hook set a string $result and returned true
1051 * Given unvalidated user input, return a canonical username, or false if
1052 * the username is invalid.
1053 * @param string $name User input
1054 * @param string|bool $validate Type of validation to use:
1055 * - false No validation
1056 * - 'valid' Valid for batch processes
1057 * - 'usable' Valid for batch processes and login
1058 * - 'creatable' Valid for batch processes, login and account creation
1060 * @throws InvalidArgumentException
1061 * @return bool|string
1063 public static function getCanonicalName( $name, $validate = 'valid' ) {
1064 // Force usernames to capital
1066 $name = $wgContLang->ucfirst( $name );
1068 # Reject names containing '#'; these will be cleaned up
1069 # with title normalisation, but then it's too late to
1071 if ( strpos( $name, '#' ) !== false ) {
1075 // Clean up name according to title rules,
1076 // but only when validation is requested (bug 12654)
1077 $t = ( $validate !== false ) ?
1078 Title
::newFromText( $name, NS_USER
) : Title
::makeTitle( NS_USER
, $name );
1079 // Check for invalid titles
1080 if ( is_null( $t ) ||
$t->getNamespace() !== NS_USER ||
$t->isExternal() ) {
1084 // Reject various classes of invalid names
1086 $name = $wgAuth->getCanonicalName( $t->getText() );
1088 switch ( $validate ) {
1092 if ( !User
::isValidUserName( $name ) ) {
1097 if ( !User
::isUsableName( $name ) ) {
1102 if ( !User
::isCreatableName( $name ) ) {
1107 throw new InvalidArgumentException(
1108 'Invalid parameter value for $validate in ' . __METHOD__
);
1114 * Count the number of edits of a user
1116 * @param int $uid User ID to check
1117 * @return int The user's edit count
1119 * @deprecated since 1.21 in favour of User::getEditCount
1121 public static function edits( $uid ) {
1122 wfDeprecated( __METHOD__
, '1.21' );
1123 $user = self
::newFromId( $uid );
1124 return $user->getEditCount();
1128 * Return a random password.
1130 * @deprecated since 1.27, use PasswordFactory::generateRandomPasswordString()
1131 * @return string New random password
1133 public static function randomPassword() {
1134 global $wgMinimalPasswordLength;
1135 return PasswordFactory
::generateRandomPasswordString( $wgMinimalPasswordLength );
1139 * Set cached properties to default.
1141 * @note This no longer clears uncached lazy-initialised properties;
1142 * the constructor does that instead.
1144 * @param string|bool $name
1146 public function loadDefaults( $name = false ) {
1148 $this->mName
= $name;
1149 $this->mRealName
= '';
1151 $this->mOptionOverrides
= null;
1152 $this->mOptionsLoaded
= false;
1154 $loggedOut = $this->mRequest
&& !defined( 'MW_NO_SESSION' )
1155 ?
$this->mRequest
->getSession()->getLoggedOutTimestamp() : 0;
1156 if ( $loggedOut !== 0 ) {
1157 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1159 $this->mTouched
= '1'; # Allow any pages to be cached
1162 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1163 $this->mEmailAuthenticated
= null;
1164 $this->mEmailToken
= '';
1165 $this->mEmailTokenExpires
= null;
1166 $this->mRegistration
= wfTimestamp( TS_MW
);
1167 $this->mGroups
= [];
1169 Hooks
::run( 'UserLoadDefaults', [ $this, $name ] );
1173 * Return whether an item has been loaded.
1175 * @param string $item Item to check. Current possibilities:
1179 * @param string $all 'all' to check if the whole object has been loaded
1180 * or any other string to check if only the item is available (e.g.
1184 public function isItemLoaded( $item, $all = 'all' ) {
1185 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1186 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1190 * Set that an item has been loaded
1192 * @param string $item
1194 protected function setItemLoaded( $item ) {
1195 if ( is_array( $this->mLoadedItems
) ) {
1196 $this->mLoadedItems
[$item] = true;
1201 * Load user data from the session.
1203 * @return bool True if the user is logged in, false otherwise.
1205 private function loadFromSession() {
1208 Hooks
::run( 'UserLoadFromSession', [ $this, &$result ], '1.27' );
1209 if ( $result !== null ) {
1213 // MediaWiki\Session\Session already did the necessary authentication of the user
1214 // returned here, so just use it if applicable.
1215 $session = $this->getRequest()->getSession();
1216 $user = $session->getUser();
1217 if ( $user->isLoggedIn() ) {
1218 $this->loadFromUserObject( $user );
1219 // Other code expects these to be set in the session, so set them.
1220 $session->set( 'wsUserID', $this->getId() );
1221 $session->set( 'wsUserName', $this->getName() );
1222 $session->set( 'wsToken', $this->getToken() );
1230 * Load user and user_group data from the database.
1231 * $this->mId must be set, this is how the user is identified.
1233 * @param integer $flags User::READ_* constant bitfield
1234 * @return bool True if the user exists, false if the user is anonymous
1236 public function loadFromDatabase( $flags = self
::READ_LATEST
) {
1238 $this->mId
= intval( $this->mId
);
1241 if ( !$this->mId
) {
1242 $this->loadDefaults();
1246 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
1247 $db = wfGetDB( $index );
1249 $s = $db->selectRow(
1251 self
::selectFields(),
1252 [ 'user_id' => $this->mId
],
1257 $this->queryFlagsUsed
= $flags;
1258 Hooks
::run( 'UserLoadFromDatabase', [ $this, &$s ] );
1260 if ( $s !== false ) {
1261 // Initialise user table data
1262 $this->loadFromRow( $s );
1263 $this->mGroups
= null; // deferred
1264 $this->getEditCount(); // revalidation for nulls
1269 $this->loadDefaults();
1275 * Initialize this object from a row from the user table.
1277 * @param stdClass $row Row from the user table to load.
1278 * @param array $data Further user data to load into the object
1280 * user_groups Array with groups out of the user_groups table
1281 * user_properties Array with properties out of the user_properties table
1283 protected function loadFromRow( $row, $data = null ) {
1286 $this->mGroups
= null; // deferred
1288 if ( isset( $row->user_name
) ) {
1289 $this->mName
= $row->user_name
;
1290 $this->mFrom
= 'name';
1291 $this->setItemLoaded( 'name' );
1296 if ( isset( $row->user_real_name
) ) {
1297 $this->mRealName
= $row->user_real_name
;
1298 $this->setItemLoaded( 'realname' );
1303 if ( isset( $row->user_id
) ) {
1304 $this->mId
= intval( $row->user_id
);
1305 $this->mFrom
= 'id';
1306 $this->setItemLoaded( 'id' );
1311 if ( isset( $row->user_id
) && isset( $row->user_name
) ) {
1312 self
::$idCacheByName[$row->user_name
] = $row->user_id
;
1315 if ( isset( $row->user_editcount
) ) {
1316 $this->mEditCount
= $row->user_editcount
;
1321 if ( isset( $row->user_touched
) ) {
1322 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1327 if ( isset( $row->user_token
) ) {
1328 // The definition for the column is binary(32), so trim the NULs
1329 // that appends. The previous definition was char(32), so trim
1331 $this->mToken
= rtrim( $row->user_token
, " \0" );
1332 if ( $this->mToken
=== '' ) {
1333 $this->mToken
= null;
1339 if ( isset( $row->user_email
) ) {
1340 $this->mEmail
= $row->user_email
;
1341 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1342 $this->mEmailToken
= $row->user_email_token
;
1343 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1344 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1350 $this->mLoadedItems
= true;
1353 if ( is_array( $data ) ) {
1354 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1355 $this->mGroups
= $data['user_groups'];
1357 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1358 $this->loadOptions( $data['user_properties'] );
1364 * Load the data for this user object from another user object.
1368 protected function loadFromUserObject( $user ) {
1370 $user->loadGroups();
1371 $user->loadOptions();
1372 foreach ( self
::$mCacheVars as $var ) {
1373 $this->$var = $user->$var;
1378 * Load the groups from the database if they aren't already loaded.
1380 private function loadGroups() {
1381 if ( is_null( $this->mGroups
) ) {
1382 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
1383 ?
wfGetDB( DB_MASTER
)
1384 : wfGetDB( DB_SLAVE
);
1385 $res = $db->select( 'user_groups',
1387 [ 'ug_user' => $this->mId
],
1389 $this->mGroups
= [];
1390 foreach ( $res as $row ) {
1391 $this->mGroups
[] = $row->ug_group
;
1397 * Add the user to the group if he/she meets given criteria.
1399 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1400 * possible to remove manually via Special:UserRights. In such case it
1401 * will not be re-added automatically. The user will also not lose the
1402 * group if they no longer meet the criteria.
1404 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1406 * @return array Array of groups the user has been promoted to.
1408 * @see $wgAutopromoteOnce
1410 public function addAutopromoteOnceGroups( $event ) {
1411 global $wgAutopromoteOnceLogInRC, $wgAuth;
1413 if ( wfReadOnly() ||
!$this->getId() ) {
1417 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1418 if ( !count( $toPromote ) ) {
1422 if ( !$this->checkAndSetTouched() ) {
1423 return []; // raced out (bug T48834)
1426 $oldGroups = $this->getGroups(); // previous groups
1427 foreach ( $toPromote as $group ) {
1428 $this->addGroup( $group );
1430 // update groups in external authentication database
1431 Hooks
::run( 'UserGroupsChanged', [ $this, $toPromote, [], false, false ] );
1432 $wgAuth->updateExternalDBGroups( $this, $toPromote );
1434 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1436 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1437 $logEntry->setPerformer( $this );
1438 $logEntry->setTarget( $this->getUserPage() );
1439 $logEntry->setParameters( [
1440 '4::oldgroups' => $oldGroups,
1441 '5::newgroups' => $newGroups,
1443 $logid = $logEntry->insert();
1444 if ( $wgAutopromoteOnceLogInRC ) {
1445 $logEntry->publish( $logid );
1452 * Bump user_touched if it didn't change since this object was loaded
1454 * On success, the mTouched field is updated.
1455 * The user serialization cache is always cleared.
1457 * @return bool Whether user_touched was actually updated
1460 protected function checkAndSetTouched() {
1463 if ( !$this->mId
) {
1464 return false; // anon
1467 // Get a new user_touched that is higher than the old one
1468 $oldTouched = $this->mTouched
;
1469 $newTouched = $this->newTouchedTimestamp();
1471 $dbw = wfGetDB( DB_MASTER
);
1472 $dbw->update( 'user',
1473 [ 'user_touched' => $dbw->timestamp( $newTouched ) ],
1475 'user_id' => $this->mId
,
1476 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
1480 $success = ( $dbw->affectedRows() > 0 );
1483 $this->mTouched
= $newTouched;
1484 $this->clearSharedCache();
1486 // Clears on failure too since that is desired if the cache is stale
1487 $this->clearSharedCache( 'refresh' );
1494 * Clear various cached data stored in this object. The cache of the user table
1495 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1497 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1498 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1500 public function clearInstanceCache( $reloadFrom = false ) {
1501 $this->mNewtalk
= -1;
1502 $this->mDatePreference
= null;
1503 $this->mBlockedby
= -1; # Unset
1504 $this->mHash
= false;
1505 $this->mRights
= null;
1506 $this->mEffectiveGroups
= null;
1507 $this->mImplicitGroups
= null;
1508 $this->mGroups
= null;
1509 $this->mOptions
= null;
1510 $this->mOptionsLoaded
= false;
1511 $this->mEditCount
= null;
1513 if ( $reloadFrom ) {
1514 $this->mLoadedItems
= [];
1515 $this->mFrom
= $reloadFrom;
1520 * Combine the language default options with any site-specific options
1521 * and add the default language variants.
1523 * @return array Array of String options
1525 public static function getDefaultOptions() {
1526 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1528 static $defOpt = null;
1529 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1530 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1531 // mid-request and see that change reflected in the return value of this function.
1532 // Which is insane and would never happen during normal MW operation
1536 $defOpt = $wgDefaultUserOptions;
1537 // Default language setting
1538 $defOpt['language'] = $wgContLang->getCode();
1539 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1540 $defOpt[$langCode == $wgContLang->getCode() ?
'variant' : "variant-$langCode"] = $langCode;
1542 $namespaces = MediaWikiServices
::getInstance()->getSearchEngineConfig()->searchableNamespaces();
1543 foreach ( $namespaces as $nsnum => $nsname ) {
1544 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1546 $defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1548 Hooks
::run( 'UserGetDefaultOptions', [ &$defOpt ] );
1554 * Get a given default option value.
1556 * @param string $opt Name of option to retrieve
1557 * @return string Default option value
1559 public static function getDefaultOption( $opt ) {
1560 $defOpts = self
::getDefaultOptions();
1561 if ( isset( $defOpts[$opt] ) ) {
1562 return $defOpts[$opt];
1569 * Get blocking information
1570 * @param bool $bFromSlave Whether to check the slave database first.
1571 * To improve performance, non-critical checks are done against slaves.
1572 * Check when actually saving should be done against master.
1574 private function getBlockedStatus( $bFromSlave = true ) {
1575 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1577 if ( -1 != $this->mBlockedby
) {
1581 wfDebug( __METHOD__
. ": checking...\n" );
1583 // Initialize data...
1584 // Otherwise something ends up stomping on $this->mBlockedby when
1585 // things get lazy-loaded later, causing false positive block hits
1586 // due to -1 !== 0. Probably session-related... Nothing should be
1587 // overwriting mBlockedby, surely?
1590 # We only need to worry about passing the IP address to the Block generator if the
1591 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1592 # know which IP address they're actually coming from
1594 if ( !$this->isAllowed( 'ipblock-exempt' ) ) {
1595 // $wgUser->getName() only works after the end of Setup.php. Until
1596 // then, assume it's a logged-out user.
1597 $globalUserName = $wgUser->isSafeToLoad()
1598 ?
$wgUser->getName()
1599 : IP
::sanitizeIP( $wgUser->getRequest()->getIP() );
1600 if ( $this->getName() === $globalUserName ) {
1601 $ip = $this->getRequest()->getIP();
1606 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1609 if ( !$block instanceof Block
&& $ip !== null && !in_array( $ip, $wgProxyWhitelist ) ) {
1611 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1613 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1614 $block->mReason
= wfMessage( 'proxyblockreason' )->text();
1615 $block->setTarget( $ip );
1616 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1618 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1619 $block->mReason
= wfMessage( 'sorbsreason' )->text();
1620 $block->setTarget( $ip );
1624 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1625 if ( !$block instanceof Block
1626 && $wgApplyIpBlocksToXff
1628 && !in_array( $ip, $wgProxyWhitelist )
1630 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1631 $xff = array_map( 'trim', explode( ',', $xff ) );
1632 $xff = array_diff( $xff, [ $ip ] );
1633 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1634 $block = Block
::chooseBlock( $xffblocks, $xff );
1635 if ( $block instanceof Block
) {
1636 # Mangle the reason to alert the user that the block
1637 # originated from matching the X-Forwarded-For header.
1638 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->text();
1642 if ( $block instanceof Block
) {
1643 wfDebug( __METHOD__
. ": Found block.\n" );
1644 $this->mBlock
= $block;
1645 $this->mBlockedby
= $block->getByName();
1646 $this->mBlockreason
= $block->mReason
;
1647 $this->mHideName
= $block->mHideName
;
1648 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1650 $this->mBlockedby
= '';
1651 $this->mHideName
= 0;
1652 $this->mAllowUsertalk
= false;
1656 Hooks
::run( 'GetBlockedStatus', [ &$this ] );
1661 * Whether the given IP is in a DNS blacklist.
1663 * @param string $ip IP to check
1664 * @param bool $checkWhitelist Whether to check the whitelist first
1665 * @return bool True if blacklisted.
1667 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1668 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1670 if ( !$wgEnableDnsBlacklist ) {
1674 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1678 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1682 * Whether the given IP is in a given DNS blacklist.
1684 * @param string $ip IP to check
1685 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1686 * @return bool True if blacklisted.
1688 public function inDnsBlacklist( $ip, $bases ) {
1691 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1692 if ( IP
::isIPv4( $ip ) ) {
1693 // Reverse IP, bug 21255
1694 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1696 foreach ( (array)$bases as $base ) {
1698 // If we have an access key, use that too (ProjectHoneypot, etc.)
1700 if ( is_array( $base ) ) {
1701 if ( count( $base ) >= 2 ) {
1702 // Access key is 1, base URL is 0
1703 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1705 $host = "$ipReversed.{$base[0]}";
1707 $basename = $base[0];
1709 $host = "$ipReversed.$base";
1713 $ipList = gethostbynamel( $host );
1716 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
1720 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
1729 * Check if an IP address is in the local proxy list
1735 public static function isLocallyBlockedProxy( $ip ) {
1736 global $wgProxyList;
1738 if ( !$wgProxyList ) {
1742 if ( !is_array( $wgProxyList ) ) {
1743 // Load from the specified file
1744 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1747 if ( !is_array( $wgProxyList ) ) {
1749 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1751 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1752 // Old-style flipped proxy list
1761 * Is this user subject to rate limiting?
1763 * @return bool True if rate limited
1765 public function isPingLimitable() {
1766 global $wgRateLimitsExcludedIPs;
1767 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1768 // No other good way currently to disable rate limits
1769 // for specific IPs. :P
1770 // But this is a crappy hack and should die.
1773 return !$this->isAllowed( 'noratelimit' );
1777 * Primitive rate limits: enforce maximum actions per time period
1778 * to put a brake on flooding.
1780 * The method generates both a generic profiling point and a per action one
1781 * (suffix being "-$action".
1783 * @note When using a shared cache like memcached, IP-address
1784 * last-hit counters will be shared across wikis.
1786 * @param string $action Action to enforce; 'edit' if unspecified
1787 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1788 * @return bool True if a rate limiter was tripped
1790 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1791 // Call the 'PingLimiter' hook
1793 if ( !Hooks
::run( 'PingLimiter', [ &$this, $action, &$result, $incrBy ] ) ) {
1797 global $wgRateLimits;
1798 if ( !isset( $wgRateLimits[$action] ) ) {
1802 // Some groups shouldn't trigger the ping limiter, ever
1803 if ( !$this->isPingLimitable() ) {
1807 $limits = $wgRateLimits[$action];
1809 $id = $this->getId();
1811 $isNewbie = $this->isNewbie();
1815 if ( isset( $limits['anon'] ) ) {
1816 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1819 // limits for logged-in users
1820 if ( isset( $limits['user'] ) ) {
1821 $userLimit = $limits['user'];
1823 // limits for newbie logged-in users
1824 if ( $isNewbie && isset( $limits['newbie'] ) ) {
1825 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1829 // limits for anons and for newbie logged-in users
1832 if ( isset( $limits['ip'] ) ) {
1833 $ip = $this->getRequest()->getIP();
1834 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1836 // subnet-based limits
1837 if ( isset( $limits['subnet'] ) ) {
1838 $ip = $this->getRequest()->getIP();
1839 $subnet = IP
::getSubnet( $ip );
1840 if ( $subnet !== false ) {
1841 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1846 // Check for group-specific permissions
1847 // If more than one group applies, use the group with the highest limit ratio (max/period)
1848 foreach ( $this->getGroups() as $group ) {
1849 if ( isset( $limits[$group] ) ) {
1850 if ( $userLimit === false
1851 ||
$limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1853 $userLimit = $limits[$group];
1858 // Set the user limit key
1859 if ( $userLimit !== false ) {
1860 list( $max, $period ) = $userLimit;
1861 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
1862 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1865 // ip-based limits for all ping-limitable users
1866 if ( isset( $limits['ip-all'] ) ) {
1867 $ip = $this->getRequest()->getIP();
1868 // ignore if user limit is more permissive
1869 if ( $isNewbie ||
$userLimit === false
1870 ||
$limits['ip-all'][0] / $limits['ip-all'][1] > $userLimit[0] / $userLimit[1] ) {
1871 $keys["mediawiki:limiter:$action:ip-all:$ip"] = $limits['ip-all'];
1875 // subnet-based limits for all ping-limitable users
1876 if ( isset( $limits['subnet-all'] ) ) {
1877 $ip = $this->getRequest()->getIP();
1878 $subnet = IP
::getSubnet( $ip );
1879 if ( $subnet !== false ) {
1880 // ignore if user limit is more permissive
1881 if ( $isNewbie ||
$userLimit === false
1882 ||
$limits['ip-all'][0] / $limits['ip-all'][1]
1883 > $userLimit[0] / $userLimit[1] ) {
1884 $keys["mediawiki:limiter:$action:subnet-all:$subnet"] = $limits['subnet-all'];
1889 $cache = ObjectCache
::getLocalClusterInstance();
1892 foreach ( $keys as $key => $limit ) {
1893 list( $max, $period ) = $limit;
1894 $summary = "(limit $max in {$period}s)";
1895 $count = $cache->get( $key );
1898 if ( $count >= $max ) {
1899 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1900 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1903 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1906 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1907 if ( $incrBy > 0 ) {
1908 $cache->add( $key, 0, intval( $period ) ); // first ping
1911 if ( $incrBy > 0 ) {
1912 $cache->incr( $key, $incrBy );
1920 * Check if user is blocked
1922 * @param bool $bFromSlave Whether to check the slave database instead of
1923 * the master. Hacked from false due to horrible probs on site.
1924 * @return bool True if blocked, false otherwise
1926 public function isBlocked( $bFromSlave = true ) {
1927 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
1931 * Get the block affecting the user, or null if the user is not blocked
1933 * @param bool $bFromSlave Whether to check the slave database instead of the master
1934 * @return Block|null
1936 public function getBlock( $bFromSlave = true ) {
1937 $this->getBlockedStatus( $bFromSlave );
1938 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
1942 * Check if user is blocked from editing a particular article
1944 * @param Title $title Title to check
1945 * @param bool $bFromSlave Whether to check the slave database instead of the master
1948 public function isBlockedFrom( $title, $bFromSlave = false ) {
1949 global $wgBlockAllowsUTEdit;
1951 $blocked = $this->isBlocked( $bFromSlave );
1952 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
1953 // If a user's name is suppressed, they cannot make edits anywhere
1954 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName()
1955 && $title->getNamespace() == NS_USER_TALK
) {
1957 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
1960 Hooks
::run( 'UserIsBlockedFrom', [ $this, $title, &$blocked, &$allowUsertalk ] );
1966 * If user is blocked, return the name of the user who placed the block
1967 * @return string Name of blocker
1969 public function blockedBy() {
1970 $this->getBlockedStatus();
1971 return $this->mBlockedby
;
1975 * If user is blocked, return the specified reason for the block
1976 * @return string Blocking reason
1978 public function blockedFor() {
1979 $this->getBlockedStatus();
1980 return $this->mBlockreason
;
1984 * If user is blocked, return the ID for the block
1985 * @return int Block ID
1987 public function getBlockId() {
1988 $this->getBlockedStatus();
1989 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
1993 * Check if user is blocked on all wikis.
1994 * Do not use for actual edit permission checks!
1995 * This is intended for quick UI checks.
1997 * @param string $ip IP address, uses current client if none given
1998 * @return bool True if blocked, false otherwise
2000 public function isBlockedGlobally( $ip = '' ) {
2001 return $this->getGlobalBlock( $ip ) instanceof Block
;
2005 * Check if user is blocked on all wikis.
2006 * Do not use for actual edit permission checks!
2007 * This is intended for quick UI checks.
2009 * @param string $ip IP address, uses current client if none given
2010 * @return Block|null Block object if blocked, null otherwise
2011 * @throws FatalError
2012 * @throws MWException
2014 public function getGlobalBlock( $ip = '' ) {
2015 if ( $this->mGlobalBlock
!== null ) {
2016 return $this->mGlobalBlock ?
: null;
2018 // User is already an IP?
2019 if ( IP
::isIPAddress( $this->getName() ) ) {
2020 $ip = $this->getName();
2022 $ip = $this->getRequest()->getIP();
2026 Hooks
::run( 'UserIsBlockedGlobally', [ &$this, $ip, &$blocked, &$block ] );
2028 if ( $blocked && $block === null ) {
2029 // back-compat: UserIsBlockedGlobally didn't have $block param first
2031 $block->setTarget( $ip );
2034 $this->mGlobalBlock
= $blocked ?
$block : false;
2035 return $this->mGlobalBlock ?
: null;
2039 * Check if user account is locked
2041 * @return bool True if locked, false otherwise
2043 public function isLocked() {
2044 if ( $this->mLocked
!== null ) {
2045 return $this->mLocked
;
2048 $authUser = $wgAuth->getUserInstance( $this );
2049 $this->mLocked
= (bool)$authUser->isLocked();
2050 Hooks
::run( 'UserIsLocked', [ $this, &$this->mLocked
] );
2051 return $this->mLocked
;
2055 * Check if user account is hidden
2057 * @return bool True if hidden, false otherwise
2059 public function isHidden() {
2060 if ( $this->mHideName
!== null ) {
2061 return $this->mHideName
;
2063 $this->getBlockedStatus();
2064 if ( !$this->mHideName
) {
2066 $authUser = $wgAuth->getUserInstance( $this );
2067 $this->mHideName
= (bool)$authUser->isHidden();
2068 Hooks
::run( 'UserIsHidden', [ $this, &$this->mHideName
] );
2070 return $this->mHideName
;
2074 * Get the user's ID.
2075 * @return int The user's ID; 0 if the user is anonymous or nonexistent
2077 public function getId() {
2078 if ( $this->mId
=== null && $this->mName
!== null && User
::isIP( $this->mName
) ) {
2079 // Special case, we know the user is anonymous
2081 } elseif ( !$this->isItemLoaded( 'id' ) ) {
2082 // Don't load if this was initialized from an ID
2086 return (int)$this->mId
;
2090 * Set the user and reload all fields according to a given ID
2091 * @param int $v User ID to reload
2093 public function setId( $v ) {
2095 $this->clearInstanceCache( 'id' );
2099 * Get the user name, or the IP of an anonymous user
2100 * @return string User's name or IP address
2102 public function getName() {
2103 if ( $this->isItemLoaded( 'name', 'only' ) ) {
2104 // Special case optimisation
2105 return $this->mName
;
2108 if ( $this->mName
=== false ) {
2110 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
2112 return $this->mName
;
2117 * Set the user name.
2119 * This does not reload fields from the database according to the given
2120 * name. Rather, it is used to create a temporary "nonexistent user" for
2121 * later addition to the database. It can also be used to set the IP
2122 * address for an anonymous user to something other than the current
2125 * @note User::newFromName() has roughly the same function, when the named user
2127 * @param string $str New user name to set
2129 public function setName( $str ) {
2131 $this->mName
= $str;
2135 * Get the user's name escaped by underscores.
2136 * @return string Username escaped by underscores.
2138 public function getTitleKey() {
2139 return str_replace( ' ', '_', $this->getName() );
2143 * Check if the user has new messages.
2144 * @return bool True if the user has new messages
2146 public function getNewtalk() {
2149 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2150 if ( $this->mNewtalk
=== -1 ) {
2151 $this->mNewtalk
= false; # reset talk page status
2153 // Check memcached separately for anons, who have no
2154 // entire User object stored in there.
2155 if ( !$this->mId
) {
2156 global $wgDisableAnonTalk;
2157 if ( $wgDisableAnonTalk ) {
2158 // Anon newtalk disabled by configuration.
2159 $this->mNewtalk
= false;
2161 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
2164 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2168 return (bool)$this->mNewtalk
;
2172 * Return the data needed to construct links for new talk page message
2173 * alerts. If there are new messages, this will return an associative array
2174 * with the following data:
2175 * wiki: The database name of the wiki
2176 * link: Root-relative link to the user's talk page
2177 * rev: The last talk page revision that the user has seen or null. This
2178 * is useful for building diff links.
2179 * If there are no new messages, it returns an empty array.
2180 * @note This function was designed to accomodate multiple talk pages, but
2181 * currently only returns a single link and revision.
2184 public function getNewMessageLinks() {
2186 if ( !Hooks
::run( 'UserRetrieveNewTalks', [ &$this, &$talks ] ) ) {
2188 } elseif ( !$this->getNewtalk() ) {
2191 $utp = $this->getTalkPage();
2192 $dbr = wfGetDB( DB_SLAVE
);
2193 // Get the "last viewed rev" timestamp from the oldest message notification
2194 $timestamp = $dbr->selectField( 'user_newtalk',
2195 'MIN(user_last_timestamp)',
2196 $this->isAnon() ?
[ 'user_ip' => $this->getName() ] : [ 'user_id' => $this->getId() ],
2198 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2199 return [ [ 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ] ];
2203 * Get the revision ID for the last talk page revision viewed by the talk
2205 * @return int|null Revision ID or null
2207 public function getNewMessageRevisionId() {
2208 $newMessageRevisionId = null;
2209 $newMessageLinks = $this->getNewMessageLinks();
2210 if ( $newMessageLinks ) {
2211 // Note: getNewMessageLinks() never returns more than a single link
2212 // and it is always for the same wiki, but we double-check here in
2213 // case that changes some time in the future.
2214 if ( count( $newMessageLinks ) === 1
2215 && $newMessageLinks[0]['wiki'] === wfWikiID()
2216 && $newMessageLinks[0]['rev']
2218 /** @var Revision $newMessageRevision */
2219 $newMessageRevision = $newMessageLinks[0]['rev'];
2220 $newMessageRevisionId = $newMessageRevision->getId();
2223 return $newMessageRevisionId;
2227 * Internal uncached check for new messages
2230 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2231 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2232 * @return bool True if the user has new messages
2234 protected function checkNewtalk( $field, $id ) {
2235 $dbr = wfGetDB( DB_SLAVE
);
2237 $ok = $dbr->selectField( 'user_newtalk', $field, [ $field => $id ], __METHOD__
);
2239 return $ok !== false;
2243 * Add or update the new messages flag
2244 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2245 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2246 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2247 * @return bool True if successful, false otherwise
2249 protected function updateNewtalk( $field, $id, $curRev = null ) {
2250 // Get timestamp of the talk page revision prior to the current one
2251 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2252 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2253 // Mark the user as having new messages since this revision
2254 $dbw = wfGetDB( DB_MASTER
);
2255 $dbw->insert( 'user_newtalk',
2256 [ $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ],
2259 if ( $dbw->affectedRows() ) {
2260 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2263 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2269 * Clear the new messages flag for the given user
2270 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2271 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2272 * @return bool True if successful, false otherwise
2274 protected function deleteNewtalk( $field, $id ) {
2275 $dbw = wfGetDB( DB_MASTER
);
2276 $dbw->delete( 'user_newtalk',
2279 if ( $dbw->affectedRows() ) {
2280 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2283 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2289 * Update the 'You have new messages!' status.
2290 * @param bool $val Whether the user has new messages
2291 * @param Revision $curRev New, as yet unseen revision of the user talk
2292 * page. Ignored if null or !$val.
2294 public function setNewtalk( $val, $curRev = null ) {
2295 if ( wfReadOnly() ) {
2300 $this->mNewtalk
= $val;
2302 if ( $this->isAnon() ) {
2304 $id = $this->getName();
2307 $id = $this->getId();
2311 $changed = $this->updateNewtalk( $field, $id, $curRev );
2313 $changed = $this->deleteNewtalk( $field, $id );
2317 $this->invalidateCache();
2322 * Generate a current or new-future timestamp to be stored in the
2323 * user_touched field when we update things.
2324 * @return string Timestamp in TS_MW format
2326 private function newTouchedTimestamp() {
2327 global $wgClockSkewFudge;
2329 $time = wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2330 if ( $this->mTouched
&& $time <= $this->mTouched
) {
2331 $time = wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $this->mTouched
) +
1 );
2338 * Clear user data from memcached
2340 * Use after applying updates to the database; caller's
2341 * responsibility to update user_touched if appropriate.
2343 * Called implicitly from invalidateCache() and saveSettings().
2345 * @param string $mode Use 'refresh' to clear now; otherwise before DB commit
2347 public function clearSharedCache( $mode = 'changed' ) {
2348 if ( !$this->getId() ) {
2352 $cache = ObjectCache
::getMainWANInstance();
2353 $processCache = self
::getInProcessCache();
2354 $key = $this->getCacheKey( $cache );
2355 if ( $mode === 'refresh' ) {
2356 $cache->delete( $key, 1 );
2357 $processCache->delete( $key );
2359 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle(
2360 function() use ( $cache, $processCache, $key ) {
2361 $cache->delete( $key );
2362 $processCache->delete( $key );
2369 * Immediately touch the user data cache for this account
2371 * Calls touch() and removes account data from memcached
2373 public function invalidateCache() {
2375 $this->clearSharedCache();
2379 * Update the "touched" timestamp for the user
2381 * This is useful on various login/logout events when making sure that
2382 * a browser or proxy that has multiple tenants does not suffer cache
2383 * pollution where the new user sees the old users content. The value
2384 * of getTouched() is checked when determining 304 vs 200 responses.
2385 * Unlike invalidateCache(), this preserves the User object cache and
2386 * avoids database writes.
2390 public function touch() {
2391 $id = $this->getId();
2393 $key = wfMemcKey( 'user-quicktouched', 'id', $id );
2394 ObjectCache
::getMainWANInstance()->touchCheckKey( $key );
2395 $this->mQuickTouched
= null;
2400 * Validate the cache for this account.
2401 * @param string $timestamp A timestamp in TS_MW format
2404 public function validateCache( $timestamp ) {
2405 return ( $timestamp >= $this->getTouched() );
2409 * Get the user touched timestamp
2411 * Use this value only to validate caches via inequalities
2412 * such as in the case of HTTP If-Modified-Since response logic
2414 * @return string TS_MW Timestamp
2416 public function getTouched() {
2420 if ( $this->mQuickTouched
=== null ) {
2421 $key = wfMemcKey( 'user-quicktouched', 'id', $this->mId
);
2422 $cache = ObjectCache
::getMainWANInstance();
2424 $this->mQuickTouched
= wfTimestamp( TS_MW
, $cache->getCheckKeyTime( $key ) );
2427 return max( $this->mTouched
, $this->mQuickTouched
);
2430 return $this->mTouched
;
2434 * Get the user_touched timestamp field (time of last DB updates)
2435 * @return string TS_MW Timestamp
2438 public function getDBTouched() {
2441 return $this->mTouched
;
2445 * @deprecated Removed in 1.27.
2449 public function getPassword() {
2450 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2454 * @deprecated Removed in 1.27.
2458 public function getTemporaryPassword() {
2459 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2463 * Set the password and reset the random token.
2464 * Calls through to authentication plugin if necessary;
2465 * will have no effect if the auth plugin refuses to
2466 * pass the change through or if the legal password
2469 * As a special case, setting the password to null
2470 * wipes it, so the account cannot be logged in until
2471 * a new password is set, for instance via e-mail.
2473 * @deprecated since 1.27. AuthManager is coming.
2474 * @param string $str New password to set
2475 * @throws PasswordError On failure
2478 public function setPassword( $str ) {
2481 if ( $str !== null ) {
2482 if ( !$wgAuth->allowPasswordChange() ) {
2483 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2486 $status = $this->checkPasswordValidity( $str );
2487 if ( !$status->isGood() ) {
2488 throw new PasswordError( $status->getMessage()->text() );
2492 if ( !$wgAuth->setPassword( $this, $str ) ) {
2493 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2496 $this->setOption( 'watchlisttoken', false );
2497 $this->setPasswordInternal( $str );
2498 SessionManager
::singleton()->invalidateSessionsForUser( $this );
2504 * Set the password and reset the random token unconditionally.
2506 * @deprecated since 1.27. AuthManager is coming.
2507 * @param string|null $str New password to set or null to set an invalid
2508 * password hash meaning that the user will not be able to log in
2509 * through the web interface.
2511 public function setInternalPassword( $str ) {
2514 if ( $wgAuth->allowSetLocalPassword() ) {
2515 $this->setOption( 'watchlisttoken', false );
2516 $this->setPasswordInternal( $str );
2517 SessionManager
::singleton()->invalidateSessionsForUser( $this );
2522 * Actually set the password and such
2523 * @since 1.27 cannot set a password for a user not in the database
2524 * @param string|null $str New password to set or null to set an invalid
2525 * password hash meaning that the user will not be able to log in
2526 * through the web interface.
2528 private function setPasswordInternal( $str ) {
2529 $id = self
::idFromName( $this->getName(), self
::READ_LATEST
);
2531 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2534 $passwordFactory = new PasswordFactory();
2535 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
2536 $dbw = wfGetDB( DB_MASTER
);
2540 'user_password' => $passwordFactory->newFromPlaintext( $str )->toString(),
2541 'user_newpassword' => PasswordFactory
::newInvalidPassword()->toString(),
2542 'user_newpass_time' => $dbw->timestampOrNull( null ),
2550 // When the main password is changed, invalidate all bot passwords too
2551 BotPassword
::invalidateAllPasswordsForUser( $this->getName() );
2555 * Get the user's current token.
2556 * @param bool $forceCreation Force the generation of a new token if the
2557 * user doesn't have one (default=true for backwards compatibility).
2558 * @return string|null Token
2560 public function getToken( $forceCreation = true ) {
2561 global $wgAuthenticationTokenVersion;
2564 if ( !$this->mToken
&& $forceCreation ) {
2568 if ( !$this->mToken
) {
2569 // The user doesn't have a token, return null to indicate that.
2571 } elseif ( $this->mToken
=== self
::INVALID_TOKEN
) {
2572 // We return a random value here so existing token checks are very
2574 return MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2575 } elseif ( $wgAuthenticationTokenVersion === null ) {
2576 // $wgAuthenticationTokenVersion not in use, so return the raw secret
2577 return $this->mToken
;
2579 // $wgAuthenticationTokenVersion in use, so hmac it.
2580 $ret = MWCryptHash
::hmac( $wgAuthenticationTokenVersion, $this->mToken
, false );
2582 // The raw hash can be overly long. Shorten it up.
2583 $len = max( 32, self
::TOKEN_LENGTH
);
2584 if ( strlen( $ret ) < $len ) {
2585 // Should never happen, even md5 is 128 bits
2586 throw new \
UnexpectedValueException( 'Hmac returned less than 128 bits' );
2588 return substr( $ret, -$len );
2593 * Set the random token (used for persistent authentication)
2594 * Called from loadDefaults() among other places.
2596 * @param string|bool $token If specified, set the token to this value
2598 public function setToken( $token = false ) {
2600 if ( $this->mToken
=== self
::INVALID_TOKEN
) {
2601 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
2602 ->debug( __METHOD__
. ": Ignoring attempt to set token for system user \"$this\"" );
2603 } elseif ( !$token ) {
2604 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2606 $this->mToken
= $token;
2611 * Set the password for a password reminder or new account email
2613 * @deprecated since 1.27, AuthManager is coming
2614 * @param string $str New password to set or null to set an invalid
2615 * password hash meaning that the user will not be able to use it
2616 * @param bool $throttle If true, reset the throttle timestamp to the present
2618 public function setNewpassword( $str, $throttle = true ) {
2619 $id = $this->getId();
2621 throw new LogicException( 'Cannot set new password for a user that is not in the database.' );
2624 $dbw = wfGetDB( DB_MASTER
);
2626 $passwordFactory = new PasswordFactory();
2627 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
2629 'user_newpassword' => $passwordFactory->newFromPlaintext( $str )->toString(),
2632 if ( $str === null ) {
2633 $update['user_newpass_time'] = null;
2634 } elseif ( $throttle ) {
2635 $update['user_newpass_time'] = $dbw->timestamp();
2638 $dbw->update( 'user', $update, [ 'user_id' => $id ], __METHOD__
);
2642 * Has password reminder email been sent within the last
2643 * $wgPasswordReminderResendTime hours?
2646 public function isPasswordReminderThrottled() {
2647 global $wgPasswordReminderResendTime;
2649 if ( !$wgPasswordReminderResendTime ) {
2655 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
2656 ?
wfGetDB( DB_MASTER
)
2657 : wfGetDB( DB_SLAVE
);
2658 $newpassTime = $db->selectField(
2660 'user_newpass_time',
2661 [ 'user_id' => $this->getId() ],
2665 if ( $newpassTime === null ) {
2668 $expiry = wfTimestamp( TS_UNIX
, $newpassTime ) +
$wgPasswordReminderResendTime * 3600;
2669 return time() < $expiry;
2673 * Get the user's e-mail address
2674 * @return string User's email address
2676 public function getEmail() {
2678 Hooks
::run( 'UserGetEmail', [ $this, &$this->mEmail
] );
2679 return $this->mEmail
;
2683 * Get the timestamp of the user's e-mail authentication
2684 * @return string TS_MW timestamp
2686 public function getEmailAuthenticationTimestamp() {
2688 Hooks
::run( 'UserGetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
2689 return $this->mEmailAuthenticated
;
2693 * Set the user's e-mail address
2694 * @param string $str New e-mail address
2696 public function setEmail( $str ) {
2698 if ( $str == $this->mEmail
) {
2701 $this->invalidateEmail();
2702 $this->mEmail
= $str;
2703 Hooks
::run( 'UserSetEmail', [ $this, &$this->mEmail
] );
2707 * Set the user's e-mail address and a confirmation mail if needed.
2710 * @param string $str New e-mail address
2713 public function setEmailWithConfirmation( $str ) {
2714 global $wgEnableEmail, $wgEmailAuthentication;
2716 if ( !$wgEnableEmail ) {
2717 return Status
::newFatal( 'emaildisabled' );
2720 $oldaddr = $this->getEmail();
2721 if ( $str === $oldaddr ) {
2722 return Status
::newGood( true );
2725 $type = $oldaddr != '' ?
'changed' : 'set';
2726 $notificationResult = null;
2728 if ( $wgEmailAuthentication ) {
2729 // Send the user an email notifying the user of the change in registered
2730 // email address on their previous email address
2731 if ( $type == 'changed' ) {
2732 $change = $str != '' ?
'changed' : 'removed';
2733 $notificationResult = $this->sendMail(
2734 wfMessage( 'notificationemail_subject_' . $change )->text(),
2735 wfMessage( 'notificationemail_body_' . $change,
2736 $this->getRequest()->getIP(),
2743 $this->setEmail( $str );
2745 if ( $str !== '' && $wgEmailAuthentication ) {
2746 // Send a confirmation request to the new address if needed
2747 $result = $this->sendConfirmationMail( $type );
2749 if ( $notificationResult !== null ) {
2750 $result->merge( $notificationResult );
2753 if ( $result->isGood() ) {
2754 // Say to the caller that a confirmation and notification mail has been sent
2755 $result->value
= 'eauth';
2758 $result = Status
::newGood( true );
2765 * Get the user's real name
2766 * @return string User's real name
2768 public function getRealName() {
2769 if ( !$this->isItemLoaded( 'realname' ) ) {
2773 return $this->mRealName
;
2777 * Set the user's real name
2778 * @param string $str New real name
2780 public function setRealName( $str ) {
2782 $this->mRealName
= $str;
2786 * Get the user's current setting for a given option.
2788 * @param string $oname The option to check
2789 * @param string $defaultOverride A default value returned if the option does not exist
2790 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2791 * @return string User's current value for the option
2792 * @see getBoolOption()
2793 * @see getIntOption()
2795 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2796 global $wgHiddenPrefs;
2797 $this->loadOptions();
2799 # We want 'disabled' preferences to always behave as the default value for
2800 # users, even if they have set the option explicitly in their settings (ie they
2801 # set it, and then it was disabled removing their ability to change it). But
2802 # we don't want to erase the preferences in the database in case the preference
2803 # is re-enabled again. So don't touch $mOptions, just override the returned value
2804 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2805 return self
::getDefaultOption( $oname );
2808 if ( array_key_exists( $oname, $this->mOptions
) ) {
2809 return $this->mOptions
[$oname];
2811 return $defaultOverride;
2816 * Get all user's options
2818 * @param int $flags Bitwise combination of:
2819 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2820 * to the default value. (Since 1.25)
2823 public function getOptions( $flags = 0 ) {
2824 global $wgHiddenPrefs;
2825 $this->loadOptions();
2826 $options = $this->mOptions
;
2828 # We want 'disabled' preferences to always behave as the default value for
2829 # users, even if they have set the option explicitly in their settings (ie they
2830 # set it, and then it was disabled removing their ability to change it). But
2831 # we don't want to erase the preferences in the database in case the preference
2832 # is re-enabled again. So don't touch $mOptions, just override the returned value
2833 foreach ( $wgHiddenPrefs as $pref ) {
2834 $default = self
::getDefaultOption( $pref );
2835 if ( $default !== null ) {
2836 $options[$pref] = $default;
2840 if ( $flags & self
::GETOPTIONS_EXCLUDE_DEFAULTS
) {
2841 $options = array_diff_assoc( $options, self
::getDefaultOptions() );
2848 * Get the user's current setting for a given option, as a boolean value.
2850 * @param string $oname The option to check
2851 * @return bool User's current value for the option
2854 public function getBoolOption( $oname ) {
2855 return (bool)$this->getOption( $oname );
2859 * Get the user's current setting for a given option, as an integer value.
2861 * @param string $oname The option to check
2862 * @param int $defaultOverride A default value returned if the option does not exist
2863 * @return int User's current value for the option
2866 public function getIntOption( $oname, $defaultOverride = 0 ) {
2867 $val = $this->getOption( $oname );
2869 $val = $defaultOverride;
2871 return intval( $val );
2875 * Set the given option for a user.
2877 * You need to call saveSettings() to actually write to the database.
2879 * @param string $oname The option to set
2880 * @param mixed $val New value to set
2882 public function setOption( $oname, $val ) {
2883 $this->loadOptions();
2885 // Explicitly NULL values should refer to defaults
2886 if ( is_null( $val ) ) {
2887 $val = self
::getDefaultOption( $oname );
2890 $this->mOptions
[$oname] = $val;
2894 * Get a token stored in the preferences (like the watchlist one),
2895 * resetting it if it's empty (and saving changes).
2897 * @param string $oname The option name to retrieve the token from
2898 * @return string|bool User's current value for the option, or false if this option is disabled.
2899 * @see resetTokenFromOption()
2901 * @deprecated 1.26 Applications should use the OAuth extension
2903 public function getTokenFromOption( $oname ) {
2904 global $wgHiddenPrefs;
2906 $id = $this->getId();
2907 if ( !$id ||
in_array( $oname, $wgHiddenPrefs ) ) {
2911 $token = $this->getOption( $oname );
2913 // Default to a value based on the user token to avoid space
2914 // wasted on storing tokens for all users. When this option
2915 // is set manually by the user, only then is it stored.
2916 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
2923 * Reset a token stored in the preferences (like the watchlist one).
2924 * *Does not* save user's preferences (similarly to setOption()).
2926 * @param string $oname The option name to reset the token in
2927 * @return string|bool New token value, or false if this option is disabled.
2928 * @see getTokenFromOption()
2931 public function resetTokenFromOption( $oname ) {
2932 global $wgHiddenPrefs;
2933 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2937 $token = MWCryptRand
::generateHex( 40 );
2938 $this->setOption( $oname, $token );
2943 * Return a list of the types of user options currently returned by
2944 * User::getOptionKinds().
2946 * Currently, the option kinds are:
2947 * - 'registered' - preferences which are registered in core MediaWiki or
2948 * by extensions using the UserGetDefaultOptions hook.
2949 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2950 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2951 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2952 * be used by user scripts.
2953 * - 'special' - "preferences" that are not accessible via User::getOptions
2954 * or User::setOptions.
2955 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2956 * These are usually legacy options, removed in newer versions.
2958 * The API (and possibly others) use this function to determine the possible
2959 * option types for validation purposes, so make sure to update this when a
2960 * new option kind is added.
2962 * @see User::getOptionKinds
2963 * @return array Option kinds
2965 public static function listOptionKinds() {
2968 'registered-multiselect',
2969 'registered-checkmatrix',
2977 * Return an associative array mapping preferences keys to the kind of a preference they're
2978 * used for. Different kinds are handled differently when setting or reading preferences.
2980 * See User::listOptionKinds for the list of valid option types that can be provided.
2982 * @see User::listOptionKinds
2983 * @param IContextSource $context
2984 * @param array $options Assoc. array with options keys to check as keys.
2985 * Defaults to $this->mOptions.
2986 * @return array The key => kind mapping data
2988 public function getOptionKinds( IContextSource
$context, $options = null ) {
2989 $this->loadOptions();
2990 if ( $options === null ) {
2991 $options = $this->mOptions
;
2994 $prefs = Preferences
::getPreferences( $this, $context );
2997 // Pull out the "special" options, so they don't get converted as
2998 // multiselect or checkmatrix.
2999 $specialOptions = array_fill_keys( Preferences
::getSaveBlacklist(), true );
3000 foreach ( $specialOptions as $name => $value ) {
3001 unset( $prefs[$name] );
3004 // Multiselect and checkmatrix options are stored in the database with
3005 // one key per option, each having a boolean value. Extract those keys.
3006 $multiselectOptions = [];
3007 foreach ( $prefs as $name => $info ) {
3008 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
3009 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
3010 $opts = HTMLFormField
::flattenOptions( $info['options'] );
3011 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
3013 foreach ( $opts as $value ) {
3014 $multiselectOptions["$prefix$value"] = true;
3017 unset( $prefs[$name] );
3020 $checkmatrixOptions = [];
3021 foreach ( $prefs as $name => $info ) {
3022 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
3023 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
3024 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
3025 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
3026 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
3028 foreach ( $columns as $column ) {
3029 foreach ( $rows as $row ) {
3030 $checkmatrixOptions["$prefix$column-$row"] = true;
3034 unset( $prefs[$name] );
3038 // $value is ignored
3039 foreach ( $options as $key => $value ) {
3040 if ( isset( $prefs[$key] ) ) {
3041 $mapping[$key] = 'registered';
3042 } elseif ( isset( $multiselectOptions[$key] ) ) {
3043 $mapping[$key] = 'registered-multiselect';
3044 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
3045 $mapping[$key] = 'registered-checkmatrix';
3046 } elseif ( isset( $specialOptions[$key] ) ) {
3047 $mapping[$key] = 'special';
3048 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
3049 $mapping[$key] = 'userjs';
3051 $mapping[$key] = 'unused';
3059 * Reset certain (or all) options to the site defaults
3061 * The optional parameter determines which kinds of preferences will be reset.
3062 * Supported values are everything that can be reported by getOptionKinds()
3063 * and 'all', which forces a reset of *all* preferences and overrides everything else.
3065 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
3066 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
3067 * for backwards-compatibility.
3068 * @param IContextSource|null $context Context source used when $resetKinds
3069 * does not contain 'all', passed to getOptionKinds().
3070 * Defaults to RequestContext::getMain() when null.
3072 public function resetOptions(
3073 $resetKinds = [ 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ],
3074 IContextSource
$context = null
3077 $defaultOptions = self
::getDefaultOptions();
3079 if ( !is_array( $resetKinds ) ) {
3080 $resetKinds = [ $resetKinds ];
3083 if ( in_array( 'all', $resetKinds ) ) {
3084 $newOptions = $defaultOptions;
3086 if ( $context === null ) {
3087 $context = RequestContext
::getMain();
3090 $optionKinds = $this->getOptionKinds( $context );
3091 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
3094 // Use default values for the options that should be deleted, and
3095 // copy old values for the ones that shouldn't.
3096 foreach ( $this->mOptions
as $key => $value ) {
3097 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
3098 if ( array_key_exists( $key, $defaultOptions ) ) {
3099 $newOptions[$key] = $defaultOptions[$key];
3102 $newOptions[$key] = $value;
3107 Hooks
::run( 'UserResetAllOptions', [ $this, &$newOptions, $this->mOptions
, $resetKinds ] );
3109 $this->mOptions
= $newOptions;
3110 $this->mOptionsLoaded
= true;
3114 * Get the user's preferred date format.
3115 * @return string User's preferred date format
3117 public function getDatePreference() {
3118 // Important migration for old data rows
3119 if ( is_null( $this->mDatePreference
) ) {
3121 $value = $this->getOption( 'date' );
3122 $map = $wgLang->getDatePreferenceMigrationMap();
3123 if ( isset( $map[$value] ) ) {
3124 $value = $map[$value];
3126 $this->mDatePreference
= $value;
3128 return $this->mDatePreference
;
3132 * Determine based on the wiki configuration and the user's options,
3133 * whether this user must be over HTTPS no matter what.
3137 public function requiresHTTPS() {
3138 global $wgSecureLogin;
3139 if ( !$wgSecureLogin ) {
3142 $https = $this->getBoolOption( 'prefershttps' );
3143 Hooks
::run( 'UserRequiresHTTPS', [ $this, &$https ] );
3145 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
3152 * Get the user preferred stub threshold
3156 public function getStubThreshold() {
3157 global $wgMaxArticleSize; # Maximum article size, in Kb
3158 $threshold = $this->getIntOption( 'stubthreshold' );
3159 if ( $threshold > $wgMaxArticleSize * 1024 ) {
3160 // If they have set an impossible value, disable the preference
3161 // so we can use the parser cache again.
3168 * Get the permissions this user has.
3169 * @return array Array of String permission names
3171 public function getRights() {
3172 if ( is_null( $this->mRights
) ) {
3173 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
3175 // Deny any rights denied by the user's session, unless this
3176 // endpoint has no sessions.
3177 if ( !defined( 'MW_NO_SESSION' ) ) {
3178 $allowedRights = $this->getRequest()->getSession()->getAllowedUserRights();
3179 if ( $allowedRights !== null ) {
3180 $this->mRights
= array_intersect( $this->mRights
, $allowedRights );
3184 Hooks
::run( 'UserGetRights', [ $this, &$this->mRights
] );
3185 // Force reindexation of rights when a hook has unset one of them
3186 $this->mRights
= array_values( array_unique( $this->mRights
) );
3188 return $this->mRights
;
3192 * Get the list of explicit group memberships this user has.
3193 * The implicit * and user groups are not included.
3194 * @return array Array of String internal group names
3196 public function getGroups() {
3198 $this->loadGroups();
3199 return $this->mGroups
;
3203 * Get the list of implicit group memberships this user has.
3204 * This includes all explicit groups, plus 'user' if logged in,
3205 * '*' for all accounts, and autopromoted groups
3206 * @param bool $recache Whether to avoid the cache
3207 * @return array Array of String internal group names
3209 public function getEffectiveGroups( $recache = false ) {
3210 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
3211 $this->mEffectiveGroups
= array_unique( array_merge(
3212 $this->getGroups(), // explicit groups
3213 $this->getAutomaticGroups( $recache ) // implicit groups
3215 // Hook for additional groups
3216 Hooks
::run( 'UserEffectiveGroups', [ &$this, &$this->mEffectiveGroups
] );
3217 // Force reindexation of groups when a hook has unset one of them
3218 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
3220 return $this->mEffectiveGroups
;
3224 * Get the list of implicit group memberships this user has.
3225 * This includes 'user' if logged in, '*' for all accounts,
3226 * and autopromoted groups
3227 * @param bool $recache Whether to avoid the cache
3228 * @return array Array of String internal group names
3230 public function getAutomaticGroups( $recache = false ) {
3231 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
3232 $this->mImplicitGroups
= [ '*' ];
3233 if ( $this->getId() ) {
3234 $this->mImplicitGroups
[] = 'user';
3236 $this->mImplicitGroups
= array_unique( array_merge(
3237 $this->mImplicitGroups
,
3238 Autopromote
::getAutopromoteGroups( $this )
3242 // Assure data consistency with rights/groups,
3243 // as getEffectiveGroups() depends on this function
3244 $this->mEffectiveGroups
= null;
3247 return $this->mImplicitGroups
;
3251 * Returns the groups the user has belonged to.
3253 * The user may still belong to the returned groups. Compare with getGroups().
3255 * The function will not return groups the user had belonged to before MW 1.17
3257 * @return array Names of the groups the user has belonged to.
3259 public function getFormerGroups() {
3262 if ( is_null( $this->mFormerGroups
) ) {
3263 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3264 ?
wfGetDB( DB_MASTER
)
3265 : wfGetDB( DB_SLAVE
);
3266 $res = $db->select( 'user_former_groups',
3268 [ 'ufg_user' => $this->mId
],
3270 $this->mFormerGroups
= [];
3271 foreach ( $res as $row ) {
3272 $this->mFormerGroups
[] = $row->ufg_group
;
3276 return $this->mFormerGroups
;
3280 * Get the user's edit count.
3281 * @return int|null Null for anonymous users
3283 public function getEditCount() {
3284 if ( !$this->getId() ) {
3288 if ( $this->mEditCount
=== null ) {
3289 /* Populate the count, if it has not been populated yet */
3290 $dbr = wfGetDB( DB_SLAVE
);
3291 // check if the user_editcount field has been initialized
3292 $count = $dbr->selectField(
3293 'user', 'user_editcount',
3294 [ 'user_id' => $this->mId
],
3298 if ( $count === null ) {
3299 // it has not been initialized. do so.
3300 $count = $this->initEditCount();
3302 $this->mEditCount
= $count;
3304 return (int)$this->mEditCount
;
3308 * Add the user to the given group.
3309 * This takes immediate effect.
3310 * @param string $group Name of the group to add
3313 public function addGroup( $group ) {
3316 if ( !Hooks
::run( 'UserAddGroup', [ $this, &$group ] ) ) {
3320 $dbw = wfGetDB( DB_MASTER
);
3321 if ( $this->getId() ) {
3322 $dbw->insert( 'user_groups',
3324 'ug_user' => $this->getId(),
3325 'ug_group' => $group,
3331 $this->loadGroups();
3332 $this->mGroups
[] = $group;
3333 // In case loadGroups was not called before, we now have the right twice.
3334 // Get rid of the duplicate.
3335 $this->mGroups
= array_unique( $this->mGroups
);
3337 // Refresh the groups caches, and clear the rights cache so it will be
3338 // refreshed on the next call to $this->getRights().
3339 $this->getEffectiveGroups( true );
3340 $this->mRights
= null;
3342 $this->invalidateCache();
3348 * Remove the user from the given group.
3349 * This takes immediate effect.
3350 * @param string $group Name of the group to remove
3353 public function removeGroup( $group ) {
3355 if ( !Hooks
::run( 'UserRemoveGroup', [ $this, &$group ] ) ) {
3359 $dbw = wfGetDB( DB_MASTER
);
3360 $dbw->delete( 'user_groups',
3362 'ug_user' => $this->getId(),
3363 'ug_group' => $group,
3366 // Remember that the user was in this group
3367 $dbw->insert( 'user_former_groups',
3369 'ufg_user' => $this->getId(),
3370 'ufg_group' => $group,
3376 $this->loadGroups();
3377 $this->mGroups
= array_diff( $this->mGroups
, [ $group ] );
3379 // Refresh the groups caches, and clear the rights cache so it will be
3380 // refreshed on the next call to $this->getRights().
3381 $this->getEffectiveGroups( true );
3382 $this->mRights
= null;
3384 $this->invalidateCache();
3390 * Get whether the user is logged in
3393 public function isLoggedIn() {
3394 return $this->getId() != 0;
3398 * Get whether the user is anonymous
3401 public function isAnon() {
3402 return !$this->isLoggedIn();
3406 * @return bool Whether this user is flagged as being a bot role account
3409 public function isBot() {
3410 if ( in_array( 'bot', $this->getGroups() ) && $this->isAllowed( 'bot' ) ) {
3415 Hooks
::run( "UserIsBot", [ $this, &$isBot ] );
3421 * Check if user is allowed to access a feature / make an action
3423 * @param string ... Permissions to test
3424 * @return bool True if user is allowed to perform *any* of the given actions
3426 public function isAllowedAny() {
3427 $permissions = func_get_args();
3428 foreach ( $permissions as $permission ) {
3429 if ( $this->isAllowed( $permission ) ) {
3438 * @param string ... Permissions to test
3439 * @return bool True if the user is allowed to perform *all* of the given actions
3441 public function isAllowedAll() {
3442 $permissions = func_get_args();
3443 foreach ( $permissions as $permission ) {
3444 if ( !$this->isAllowed( $permission ) ) {
3452 * Internal mechanics of testing a permission
3453 * @param string $action
3456 public function isAllowed( $action = '' ) {
3457 if ( $action === '' ) {
3458 return true; // In the spirit of DWIM
3460 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3461 // by misconfiguration: 0 == 'foo'
3462 return in_array( $action, $this->getRights(), true );
3466 * Check whether to enable recent changes patrol features for this user
3467 * @return bool True or false
3469 public function useRCPatrol() {
3470 global $wgUseRCPatrol;
3471 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3475 * Check whether to enable new pages patrol features for this user
3476 * @return bool True or false
3478 public function useNPPatrol() {
3479 global $wgUseRCPatrol, $wgUseNPPatrol;
3481 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3482 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3487 * Check whether to enable new files patrol features for this user
3488 * @return bool True or false
3490 public function useFilePatrol() {
3491 global $wgUseRCPatrol, $wgUseFilePatrol;
3493 ( $wgUseRCPatrol ||
$wgUseFilePatrol )
3494 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3499 * Get the WebRequest object to use with this object
3501 * @return WebRequest
3503 public function getRequest() {
3504 if ( $this->mRequest
) {
3505 return $this->mRequest
;
3513 * Check the watched status of an article.
3514 * @since 1.22 $checkRights parameter added
3515 * @param Title $title Title of the article to look at
3516 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3517 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3520 public function isWatched( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3521 if ( $title->isWatchable() && ( !$checkRights ||
$this->isAllowed( 'viewmywatchlist' ) ) ) {
3522 return MediaWikiServices
::getInstance()->getWatchedItemStore()->isWatched( $this, $title );
3529 * @since 1.22 $checkRights parameter added
3530 * @param Title $title Title of the article to look at
3531 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3532 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3534 public function addWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3535 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3536 MediaWikiServices
::getInstance()->getWatchedItemStore()->addWatchBatchForUser(
3538 [ $title->getSubjectPage(), $title->getTalkPage() ]
3541 $this->invalidateCache();
3545 * Stop watching an article.
3546 * @since 1.22 $checkRights parameter added
3547 * @param Title $title Title of the article to look at
3548 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3549 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3551 public function removeWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3552 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3553 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
3554 $store->removeWatch( $this, $title->getSubjectPage() );
3555 $store->removeWatch( $this, $title->getTalkPage() );
3557 $this->invalidateCache();
3561 * Clear the user's notification timestamp for the given title.
3562 * If e-notif e-mails are on, they will receive notification mails on
3563 * the next change of the page if it's watched etc.
3564 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3565 * @param Title $title Title of the article to look at
3566 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3568 public function clearNotification( &$title, $oldid = 0 ) {
3569 global $wgUseEnotif, $wgShowUpdatedMarker;
3571 // Do nothing if the database is locked to writes
3572 if ( wfReadOnly() ) {
3576 // Do nothing if not allowed to edit the watchlist
3577 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3581 // If we're working on user's talk page, we should update the talk page message indicator
3582 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3583 if ( !Hooks
::run( 'UserClearNewTalkNotification', [ &$this, $oldid ] ) ) {
3587 // Try to update the DB post-send and only if needed...
3588 DeferredUpdates
::addCallableUpdate( function() use ( $title, $oldid ) {
3589 if ( !$this->getNewtalk() ) {
3590 return; // no notifications to clear
3593 // Delete the last notifications (they stack up)
3594 $this->setNewtalk( false );
3596 // If there is a new, unseen, revision, use its timestamp
3598 ?
$title->getNextRevisionID( $oldid, Title
::GAID_FOR_UPDATE
)
3601 $this->setNewtalk( true, Revision
::newFromId( $nextid ) );
3606 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3610 if ( $this->isAnon() ) {
3611 // Nothing else to do...
3615 // Only update the timestamp if the page is being watched.
3616 // The query to find out if it is watched is cached both in memcached and per-invocation,
3617 // and when it does have to be executed, it can be on a slave
3618 // If this is the user's newtalk page, we always update the timestamp
3620 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3624 MediaWikiServices
::getInstance()->getWatchedItemStore()
3625 ->resetNotificationTimestamp( $this, $title, $force, $oldid );
3629 * Resets all of the given user's page-change notification timestamps.
3630 * If e-notif e-mails are on, they will receive notification mails on
3631 * the next change of any watched page.
3632 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3634 public function clearAllNotifications() {
3635 if ( wfReadOnly() ) {
3639 // Do nothing if not allowed to edit the watchlist
3640 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3644 global $wgUseEnotif, $wgShowUpdatedMarker;
3645 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3646 $this->setNewtalk( false );
3649 $id = $this->getId();
3651 $dbw = wfGetDB( DB_MASTER
);
3652 $dbw->update( 'watchlist',
3653 [ /* SET */ 'wl_notificationtimestamp' => null ],
3654 [ /* WHERE */ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ],
3657 // We also need to clear here the "you have new message" notification for the own user_talk page;
3658 // it's cleared one page view later in WikiPage::doViewUpdates().
3663 * Set a cookie on the user's client. Wrapper for
3664 * WebResponse::setCookie
3665 * @deprecated since 1.27
3666 * @param string $name Name of the cookie to set
3667 * @param string $value Value to set
3668 * @param int $exp Expiration time, as a UNIX time value;
3669 * if 0 or not specified, use the default $wgCookieExpiration
3670 * @param bool $secure
3671 * true: Force setting the secure attribute when setting the cookie
3672 * false: Force NOT setting the secure attribute when setting the cookie
3673 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3674 * @param array $params Array of options sent passed to WebResponse::setcookie()
3675 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3678 protected function setCookie(
3679 $name, $value, $exp = 0, $secure = null, $params = [], $request = null
3681 wfDeprecated( __METHOD__
, '1.27' );
3682 if ( $request === null ) {
3683 $request = $this->getRequest();
3685 $params['secure'] = $secure;
3686 $request->response()->setCookie( $name, $value, $exp, $params );
3690 * Clear a cookie on the user's client
3691 * @deprecated since 1.27
3692 * @param string $name Name of the cookie to clear
3693 * @param bool $secure
3694 * true: Force setting the secure attribute when setting the cookie
3695 * false: Force NOT setting the secure attribute when setting the cookie
3696 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3697 * @param array $params Array of options sent passed to WebResponse::setcookie()
3699 protected function clearCookie( $name, $secure = null, $params = [] ) {
3700 wfDeprecated( __METHOD__
, '1.27' );
3701 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3705 * Set an extended login cookie on the user's client. The expiry of the cookie
3706 * is controlled by the $wgExtendedLoginCookieExpiration configuration
3709 * @see User::setCookie
3711 * @deprecated since 1.27
3712 * @param string $name Name of the cookie to set
3713 * @param string $value Value to set
3714 * @param bool $secure
3715 * true: Force setting the secure attribute when setting the cookie
3716 * false: Force NOT setting the secure attribute when setting the cookie
3717 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3719 protected function setExtendedLoginCookie( $name, $value, $secure ) {
3720 global $wgExtendedLoginCookieExpiration, $wgCookieExpiration;
3722 wfDeprecated( __METHOD__
, '1.27' );
3725 $exp +
= $wgExtendedLoginCookieExpiration !== null
3726 ?
$wgExtendedLoginCookieExpiration
3727 : $wgCookieExpiration;
3729 $this->setCookie( $name, $value, $exp, $secure );
3733 * Persist this user's session (e.g. set cookies)
3735 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3737 * @param bool $secure Whether to force secure/insecure cookies or use default
3738 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3740 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3742 if ( 0 == $this->mId
) {
3746 $session = $this->getRequest()->getSession();
3747 if ( $request && $session->getRequest() !== $request ) {
3748 $session = $session->sessionWithRequest( $request );
3750 $delay = $session->delaySave();
3752 if ( !$session->getUser()->equals( $this ) ) {
3753 if ( !$session->canSetUser() ) {
3754 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3755 ->warning( __METHOD__
.
3756 ": Cannot save user \"$this\" to a user \"{$session->getUser()}\"'s immutable session"
3760 $session->setUser( $this );
3763 $session->setRememberUser( $rememberMe );
3764 if ( $secure !== null ) {
3765 $session->setForceHTTPS( $secure );
3768 $session->persist();
3770 ScopedCallback
::consume( $delay );
3774 * Log this user out.
3776 public function logout() {
3777 if ( Hooks
::run( 'UserLogout', [ &$this ] ) ) {
3783 * Clear the user's session, and reset the instance cache.
3786 public function doLogout() {
3787 $session = $this->getRequest()->getSession();
3788 if ( !$session->canSetUser() ) {
3789 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3790 ->warning( __METHOD__
. ": Cannot log out of an immutable session" );
3791 } elseif ( !$session->getUser()->equals( $this ) ) {
3792 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3793 ->warning( __METHOD__
.
3794 ": Cannot log user \"$this\" out of a user \"{$session->getUser()}\"'s session"
3796 // But we still may as well make this user object anon
3797 $this->clearInstanceCache( 'defaults' );
3799 $this->clearInstanceCache( 'defaults' );
3800 $delay = $session->delaySave();
3801 $session->unpersist(); // Clear cookies (T127436)
3802 $session->setLoggedOutTimestamp( time() );
3803 $session->setUser( new User
);
3804 $session->set( 'wsUserID', 0 ); // Other code expects this
3805 ScopedCallback
::consume( $delay );
3810 * Save this user's settings into the database.
3811 * @todo Only rarely do all these fields need to be set!
3813 public function saveSettings() {
3814 if ( wfReadOnly() ) {
3815 // @TODO: caller should deal with this instead!
3816 // This should really just be an exception.
3817 MWExceptionHandler
::logException( new DBExpectedError(
3819 "Could not update user with ID '{$this->mId}'; DB is read-only."
3825 if ( 0 == $this->mId
) {
3829 // Get a new user_touched that is higher than the old one.
3830 // This will be used for a CAS check as a last-resort safety
3831 // check against race conditions and slave lag.
3832 $oldTouched = $this->mTouched
;
3833 $newTouched = $this->newTouchedTimestamp();
3835 $dbw = wfGetDB( DB_MASTER
);
3836 $dbw->update( 'user',
3838 'user_name' => $this->mName
,
3839 'user_real_name' => $this->mRealName
,
3840 'user_email' => $this->mEmail
,
3841 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3842 'user_touched' => $dbw->timestamp( $newTouched ),
3843 'user_token' => strval( $this->mToken
),
3844 'user_email_token' => $this->mEmailToken
,
3845 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
3847 'user_id' => $this->mId
,
3848 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
3852 if ( !$dbw->affectedRows() ) {
3853 // Maybe the problem was a missed cache update; clear it to be safe
3854 $this->clearSharedCache( 'refresh' );
3855 // User was changed in the meantime or loaded with stale data
3856 $from = ( $this->queryFlagsUsed
& self
::READ_LATEST
) ?
'master' : 'slave';
3857 throw new MWException(
3858 "CAS update failed on user_touched for user ID '{$this->mId}' (read from $from);" .
3859 " the version of the user to be saved is older than the current version."
3863 $this->mTouched
= $newTouched;
3864 $this->saveOptions();
3866 Hooks
::run( 'UserSaveSettings', [ $this ] );
3867 $this->clearSharedCache();
3868 $this->getUserPage()->invalidateCache();
3872 * If only this user's username is known, and it exists, return the user ID.
3874 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
3877 public function idForName( $flags = 0 ) {
3878 $s = trim( $this->getName() );
3883 $db = ( ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
)
3884 ?
wfGetDB( DB_MASTER
)
3885 : wfGetDB( DB_SLAVE
);
3887 $options = ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
)
3888 ?
[ 'LOCK IN SHARE MODE' ]
3891 $id = $db->selectField( 'user',
3892 'user_id', [ 'user_name' => $s ], __METHOD__
, $options );
3898 * Add a user to the database, return the user object
3900 * @param string $name Username to add
3901 * @param array $params Array of Strings Non-default parameters to save to
3902 * the database as user_* fields:
3903 * - email: The user's email address.
3904 * - email_authenticated: The email authentication timestamp.
3905 * - real_name: The user's real name.
3906 * - options: An associative array of non-default options.
3907 * - token: Random authentication token. Do not set.
3908 * - registration: Registration timestamp. Do not set.
3910 * @return User|null User object, or null if the username already exists.
3912 public static function createNew( $name, $params = [] ) {
3913 foreach ( [ 'password', 'newpassword', 'newpass_time', 'password_expires' ] as $field ) {
3914 if ( isset( $params[$field] ) ) {
3915 wfDeprecated( __METHOD__
. " with param '$field'", '1.27' );
3916 unset( $params[$field] );
3922 $user->setToken(); // init token
3923 if ( isset( $params['options'] ) ) {
3924 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
3925 unset( $params['options'] );
3927 $dbw = wfGetDB( DB_MASTER
);
3928 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3930 $noPass = PasswordFactory
::newInvalidPassword()->toString();
3933 'user_id' => $seqVal,
3934 'user_name' => $name,
3935 'user_password' => $noPass,
3936 'user_newpassword' => $noPass,
3937 'user_email' => $user->mEmail
,
3938 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
3939 'user_real_name' => $user->mRealName
,
3940 'user_token' => strval( $user->mToken
),
3941 'user_registration' => $dbw->timestamp( $user->mRegistration
),
3942 'user_editcount' => 0,
3943 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
3945 foreach ( $params as $name => $value ) {
3946 $fields["user_$name"] = $value;
3948 $dbw->insert( 'user', $fields, __METHOD__
, [ 'IGNORE' ] );
3949 if ( $dbw->affectedRows() ) {
3950 $newUser = User
::newFromId( $dbw->insertId() );
3958 * Add this existing user object to the database. If the user already
3959 * exists, a fatal status object is returned, and the user object is
3960 * initialised with the data from the database.
3962 * Previously, this function generated a DB error due to a key conflict
3963 * if the user already existed. Many extension callers use this function
3964 * in code along the lines of:
3966 * $user = User::newFromName( $name );
3967 * if ( !$user->isLoggedIn() ) {
3968 * $user->addToDatabase();
3970 * // do something with $user...
3972 * However, this was vulnerable to a race condition (bug 16020). By
3973 * initialising the user object if the user exists, we aim to support this
3974 * calling sequence as far as possible.
3976 * Note that if the user exists, this function will acquire a write lock,
3977 * so it is still advisable to make the call conditional on isLoggedIn(),
3978 * and to commit the transaction after calling.
3980 * @throws MWException
3983 public function addToDatabase() {
3985 if ( !$this->mToken
) {
3986 $this->setToken(); // init token
3989 $this->mTouched
= $this->newTouchedTimestamp();
3991 $noPass = PasswordFactory
::newInvalidPassword()->toString();
3993 $dbw = wfGetDB( DB_MASTER
);
3994 $inWrite = $dbw->writesOrCallbacksPending();
3995 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3996 $dbw->insert( 'user',
3998 'user_id' => $seqVal,
3999 'user_name' => $this->mName
,
4000 'user_password' => $noPass,
4001 'user_newpassword' => $noPass,
4002 'user_email' => $this->mEmail
,
4003 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
4004 'user_real_name' => $this->mRealName
,
4005 'user_token' => strval( $this->mToken
),
4006 'user_registration' => $dbw->timestamp( $this->mRegistration
),
4007 'user_editcount' => 0,
4008 'user_touched' => $dbw->timestamp( $this->mTouched
),
4012 if ( !$dbw->affectedRows() ) {
4013 // The queries below cannot happen in the same REPEATABLE-READ snapshot.
4014 // Handle this by COMMIT, if possible, or by LOCK IN SHARE MODE otherwise.
4016 // Can't commit due to pending writes that may need atomicity.
4017 // This may cause some lock contention unlike the case below.
4018 $options = [ 'LOCK IN SHARE MODE' ];
4019 $flags = self
::READ_LOCKING
;
4021 // Often, this case happens early in views before any writes when
4022 // using CentralAuth. It's should be OK to commit and break the snapshot.
4023 $dbw->commit( __METHOD__
, 'flush' );
4025 $flags = self
::READ_LATEST
;
4027 $this->mId
= $dbw->selectField( 'user', 'user_id',
4028 [ 'user_name' => $this->mName
], __METHOD__
, $options );
4031 if ( $this->loadFromDatabase( $flags ) ) {
4036 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
4037 "to insert user '{$this->mName}' row, but it was not present in select!" );
4039 return Status
::newFatal( 'userexists' );
4041 $this->mId
= $dbw->insertId();
4042 self
::$idCacheByName[$this->mName
] = $this->mId
;
4044 // Clear instance cache other than user table data, which is already accurate
4045 $this->clearInstanceCache();
4047 $this->saveOptions();
4048 return Status
::newGood();
4052 * If this user is logged-in and blocked,
4053 * block any IP address they've successfully logged in from.
4054 * @return bool A block was spread
4056 public function spreadAnyEditBlock() {
4057 if ( $this->isLoggedIn() && $this->isBlocked() ) {
4058 return $this->spreadBlock();
4065 * If this (non-anonymous) user is blocked,
4066 * block the IP address they've successfully logged in from.
4067 * @return bool A block was spread
4069 protected function spreadBlock() {
4070 wfDebug( __METHOD__
. "()\n" );
4072 if ( $this->mId
== 0 ) {
4076 $userblock = Block
::newFromTarget( $this->getName() );
4077 if ( !$userblock ) {
4081 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
4085 * Get whether the user is explicitly blocked from account creation.
4086 * @return bool|Block
4088 public function isBlockedFromCreateAccount() {
4089 $this->getBlockedStatus();
4090 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
4091 return $this->mBlock
;
4094 # bug 13611: if the IP address the user is trying to create an account from is
4095 # blocked with createaccount disabled, prevent new account creation there even
4096 # when the user is logged in
4097 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
4098 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
4100 return $this->mBlockedFromCreateAccount
instanceof Block
4101 && $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
4102 ?
$this->mBlockedFromCreateAccount
4107 * Get whether the user is blocked from using Special:Emailuser.
4110 public function isBlockedFromEmailuser() {
4111 $this->getBlockedStatus();
4112 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
4116 * Get whether the user is allowed to create an account.
4119 public function isAllowedToCreateAccount() {
4120 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
4124 * Get this user's personal page title.
4126 * @return Title User's personal page title
4128 public function getUserPage() {
4129 return Title
::makeTitle( NS_USER
, $this->getName() );
4133 * Get this user's talk page title.
4135 * @return Title User's talk page title
4137 public function getTalkPage() {
4138 $title = $this->getUserPage();
4139 return $title->getTalkPage();
4143 * Determine whether the user is a newbie. Newbies are either
4144 * anonymous IPs, or the most recently created accounts.
4147 public function isNewbie() {
4148 return !$this->isAllowed( 'autoconfirmed' );
4152 * Check to see if the given clear-text password is one of the accepted passwords
4153 * @deprecated since 1.27. AuthManager is coming.
4154 * @param string $password User password
4155 * @return bool True if the given password is correct, otherwise False
4157 public function checkPassword( $password ) {
4158 global $wgAuth, $wgLegacyEncoding;
4162 // Some passwords will give a fatal Status, which means there is
4163 // some sort of technical or security reason for this password to
4164 // be completely invalid and should never be checked (e.g., T64685)
4165 if ( !$this->checkPasswordValidity( $password )->isOK() ) {
4169 // Certain authentication plugins do NOT want to save
4170 // domain passwords in a mysql database, so we should
4171 // check this (in case $wgAuth->strict() is false).
4172 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
4174 } elseif ( $wgAuth->strict() ) {
4175 // Auth plugin doesn't allow local authentication
4177 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
4178 // Auth plugin doesn't allow local authentication for this user name
4182 $passwordFactory = new PasswordFactory();
4183 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4184 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
4185 ?
wfGetDB( DB_MASTER
)
4186 : wfGetDB( DB_SLAVE
);
4189 $mPassword = $passwordFactory->newFromCiphertext( $db->selectField(
4190 'user', 'user_password', [ 'user_id' => $this->getId() ], __METHOD__
4192 } catch ( PasswordError
$e ) {
4193 wfDebug( 'Invalid password hash found in database.' );
4194 $mPassword = PasswordFactory
::newInvalidPassword();
4197 if ( !$mPassword->equals( $password ) ) {
4198 if ( $wgLegacyEncoding ) {
4199 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
4200 // Check for this with iconv
4201 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
4202 if ( $cp1252Password === $password ||
!$mPassword->equals( $cp1252Password ) ) {
4210 if ( $passwordFactory->needsUpdate( $mPassword ) && !wfReadOnly() ) {
4211 $this->setPasswordInternal( $password );
4218 * Check if the given clear-text password matches the temporary password
4219 * sent by e-mail for password reset operations.
4221 * @deprecated since 1.27. AuthManager is coming.
4222 * @param string $plaintext
4223 * @return bool True if matches, false otherwise
4225 public function checkTemporaryPassword( $plaintext ) {
4226 global $wgNewPasswordExpiry;
4230 $passwordFactory = new PasswordFactory();
4231 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4232 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
4233 ?
wfGetDB( DB_MASTER
)
4234 : wfGetDB( DB_SLAVE
);
4236 $row = $db->selectRow(
4238 [ 'user_newpassword', 'user_newpass_time' ],
4239 [ 'user_id' => $this->getId() ],
4243 $newPassword = $passwordFactory->newFromCiphertext( $row->user_newpassword
);
4244 } catch ( PasswordError
$e ) {
4245 wfDebug( 'Invalid password hash found in database.' );
4246 $newPassword = PasswordFactory
::newInvalidPassword();
4249 if ( $newPassword->equals( $plaintext ) ) {
4250 if ( is_null( $row->user_newpass_time
) ) {
4253 $expiry = wfTimestamp( TS_UNIX
, $row->user_newpass_time
) +
$wgNewPasswordExpiry;
4254 return ( time() < $expiry );
4261 * Initialize (if necessary) and return a session token value
4262 * which can be used in edit forms to show that the user's
4263 * login credentials aren't being hijacked with a foreign form
4267 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4268 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4269 * @return MediaWiki\Session\Token The new edit token
4271 public function getEditTokenObject( $salt = '', $request = null ) {
4272 if ( $this->isAnon() ) {
4273 return new LoggedOutEditToken();
4277 $request = $this->getRequest();
4279 return $request->getSession()->getToken( $salt );
4283 * Initialize (if necessary) and return a session token value
4284 * which can be used in edit forms to show that the user's
4285 * login credentials aren't being hijacked with a foreign form
4289 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4290 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4291 * @return string The new edit token
4293 public function getEditToken( $salt = '', $request = null ) {
4294 return $this->getEditTokenObject( $salt, $request )->toString();
4298 * Get the embedded timestamp from a token.
4299 * @deprecated since 1.27, use \MediaWiki\Session\Token::getTimestamp instead.
4300 * @param string $val Input token
4303 public static function getEditTokenTimestamp( $val ) {
4304 wfDeprecated( __METHOD__
, '1.27' );
4305 return MediaWiki\Session\Token
::getTimestamp( $val );
4309 * Check given value against the token value stored in the session.
4310 * A match should confirm that the form was submitted from the
4311 * user's own login session, not a form submission from a third-party
4314 * @param string $val Input value to compare
4315 * @param string $salt Optional function-specific data for hashing
4316 * @param WebRequest|null $request Object to use or null to use $wgRequest
4317 * @param int $maxage Fail tokens older than this, in seconds
4318 * @return bool Whether the token matches
4320 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4321 return $this->getEditTokenObject( $salt, $request )->match( $val, $maxage );
4325 * Check given value against the token value stored in the session,
4326 * ignoring the suffix.
4328 * @param string $val Input value to compare
4329 * @param string $salt Optional function-specific data for hashing
4330 * @param WebRequest|null $request Object to use or null to use $wgRequest
4331 * @param int $maxage Fail tokens older than this, in seconds
4332 * @return bool Whether the token matches
4334 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4335 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . Token
::SUFFIX
;
4336 return $this->matchEditToken( $val, $salt, $request, $maxage );
4340 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4341 * mail to the user's given address.
4343 * @param string $type Message to send, either "created", "changed" or "set"
4346 public function sendConfirmationMail( $type = 'created' ) {
4348 $expiration = null; // gets passed-by-ref and defined in next line.
4349 $token = $this->confirmationToken( $expiration );
4350 $url = $this->confirmationTokenUrl( $token );
4351 $invalidateURL = $this->invalidationTokenUrl( $token );
4352 $this->saveSettings();
4354 if ( $type == 'created' ||
$type === false ) {
4355 $message = 'confirmemail_body';
4356 } elseif ( $type === true ) {
4357 $message = 'confirmemail_body_changed';
4359 // Messages: confirmemail_body_changed, confirmemail_body_set
4360 $message = 'confirmemail_body_' . $type;
4363 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4364 wfMessage( $message,
4365 $this->getRequest()->getIP(),
4368 $wgLang->userTimeAndDate( $expiration, $this ),
4370 $wgLang->userDate( $expiration, $this ),
4371 $wgLang->userTime( $expiration, $this ) )->text() );
4375 * Send an e-mail to this user's account. Does not check for
4376 * confirmed status or validity.
4378 * @param string $subject Message subject
4379 * @param string $body Message body
4380 * @param User|null $from Optional sending user; if unspecified, default
4381 * $wgPasswordSender will be used.
4382 * @param string $replyto Reply-To address
4385 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4386 global $wgPasswordSender;
4388 if ( $from instanceof User
) {
4389 $sender = MailAddress
::newFromUser( $from );
4391 $sender = new MailAddress( $wgPasswordSender,
4392 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4394 $to = MailAddress
::newFromUser( $this );
4396 return UserMailer
::send( $to, $sender, $subject, $body, [
4397 'replyTo' => $replyto,
4402 * Generate, store, and return a new e-mail confirmation code.
4403 * A hash (unsalted, since it's used as a key) is stored.
4405 * @note Call saveSettings() after calling this function to commit
4406 * this change to the database.
4408 * @param string &$expiration Accepts the expiration time
4409 * @return string New token
4411 protected function confirmationToken( &$expiration ) {
4412 global $wgUserEmailConfirmationTokenExpiry;
4414 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4415 $expiration = wfTimestamp( TS_MW
, $expires );
4417 $token = MWCryptRand
::generateHex( 32 );
4418 $hash = md5( $token );
4419 $this->mEmailToken
= $hash;
4420 $this->mEmailTokenExpires
= $expiration;
4425 * Return a URL the user can use to confirm their email address.
4426 * @param string $token Accepts the email confirmation token
4427 * @return string New token URL
4429 protected function confirmationTokenUrl( $token ) {
4430 return $this->getTokenUrl( 'ConfirmEmail', $token );
4434 * Return a URL the user can use to invalidate their email address.
4435 * @param string $token Accepts the email confirmation token
4436 * @return string New token URL
4438 protected function invalidationTokenUrl( $token ) {
4439 return $this->getTokenUrl( 'InvalidateEmail', $token );
4443 * Internal function to format the e-mail validation/invalidation URLs.
4444 * This uses a quickie hack to use the
4445 * hardcoded English names of the Special: pages, for ASCII safety.
4447 * @note Since these URLs get dropped directly into emails, using the
4448 * short English names avoids insanely long URL-encoded links, which
4449 * also sometimes can get corrupted in some browsers/mailers
4450 * (bug 6957 with Gmail and Internet Explorer).
4452 * @param string $page Special page
4453 * @param string $token Token
4454 * @return string Formatted URL
4456 protected function getTokenUrl( $page, $token ) {
4457 // Hack to bypass localization of 'Special:'
4458 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4459 return $title->getCanonicalURL();
4463 * Mark the e-mail address confirmed.
4465 * @note Call saveSettings() after calling this function to commit the change.
4469 public function confirmEmail() {
4470 // Check if it's already confirmed, so we don't touch the database
4471 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4472 if ( !$this->isEmailConfirmed() ) {
4473 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4474 Hooks
::run( 'ConfirmEmailComplete', [ $this ] );
4480 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4481 * address if it was already confirmed.
4483 * @note Call saveSettings() after calling this function to commit the change.
4484 * @return bool Returns true
4486 public function invalidateEmail() {
4488 $this->mEmailToken
= null;
4489 $this->mEmailTokenExpires
= null;
4490 $this->setEmailAuthenticationTimestamp( null );
4492 Hooks
::run( 'InvalidateEmailComplete', [ $this ] );
4497 * Set the e-mail authentication timestamp.
4498 * @param string $timestamp TS_MW timestamp
4500 public function setEmailAuthenticationTimestamp( $timestamp ) {
4502 $this->mEmailAuthenticated
= $timestamp;
4503 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
4507 * Is this user allowed to send e-mails within limits of current
4508 * site configuration?
4511 public function canSendEmail() {
4512 global $wgEnableEmail, $wgEnableUserEmail;
4513 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4516 $canSend = $this->isEmailConfirmed();
4517 Hooks
::run( 'UserCanSendEmail', [ &$this, &$canSend ] );
4522 * Is this user allowed to receive e-mails within limits of current
4523 * site configuration?
4526 public function canReceiveEmail() {
4527 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4531 * Is this user's e-mail address valid-looking and confirmed within
4532 * limits of the current site configuration?
4534 * @note If $wgEmailAuthentication is on, this may require the user to have
4535 * confirmed their address by returning a code or using a password
4536 * sent to the address from the wiki.
4540 public function isEmailConfirmed() {
4541 global $wgEmailAuthentication;
4544 if ( Hooks
::run( 'EmailConfirmed', [ &$this, &$confirmed ] ) ) {
4545 if ( $this->isAnon() ) {
4548 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4551 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4561 * Check whether there is an outstanding request for e-mail confirmation.
4564 public function isEmailConfirmationPending() {
4565 global $wgEmailAuthentication;
4566 return $wgEmailAuthentication &&
4567 !$this->isEmailConfirmed() &&
4568 $this->mEmailToken
&&
4569 $this->mEmailTokenExpires
> wfTimestamp();
4573 * Get the timestamp of account creation.
4575 * @return string|bool|null Timestamp of account creation, false for
4576 * non-existent/anonymous user accounts, or null if existing account
4577 * but information is not in database.
4579 public function getRegistration() {
4580 if ( $this->isAnon() ) {
4584 return $this->mRegistration
;
4588 * Get the timestamp of the first edit
4590 * @return string|bool Timestamp of first edit, or false for
4591 * non-existent/anonymous user accounts.
4593 public function getFirstEditTimestamp() {
4594 if ( $this->getId() == 0 ) {
4595 return false; // anons
4597 $dbr = wfGetDB( DB_SLAVE
);
4598 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4599 [ 'rev_user' => $this->getId() ],
4601 [ 'ORDER BY' => 'rev_timestamp ASC' ]
4604 return false; // no edits
4606 return wfTimestamp( TS_MW
, $time );
4610 * Get the permissions associated with a given list of groups
4612 * @param array $groups Array of Strings List of internal group names
4613 * @return array Array of Strings List of permission key names for given groups combined
4615 public static function getGroupPermissions( $groups ) {
4616 global $wgGroupPermissions, $wgRevokePermissions;
4618 // grant every granted permission first
4619 foreach ( $groups as $group ) {
4620 if ( isset( $wgGroupPermissions[$group] ) ) {
4621 $rights = array_merge( $rights,
4622 // array_filter removes empty items
4623 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4626 // now revoke the revoked permissions
4627 foreach ( $groups as $group ) {
4628 if ( isset( $wgRevokePermissions[$group] ) ) {
4629 $rights = array_diff( $rights,
4630 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4633 return array_unique( $rights );
4637 * Get all the groups who have a given permission
4639 * @param string $role Role to check
4640 * @return array Array of Strings List of internal group names with the given permission
4642 public static function getGroupsWithPermission( $role ) {
4643 global $wgGroupPermissions;
4644 $allowedGroups = [];
4645 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4646 if ( self
::groupHasPermission( $group, $role ) ) {
4647 $allowedGroups[] = $group;
4650 return $allowedGroups;
4654 * Check, if the given group has the given permission
4656 * If you're wanting to check whether all users have a permission, use
4657 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4661 * @param string $group Group to check
4662 * @param string $role Role to check
4665 public static function groupHasPermission( $group, $role ) {
4666 global $wgGroupPermissions, $wgRevokePermissions;
4667 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4668 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4672 * Check if all users may be assumed to have the given permission
4674 * We generally assume so if the right is granted to '*' and isn't revoked
4675 * on any group. It doesn't attempt to take grants or other extension
4676 * limitations on rights into account in the general case, though, as that
4677 * would require it to always return false and defeat the purpose.
4678 * Specifically, session-based rights restrictions (such as OAuth or bot
4679 * passwords) are applied based on the current session.
4682 * @param string $right Right to check
4685 public static function isEveryoneAllowed( $right ) {
4686 global $wgGroupPermissions, $wgRevokePermissions;
4689 // Use the cached results, except in unit tests which rely on
4690 // being able change the permission mid-request
4691 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4692 return $cache[$right];
4695 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4696 $cache[$right] = false;
4700 // If it's revoked anywhere, then everyone doesn't have it
4701 foreach ( $wgRevokePermissions as $rights ) {
4702 if ( isset( $rights[$right] ) && $rights[$right] ) {
4703 $cache[$right] = false;
4708 // Remove any rights that aren't allowed to the global-session user,
4709 // unless there are no sessions for this endpoint.
4710 if ( !defined( 'MW_NO_SESSION' ) ) {
4711 $allowedRights = SessionManager
::getGlobalSession()->getAllowedUserRights();
4712 if ( $allowedRights !== null && !in_array( $right, $allowedRights, true ) ) {
4713 $cache[$right] = false;
4718 // Allow extensions to say false
4719 if ( !Hooks
::run( 'UserIsEveryoneAllowed', [ $right ] ) ) {
4720 $cache[$right] = false;
4724 $cache[$right] = true;
4729 * Get the localized descriptive name for a group, if it exists
4731 * @param string $group Internal group name
4732 * @return string Localized descriptive group name
4734 public static function getGroupName( $group ) {
4735 $msg = wfMessage( "group-$group" );
4736 return $msg->isBlank() ?
$group : $msg->text();
4740 * Get the localized descriptive name for a member of a group, if it exists
4742 * @param string $group Internal group name
4743 * @param string $username Username for gender (since 1.19)
4744 * @return string Localized name for group member
4746 public static function getGroupMember( $group, $username = '#' ) {
4747 $msg = wfMessage( "group-$group-member", $username );
4748 return $msg->isBlank() ?
$group : $msg->text();
4752 * Return the set of defined explicit groups.
4753 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4754 * are not included, as they are defined automatically, not in the database.
4755 * @return array Array of internal group names
4757 public static function getAllGroups() {
4758 global $wgGroupPermissions, $wgRevokePermissions;
4760 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4761 self
::getImplicitGroups()
4766 * Get a list of all available permissions.
4767 * @return string[] Array of permission names
4769 public static function getAllRights() {
4770 if ( self
::$mAllRights === false ) {
4771 global $wgAvailableRights;
4772 if ( count( $wgAvailableRights ) ) {
4773 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
4775 self
::$mAllRights = self
::$mCoreRights;
4777 Hooks
::run( 'UserGetAllRights', [ &self
::$mAllRights ] );
4779 return self
::$mAllRights;
4783 * Get a list of implicit groups
4784 * @return array Array of Strings Array of internal group names
4786 public static function getImplicitGroups() {
4787 global $wgImplicitGroups;
4789 $groups = $wgImplicitGroups;
4790 # Deprecated, use $wgImplicitGroups instead
4791 Hooks
::run( 'UserGetImplicitGroups', [ &$groups ], '1.25' );
4797 * Get the title of a page describing a particular group
4799 * @param string $group Internal group name
4800 * @return Title|bool Title of the page if it exists, false otherwise
4802 public static function getGroupPage( $group ) {
4803 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4804 if ( $msg->exists() ) {
4805 $title = Title
::newFromText( $msg->text() );
4806 if ( is_object( $title ) ) {
4814 * Create a link to the group in HTML, if available;
4815 * else return the group name.
4817 * @param string $group Internal name of the group
4818 * @param string $text The text of the link
4819 * @return string HTML link to the group
4821 public static function makeGroupLinkHTML( $group, $text = '' ) {
4822 if ( $text == '' ) {
4823 $text = self
::getGroupName( $group );
4825 $title = self
::getGroupPage( $group );
4827 return Linker
::link( $title, htmlspecialchars( $text ) );
4829 return htmlspecialchars( $text );
4834 * Create a link to the group in Wikitext, if available;
4835 * else return the group name.
4837 * @param string $group Internal name of the group
4838 * @param string $text The text of the link
4839 * @return string Wikilink to the group
4841 public static function makeGroupLinkWiki( $group, $text = '' ) {
4842 if ( $text == '' ) {
4843 $text = self
::getGroupName( $group );
4845 $title = self
::getGroupPage( $group );
4847 $page = $title->getFullText();
4848 return "[[$page|$text]]";
4855 * Returns an array of the groups that a particular group can add/remove.
4857 * @param string $group The group to check for whether it can add/remove
4858 * @return array Array( 'add' => array( addablegroups ),
4859 * 'remove' => array( removablegroups ),
4860 * 'add-self' => array( addablegroups to self),
4861 * 'remove-self' => array( removable groups from self) )
4863 public static function changeableByGroup( $group ) {
4864 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4873 if ( empty( $wgAddGroups[$group] ) ) {
4874 // Don't add anything to $groups
4875 } elseif ( $wgAddGroups[$group] === true ) {
4876 // You get everything
4877 $groups['add'] = self
::getAllGroups();
4878 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4879 $groups['add'] = $wgAddGroups[$group];
4882 // Same thing for remove
4883 if ( empty( $wgRemoveGroups[$group] ) ) {
4885 } elseif ( $wgRemoveGroups[$group] === true ) {
4886 $groups['remove'] = self
::getAllGroups();
4887 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4888 $groups['remove'] = $wgRemoveGroups[$group];
4891 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4892 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4893 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4894 if ( is_int( $key ) ) {
4895 $wgGroupsAddToSelf['user'][] = $value;
4900 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
4901 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4902 if ( is_int( $key ) ) {
4903 $wgGroupsRemoveFromSelf['user'][] = $value;
4908 // Now figure out what groups the user can add to him/herself
4909 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4911 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4912 // No idea WHY this would be used, but it's there
4913 $groups['add-self'] = User
::getAllGroups();
4914 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4915 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4918 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4920 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4921 $groups['remove-self'] = User
::getAllGroups();
4922 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4923 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4930 * Returns an array of groups that this user can add and remove
4931 * @return array Array( 'add' => array( addablegroups ),
4932 * 'remove' => array( removablegroups ),
4933 * 'add-self' => array( addablegroups to self),
4934 * 'remove-self' => array( removable groups from self) )
4936 public function changeableGroups() {
4937 if ( $this->isAllowed( 'userrights' ) ) {
4938 // This group gives the right to modify everything (reverse-
4939 // compatibility with old "userrights lets you change
4941 // Using array_merge to make the groups reindexed
4942 $all = array_merge( User
::getAllGroups() );
4951 // Okay, it's not so simple, we will have to go through the arrays
4958 $addergroups = $this->getEffectiveGroups();
4960 foreach ( $addergroups as $addergroup ) {
4961 $groups = array_merge_recursive(
4962 $groups, $this->changeableByGroup( $addergroup )
4964 $groups['add'] = array_unique( $groups['add'] );
4965 $groups['remove'] = array_unique( $groups['remove'] );
4966 $groups['add-self'] = array_unique( $groups['add-self'] );
4967 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4973 * Deferred version of incEditCountImmediate()
4975 public function incEditCount() {
4976 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle( function() {
4977 $this->incEditCountImmediate();
4982 * Increment the user's edit-count field.
4983 * Will have no effect for anonymous users.
4986 public function incEditCountImmediate() {
4987 if ( $this->isAnon() ) {
4991 $dbw = wfGetDB( DB_MASTER
);
4992 // No rows will be "affected" if user_editcount is NULL
4995 [ 'user_editcount=user_editcount+1' ],
4996 [ 'user_id' => $this->getId(), 'user_editcount IS NOT NULL' ],
4999 // Lazy initialization check...
5000 if ( $dbw->affectedRows() == 0 ) {
5001 // Now here's a goddamn hack...
5002 $dbr = wfGetDB( DB_SLAVE
);
5003 if ( $dbr !== $dbw ) {
5004 // If we actually have a slave server, the count is
5005 // at least one behind because the current transaction
5006 // has not been committed and replicated.
5007 $this->initEditCount( 1 );
5009 // But if DB_SLAVE is selecting the master, then the
5010 // count we just read includes the revision that was
5011 // just added in the working transaction.
5012 $this->initEditCount();
5015 // Edit count in user cache too
5016 $this->invalidateCache();
5020 * Initialize user_editcount from data out of the revision table
5022 * @param int $add Edits to add to the count from the revision table
5023 * @return int Number of edits
5025 protected function initEditCount( $add = 0 ) {
5026 // Pull from a slave to be less cruel to servers
5027 // Accuracy isn't the point anyway here
5028 $dbr = wfGetDB( DB_SLAVE
);
5029 $count = (int)$dbr->selectField(
5032 [ 'rev_user' => $this->getId() ],
5035 $count = $count +
$add;
5037 $dbw = wfGetDB( DB_MASTER
);
5040 [ 'user_editcount' => $count ],
5041 [ 'user_id' => $this->getId() ],
5049 * Get the description of a given right
5051 * @param string $right Right to query
5052 * @return string Localized description of the right
5054 public static function getRightDescription( $right ) {
5055 $key = "right-$right";
5056 $msg = wfMessage( $key );
5057 return $msg->isBlank() ?
$right : $msg->text();
5061 * Make a new-style password hash
5063 * @param string $password Plain-text password
5064 * @param bool|string $salt Optional salt, may be random or the user ID.
5065 * If unspecified or false, will generate one automatically
5066 * @return string Password hash
5067 * @deprecated since 1.24, use Password class
5069 public static function crypt( $password, $salt = false ) {
5070 wfDeprecated( __METHOD__
, '1.24' );
5071 $passwordFactory = new PasswordFactory();
5072 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
5073 $hash = $passwordFactory->newFromPlaintext( $password );
5074 return $hash->toString();
5078 * Compare a password hash with a plain-text password. Requires the user
5079 * ID if there's a chance that the hash is an old-style hash.
5081 * @param string $hash Password hash
5082 * @param string $password Plain-text password to compare
5083 * @param string|bool $userId User ID for old-style password salt
5086 * @deprecated since 1.24, use Password class
5088 public static function comparePasswords( $hash, $password, $userId = false ) {
5089 wfDeprecated( __METHOD__
, '1.24' );
5091 // Check for *really* old password hashes that don't even have a type
5092 // The old hash format was just an md5 hex hash, with no type information
5093 if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) {
5094 global $wgPasswordSalt;
5095 if ( $wgPasswordSalt ) {
5096 $password = ":B:{$userId}:{$hash}";
5098 $password = ":A:{$hash}";
5102 $passwordFactory = new PasswordFactory();
5103 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
5104 $hash = $passwordFactory->newFromCiphertext( $hash );
5105 return $hash->equals( $password );
5109 * Add a newuser log entry for this user.
5110 * Before 1.19 the return value was always true.
5112 * @param string|bool $action Account creation type.
5113 * - String, one of the following values:
5114 * - 'create' for an anonymous user creating an account for himself.
5115 * This will force the action's performer to be the created user itself,
5116 * no matter the value of $wgUser
5117 * - 'create2' for a logged in user creating an account for someone else
5118 * - 'byemail' when the created user will receive its password by e-mail
5119 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
5120 * - Boolean means whether the account was created by e-mail (deprecated):
5121 * - true will be converted to 'byemail'
5122 * - false will be converted to 'create' if this object is the same as
5123 * $wgUser and to 'create2' otherwise
5125 * @param string $reason User supplied reason
5127 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
5129 public function addNewUserLogEntry( $action = false, $reason = '' ) {
5130 global $wgUser, $wgNewUserLog;
5131 if ( empty( $wgNewUserLog ) ) {
5132 return true; // disabled
5135 if ( $action === true ) {
5136 $action = 'byemail';
5137 } elseif ( $action === false ) {
5138 if ( $this->equals( $wgUser ) ) {
5141 $action = 'create2';
5145 if ( $action === 'create' ||
$action === 'autocreate' ) {
5148 $performer = $wgUser;
5151 $logEntry = new ManualLogEntry( 'newusers', $action );
5152 $logEntry->setPerformer( $performer );
5153 $logEntry->setTarget( $this->getUserPage() );
5154 $logEntry->setComment( $reason );
5155 $logEntry->setParameters( [
5156 '4::userid' => $this->getId(),
5158 $logid = $logEntry->insert();
5160 if ( $action !== 'autocreate' ) {
5161 $logEntry->publish( $logid );
5168 * Add an autocreate newuser log entry for this user
5169 * Used by things like CentralAuth and perhaps other authplugins.
5170 * Consider calling addNewUserLogEntry() directly instead.
5174 public function addNewUserLogEntryAutoCreate() {
5175 $this->addNewUserLogEntry( 'autocreate' );
5181 * Load the user options either from cache, the database or an array
5183 * @param array $data Rows for the current user out of the user_properties table
5185 protected function loadOptions( $data = null ) {
5190 if ( $this->mOptionsLoaded
) {
5194 $this->mOptions
= self
::getDefaultOptions();
5196 if ( !$this->getId() ) {
5197 // For unlogged-in users, load language/variant options from request.
5198 // There's no need to do it for logged-in users: they can set preferences,
5199 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5200 // so don't override user's choice (especially when the user chooses site default).
5201 $variant = $wgContLang->getDefaultVariant();
5202 $this->mOptions
['variant'] = $variant;
5203 $this->mOptions
['language'] = $variant;
5204 $this->mOptionsLoaded
= true;
5208 // Maybe load from the object
5209 if ( !is_null( $this->mOptionOverrides
) ) {
5210 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5211 foreach ( $this->mOptionOverrides
as $key => $value ) {
5212 $this->mOptions
[$key] = $value;
5215 if ( !is_array( $data ) ) {
5216 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5217 // Load from database
5218 $dbr = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
5219 ?
wfGetDB( DB_MASTER
)
5220 : wfGetDB( DB_SLAVE
);
5222 $res = $dbr->select(
5224 [ 'up_property', 'up_value' ],
5225 [ 'up_user' => $this->getId() ],
5229 $this->mOptionOverrides
= [];
5231 foreach ( $res as $row ) {
5232 $data[$row->up_property
] = $row->up_value
;
5235 foreach ( $data as $property => $value ) {
5236 $this->mOptionOverrides
[$property] = $value;
5237 $this->mOptions
[$property] = $value;
5241 $this->mOptionsLoaded
= true;
5243 Hooks
::run( 'UserLoadOptions', [ $this, &$this->mOptions
] );
5247 * Saves the non-default options for this user, as previously set e.g. via
5248 * setOption(), in the database's "user_properties" (preferences) table.
5249 * Usually used via saveSettings().
5251 protected function saveOptions() {
5252 $this->loadOptions();
5254 // Not using getOptions(), to keep hidden preferences in database
5255 $saveOptions = $this->mOptions
;
5257 // Allow hooks to abort, for instance to save to a global profile.
5258 // Reset options to default state before saving.
5259 if ( !Hooks
::run( 'UserSaveOptions', [ $this, &$saveOptions ] ) ) {
5263 $userId = $this->getId();
5265 $insert_rows = []; // all the new preference rows
5266 foreach ( $saveOptions as $key => $value ) {
5267 // Don't bother storing default values
5268 $defaultOption = self
::getDefaultOption( $key );
5269 if ( ( $defaultOption === null && $value !== false && $value !== null )
5270 ||
$value != $defaultOption
5273 'up_user' => $userId,
5274 'up_property' => $key,
5275 'up_value' => $value,
5280 $dbw = wfGetDB( DB_MASTER
);
5282 $res = $dbw->select( 'user_properties',
5283 [ 'up_property', 'up_value' ], [ 'up_user' => $userId ], __METHOD__
);
5285 // Find prior rows that need to be removed or updated. These rows will
5286 // all be deleted (the later so that INSERT IGNORE applies the new values).
5288 foreach ( $res as $row ) {
5289 if ( !isset( $saveOptions[$row->up_property
] )
5290 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
5292 $keysDelete[] = $row->up_property
;
5296 if ( count( $keysDelete ) ) {
5297 // Do the DELETE by PRIMARY KEY for prior rows.
5298 // In the past a very large portion of calls to this function are for setting
5299 // 'rememberpassword' for new accounts (a preference that has since been removed).
5300 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5301 // caused gap locks on [max user ID,+infinity) which caused high contention since
5302 // updates would pile up on each other as they are for higher (newer) user IDs.
5303 // It might not be necessary these days, but it shouldn't hurt either.
5304 $dbw->delete( 'user_properties',
5305 [ 'up_user' => $userId, 'up_property' => $keysDelete ], __METHOD__
);
5307 // Insert the new preference rows
5308 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, [ 'IGNORE' ] );
5312 * Lazily instantiate and return a factory object for making passwords
5314 * @deprecated since 1.27, create a PasswordFactory directly instead
5315 * @return PasswordFactory
5317 public static function getPasswordFactory() {
5318 wfDeprecated( __METHOD__
, '1.27' );
5319 $ret = new PasswordFactory();
5320 $ret->init( RequestContext
::getMain()->getConfig() );
5325 * Provide an array of HTML5 attributes to put on an input element
5326 * intended for the user to enter a new password. This may include
5327 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
5329 * Do *not* use this when asking the user to enter his current password!
5330 * Regardless of configuration, users may have invalid passwords for whatever
5331 * reason (e.g., they were set before requirements were tightened up).
5332 * Only use it when asking for a new password, like on account creation or
5335 * Obviously, you still need to do server-side checking.
5337 * NOTE: A combination of bugs in various browsers means that this function
5338 * actually just returns array() unconditionally at the moment. May as
5339 * well keep it around for when the browser bugs get fixed, though.
5341 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
5343 * @deprecated since 1.27
5344 * @return array Array of HTML attributes suitable for feeding to
5345 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
5346 * That will get confused by the boolean attribute syntax used.)
5348 public static function passwordChangeInputAttribs() {
5349 global $wgMinimalPasswordLength;
5351 if ( $wgMinimalPasswordLength == 0 ) {
5355 # Note that the pattern requirement will always be satisfied if the
5356 # input is empty, so we need required in all cases.
5358 # @todo FIXME: Bug 23769: This needs to not claim the password is required
5359 # if e-mail confirmation is being used. Since HTML5 input validation
5360 # is b0rked anyway in some browsers, just return nothing. When it's
5361 # re-enabled, fix this code to not output required for e-mail
5363 # $ret = array( 'required' );
5366 # We can't actually do this right now, because Opera 9.6 will print out
5367 # the entered password visibly in its error message! When other
5368 # browsers add support for this attribute, or Opera fixes its support,
5369 # we can add support with a version check to avoid doing this on Opera
5370 # versions where it will be a problem. Reported to Opera as
5371 # DSK-262266, but they don't have a public bug tracker for us to follow.
5373 if ( $wgMinimalPasswordLength > 1 ) {
5374 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
5375 $ret['title'] = wfMessage( 'passwordtooshort' )
5376 ->numParams( $wgMinimalPasswordLength )->text();
5384 * Return the list of user fields that should be selected to create
5385 * a new user object.
5388 public static function selectFields() {
5396 'user_email_authenticated',
5398 'user_email_token_expires',
5399 'user_registration',
5405 * Factory function for fatal permission-denied errors
5408 * @param string $permission User right required
5411 static function newFatalPermissionDeniedStatus( $permission ) {
5414 $groups = array_map(
5415 [ 'User', 'makeGroupLinkWiki' ],
5416 User
::getGroupsWithPermission( $permission )
5420 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5422 return Status
::newFatal( 'badaccess-group0' );
5427 * Get a new instance of this user that was loaded from the master via a locking read
5429 * Use this instead of the main context User when updating that user. This avoids races
5430 * where that user was loaded from a slave or even the master but without proper locks.
5432 * @return User|null Returns null if the user was not found in the DB
5435 public function getInstanceForUpdate() {
5436 if ( !$this->getId() ) {
5437 return null; // anon
5440 $user = self
::newFromId( $this->getId() );
5441 if ( !$user->loadFromId( self
::READ_EXCLUSIVE
) ) {
5449 * Checks if two user objects point to the same user.
5455 public function equals( User
$user ) {
5456 return $this->getName() === $user->getName();