3 * Implements the User class for the %MediaWiki software.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use MediaWiki\Session\SessionManager
;
26 * String Some punctuation to prevent editing from broken text-mangling proxies.
27 * @deprecated since 1.27, use \\MediaWiki\\Session\\Token::SUFFIX
30 define( 'EDIT_TOKEN_SUFFIX', MediaWiki\Session\Token
::SUFFIX
);
33 * The User object encapsulates all of the user-specific settings (user_id,
34 * name, rights, email address, options, last login time). Client
35 * classes use the getXXX() functions to access these fields. These functions
36 * do all the work of determining whether the user is logged in,
37 * whether the requested option can be satisfied from cookies or
38 * whether a database query is needed. Most of the settings needed
39 * for rendering normal pages are set in the cookie to minimize use
42 class User
implements IDBAccessObject
{
44 * @const int Number of characters in user_token field.
46 const TOKEN_LENGTH
= 32;
49 * @const string An invalid value for user_token
51 const INVALID_TOKEN
= '*** INVALID ***';
54 * Global constant made accessible as class constants so that autoloader
56 * @deprecated since 1.27, use \\MediaWiki\\Session\\Token::SUFFIX
58 const EDIT_TOKEN_SUFFIX
= EDIT_TOKEN_SUFFIX
;
61 * @const int Serialized record version.
66 * Maximum items in $mWatchedItems
68 const MAX_WATCHED_ITEMS_CACHE
= 100;
71 * Exclude user options that are set to their default value.
74 const GETOPTIONS_EXCLUDE_DEFAULTS
= 1;
77 * Array of Strings List of member variables which are saved to the
78 * shared cache (memcached). Any operation which changes the
79 * corresponding database fields must call a cache-clearing function.
82 protected static $mCacheVars = [
90 'mEmailAuthenticated',
97 // user_properties table
102 * Array of Strings Core rights.
103 * Each of these should have a corresponding message of the form
107 protected static $mCoreRights = [
137 'editusercssjs', # deprecated
150 'move-categorypages',
151 'move-rootuserpages',
155 'override-export-depth',
178 'userrights-interwiki',
186 * String Cached results of getAllRights()
188 protected static $mAllRights = false;
190 /** Cache variables */
200 /** @var string TS_MW timestamp from the DB */
202 /** @var string TS_MW timestamp from cache */
203 protected $mQuickTouched;
207 public $mEmailAuthenticated;
209 protected $mEmailToken;
211 protected $mEmailTokenExpires;
213 protected $mRegistration;
215 protected $mEditCount;
219 protected $mOptionOverrides;
223 * Bool Whether the cache variables have been loaded.
226 public $mOptionsLoaded;
229 * Array with already loaded items or true if all items have been loaded.
231 protected $mLoadedItems = [];
235 * String Initialization data source if mLoadedItems!==true. May be one of:
236 * - 'defaults' anonymous user initialised from class defaults
237 * - 'name' initialise from mName
238 * - 'id' initialise from mId
239 * - 'session' log in from session if possible
241 * Use the User::newFrom*() family of functions to set this.
246 * Lazy-initialized variables, invalidated with clearInstanceCache
250 protected $mDatePreference;
258 protected $mBlockreason;
260 protected $mEffectiveGroups;
262 protected $mImplicitGroups;
264 protected $mFormerGroups;
266 protected $mBlockedGlobally;
283 protected $mAllowUsertalk;
286 private $mBlockedFromCreateAccount = false;
289 private $mWatchedItems = [];
291 /** @var integer User::READ_* constant bitfield used to load data */
292 protected $queryFlagsUsed = self
::READ_NORMAL
;
294 public static $idCacheByName = [];
297 * Lightweight constructor for an anonymous user.
298 * Use the User::newFrom* factory functions for other kinds of users.
302 * @see newFromConfirmationCode()
303 * @see newFromSession()
306 public function __construct() {
307 $this->clearInstanceCache( 'defaults' );
313 public function __toString() {
314 return $this->getName();
318 * Test if it's safe to load this User object. You should typically check this before using
319 * $wgUser or RequestContext::getUser in a method that might be called before the system has
320 * been fully initialized. If the object is unsafe, you should use an anonymous user:
322 * $user = $wgUser->isSafeToLoad() ? $wgUser : new User;
328 public function isSafeToLoad() {
329 global $wgFullyInitialised;
330 return $wgFullyInitialised ||
$this->mLoadedItems
=== true ||
$this->mFrom
!== 'session';
334 * Load the user table data for this object from the source given by mFrom.
336 * @param integer $flags User::READ_* constant bitfield
338 public function load( $flags = self
::READ_NORMAL
) {
339 global $wgFullyInitialised;
341 if ( $this->mLoadedItems
=== true ) {
345 // Set it now to avoid infinite recursion in accessors
346 $oldLoadedItems = $this->mLoadedItems
;
347 $this->mLoadedItems
= true;
348 $this->queryFlagsUsed
= $flags;
350 // If this is called too early, things are likely to break.
351 if ( !$wgFullyInitialised && $this->mFrom
=== 'session' ) {
352 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
353 ->warning( 'User::loadFromSession called before the end of Setup.php', [
354 'exception' => new Exception( 'User::loadFromSession called before the end of Setup.php' ),
356 $this->loadDefaults();
357 $this->mLoadedItems
= $oldLoadedItems;
361 switch ( $this->mFrom
) {
363 $this->loadDefaults();
366 // Make sure this thread sees its own changes
367 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
368 $flags |
= self
::READ_LATEST
;
369 $this->queryFlagsUsed
= $flags;
372 $this->mId
= self
::idFromName( $this->mName
, $flags );
374 // Nonexistent user placeholder object
375 $this->loadDefaults( $this->mName
);
377 $this->loadFromId( $flags );
381 $this->loadFromId( $flags );
384 if ( !$this->loadFromSession() ) {
385 // Loading from session failed. Load defaults.
386 $this->loadDefaults();
388 Hooks
::run( 'UserLoadAfterLoadFromSession', [ $this ] );
391 throw new UnexpectedValueException(
392 "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
397 * Load user table data, given mId has already been set.
398 * @param integer $flags User::READ_* constant bitfield
399 * @return bool False if the ID does not exist, true otherwise
401 public function loadFromId( $flags = self
::READ_NORMAL
) {
402 if ( $this->mId
== 0 ) {
403 $this->loadDefaults();
407 // Try cache (unless this needs data from the master DB).
408 // NOTE: if this thread called saveSettings(), the cache was cleared.
409 $latest = DBAccessObjectUtils
::hasFlags( $flags, self
::READ_LATEST
);
410 if ( $latest ||
!$this->loadFromCache() ) {
411 wfDebug( "User: cache miss for user {$this->mId}\n" );
412 // Load from DB (make sure this thread sees its own changes)
413 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
414 $flags |
= self
::READ_LATEST
;
416 if ( !$this->loadFromDatabase( $flags ) ) {
417 // Can't load from ID, user is anonymous
420 $this->saveToCache();
423 $this->mLoadedItems
= true;
424 $this->queryFlagsUsed
= $flags;
431 * @param string $wikiId
432 * @param integer $userId
434 public static function purge( $wikiId, $userId ) {
435 $cache = ObjectCache
::getMainWANInstance();
436 $cache->delete( $cache->makeGlobalKey( 'user', 'id', $wikiId, $userId ) );
441 * @param WANObjectCache $cache
444 protected function getCacheKey( WANObjectCache
$cache ) {
445 return $cache->makeGlobalKey( 'user', 'id', wfWikiID(), $this->mId
);
449 * Load user data from shared cache, given mId has already been set.
451 * @return bool false if the ID does not exist or data is invalid, true otherwise
454 protected function loadFromCache() {
455 if ( $this->mId
== 0 ) {
456 $this->loadDefaults();
460 $cache = ObjectCache
::getMainWANInstance();
461 $key = $this->getCacheKey( $cache );
463 $processCache = ObjectCache
::getLocalServerInstance( 'hash' );
464 $data = $processCache->get( $key );
465 if ( !is_array( $data ) ) {
466 $data = $cache->get( $key );
467 if ( !is_array( $data ) ||
$data['mVersion'] < self
::VERSION
) {
471 $processCache->set( $key, $data );
473 wfDebug( "User: got user {$this->mId} from cache\n" );
475 // Restore from cache
476 foreach ( self
::$mCacheVars as $name ) {
477 $this->$name = $data[$name];
484 * Save user data to the shared cache
486 * This method should not be called outside the User class
488 public function saveToCache() {
491 $this->loadOptions();
493 if ( $this->isAnon() ) {
494 // Anonymous users are uncached
499 foreach ( self
::$mCacheVars as $name ) {
500 $data[$name] = $this->$name;
502 $data['mVersion'] = self
::VERSION
;
503 $opts = Database
::getCacheSetOptions( wfGetDB( DB_SLAVE
) );
505 $cache = ObjectCache
::getMainWANInstance();
506 $key = $this->getCacheKey( $cache );
507 $cache->set( $key, $data, $cache::TTL_HOUR
, $opts );
510 /** @name newFrom*() static factory methods */
514 * Static factory method for creation from username.
516 * This is slightly less efficient than newFromId(), so use newFromId() if
517 * you have both an ID and a name handy.
519 * @param string $name Username, validated by Title::newFromText()
520 * @param string|bool $validate Validate username. Takes the same parameters as
521 * User::getCanonicalName(), except that true is accepted as an alias
522 * for 'valid', for BC.
524 * @return User|bool User object, or false if the username is invalid
525 * (e.g. if it contains illegal characters or is an IP address). If the
526 * username is not present in the database, the result will be a user object
527 * with a name, zero user ID and default settings.
529 public static function newFromName( $name, $validate = 'valid' ) {
530 if ( $validate === true ) {
533 $name = self
::getCanonicalName( $name, $validate );
534 if ( $name === false ) {
537 // Create unloaded user object
541 $u->setItemLoaded( 'name' );
547 * Static factory method for creation from a given user ID.
549 * @param int $id Valid user ID
550 * @return User The corresponding User object
552 public static function newFromId( $id ) {
556 $u->setItemLoaded( 'id' );
561 * Factory method to fetch whichever user has a given email confirmation code.
562 * This code is generated when an account is created or its e-mail address
565 * If the code is invalid or has expired, returns NULL.
567 * @param string $code Confirmation code
568 * @param int $flags User::READ_* bitfield
571 public static function newFromConfirmationCode( $code, $flags = 0 ) {
572 $db = ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
573 ?
wfGetDB( DB_MASTER
)
574 : wfGetDB( DB_SLAVE
);
576 $id = $db->selectField(
580 'user_email_token' => md5( $code ),
581 'user_email_token_expires > ' . $db->addQuotes( $db->timestamp() ),
585 return $id ? User
::newFromId( $id ) : null;
589 * Create a new user object using data from session. If the login
590 * credentials are invalid, the result is an anonymous user.
592 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
595 public static function newFromSession( WebRequest
$request = null ) {
597 $user->mFrom
= 'session';
598 $user->mRequest
= $request;
603 * Create a new user object from a user row.
604 * The row should have the following fields from the user table in it:
605 * - either user_name or user_id to load further data if needed (or both)
607 * - all other fields (email, etc.)
608 * It is useless to provide the remaining fields if either user_id,
609 * user_name and user_real_name are not provided because the whole row
610 * will be loaded once more from the database when accessing them.
612 * @param stdClass $row A row from the user table
613 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
616 public static function newFromRow( $row, $data = null ) {
618 $user->loadFromRow( $row, $data );
623 * Static factory method for creation of a "system" user from username.
625 * A "system" user is an account that's used to attribute logged actions
626 * taken by MediaWiki itself, as opposed to a bot or human user. Examples
627 * might include the 'Maintenance script' or 'Conversion script' accounts
628 * used by various scripts in the maintenance/ directory or accounts such
629 * as 'MediaWiki message delivery' used by the MassMessage extension.
631 * This can optionally create the user if it doesn't exist, and "steal" the
632 * account if it does exist.
634 * @param string $name Username
635 * @param array $options Options are:
636 * - validate: As for User::getCanonicalName(), default 'valid'
637 * - create: Whether to create the user if it doesn't already exist, default true
638 * - steal: Whether to reset the account's password and email if it
639 * already exists, default false
642 public static function newSystemUser( $name, $options = [] ) {
644 'validate' => 'valid',
649 $name = self
::getCanonicalName( $name, $options['validate'] );
650 if ( $name === false ) {
654 $dbw = wfGetDB( DB_MASTER
);
655 $row = $dbw->selectRow(
658 self
::selectFields(),
659 [ 'user_password', 'user_newpassword' ]
661 [ 'user_name' => $name ],
665 // No user. Create it?
666 return $options['create'] ? self
::createNew( $name ) : null;
668 $user = self
::newFromRow( $row );
670 // A user is considered to exist as a non-system user if it has a
671 // password set, or a temporary password set, or an email set, or a
672 // non-invalid token.
673 $passwordFactory = new PasswordFactory();
674 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
676 $password = $passwordFactory->newFromCiphertext( $row->user_password
);
677 } catch ( PasswordError
$e ) {
678 wfDebug( 'Invalid password hash found in database.' );
679 $password = PasswordFactory
::newInvalidPassword();
682 $newpassword = $passwordFactory->newFromCiphertext( $row->user_newpassword
);
683 } catch ( PasswordError
$e ) {
684 wfDebug( 'Invalid password hash found in database.' );
685 $newpassword = PasswordFactory
::newInvalidPassword();
687 if ( !$password instanceof InvalidPassword ||
!$newpassword instanceof InvalidPassword
688 ||
$user->mEmail ||
$user->mToken
!== self
::INVALID_TOKEN
690 // User exists. Steal it?
691 if ( !$options['steal'] ) {
695 $nopass = PasswordFactory
::newInvalidPassword()->toString();
700 'user_password' => $nopass,
701 'user_newpassword' => $nopass,
702 'user_newpass_time' => null,
704 [ 'user_id' => $user->getId() ],
707 $user->invalidateEmail();
708 $user->mToken
= self
::INVALID_TOKEN
;
709 $user->saveSettings();
710 SessionManager
::singleton()->preventSessionsForUser( $user->getName() );
719 * Get the username corresponding to a given user ID
720 * @param int $id User ID
721 * @return string|bool The corresponding username
723 public static function whoIs( $id ) {
724 return UserCache
::singleton()->getProp( $id, 'name' );
728 * Get the real name of a user given their user ID
730 * @param int $id User ID
731 * @return string|bool The corresponding user's real name
733 public static function whoIsReal( $id ) {
734 return UserCache
::singleton()->getProp( $id, 'real_name' );
738 * Get database id given a user name
739 * @param string $name Username
740 * @param integer $flags User::READ_* constant bitfield
741 * @return int|null The corresponding user's ID, or null if user is nonexistent
743 public static function idFromName( $name, $flags = self
::READ_NORMAL
) {
744 $nt = Title
::makeTitleSafe( NS_USER
, $name );
745 if ( is_null( $nt ) ) {
750 if ( !( $flags & self
::READ_LATEST
) && isset( self
::$idCacheByName[$name] ) ) {
751 return self
::$idCacheByName[$name];
754 $db = ( $flags & self
::READ_LATEST
)
755 ?
wfGetDB( DB_MASTER
)
756 : wfGetDB( DB_SLAVE
);
761 [ 'user_name' => $nt->getText() ],
765 if ( $s === false ) {
768 $result = $s->user_id
;
771 self
::$idCacheByName[$name] = $result;
773 if ( count( self
::$idCacheByName ) > 1000 ) {
774 self
::$idCacheByName = [];
781 * Reset the cache used in idFromName(). For use in tests.
783 public static function resetIdByNameCache() {
784 self
::$idCacheByName = [];
788 * Does the string match an anonymous IPv4 address?
790 * This function exists for username validation, in order to reject
791 * usernames which are similar in form to IP addresses. Strings such
792 * as 300.300.300.300 will return true because it looks like an IP
793 * address, despite not being strictly valid.
795 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
796 * address because the usemod software would "cloak" anonymous IP
797 * addresses like this, if we allowed accounts like this to be created
798 * new users could get the old edits of these anonymous users.
800 * @param string $name Name to match
803 public static function isIP( $name ) {
804 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
805 || IP
::isIPv6( $name );
809 * Is the input a valid username?
811 * Checks if the input is a valid username, we don't want an empty string,
812 * an IP address, anything that contains slashes (would mess up subpages),
813 * is longer than the maximum allowed username size or doesn't begin with
816 * @param string $name Name to match
819 public static function isValidUserName( $name ) {
820 global $wgContLang, $wgMaxNameChars;
823 || User
::isIP( $name )
824 ||
strpos( $name, '/' ) !== false
825 ||
strlen( $name ) > $wgMaxNameChars
826 ||
$name != $wgContLang->ucfirst( $name )
828 wfDebugLog( 'username', __METHOD__
.
829 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
833 // Ensure that the name can't be misresolved as a different title,
834 // such as with extra namespace keys at the start.
835 $parsed = Title
::newFromText( $name );
836 if ( is_null( $parsed )
837 ||
$parsed->getNamespace()
838 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
839 wfDebugLog( 'username', __METHOD__
.
840 ": '$name' invalid due to ambiguous prefixes" );
844 // Check an additional blacklist of troublemaker characters.
845 // Should these be merged into the title char list?
846 $unicodeBlacklist = '/[' .
847 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
848 '\x{00a0}' . # non-breaking space
849 '\x{2000}-\x{200f}' . # various whitespace
850 '\x{2028}-\x{202f}' . # breaks and control chars
851 '\x{3000}' . # ideographic space
852 '\x{e000}-\x{f8ff}' . # private use
854 if ( preg_match( $unicodeBlacklist, $name ) ) {
855 wfDebugLog( 'username', __METHOD__
.
856 ": '$name' invalid due to blacklisted characters" );
864 * Usernames which fail to pass this function will be blocked
865 * from user login and new account registrations, but may be used
866 * internally by batch processes.
868 * If an account already exists in this form, login will be blocked
869 * by a failure to pass this function.
871 * @param string $name Name to match
874 public static function isUsableName( $name ) {
875 global $wgReservedUsernames;
876 // Must be a valid username, obviously ;)
877 if ( !self
::isValidUserName( $name ) ) {
881 static $reservedUsernames = false;
882 if ( !$reservedUsernames ) {
883 $reservedUsernames = $wgReservedUsernames;
884 Hooks
::run( 'UserGetReservedNames', [ &$reservedUsernames ] );
887 // Certain names may be reserved for batch processes.
888 foreach ( $reservedUsernames as $reserved ) {
889 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
890 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
892 if ( $reserved == $name ) {
900 * Usernames which fail to pass this function will be blocked
901 * from new account registrations, but may be used internally
902 * either by batch processes or by user accounts which have
903 * already been created.
905 * Additional blacklisting may be added here rather than in
906 * isValidUserName() to avoid disrupting existing accounts.
908 * @param string $name String to match
911 public static function isCreatableName( $name ) {
912 global $wgInvalidUsernameCharacters;
914 // Ensure that the username isn't longer than 235 bytes, so that
915 // (at least for the builtin skins) user javascript and css files
916 // will work. (bug 23080)
917 if ( strlen( $name ) > 235 ) {
918 wfDebugLog( 'username', __METHOD__
.
919 ": '$name' invalid due to length" );
923 // Preg yells if you try to give it an empty string
924 if ( $wgInvalidUsernameCharacters !== '' ) {
925 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
926 wfDebugLog( 'username', __METHOD__
.
927 ": '$name' invalid due to wgInvalidUsernameCharacters" );
932 return self
::isUsableName( $name );
936 * Is the input a valid password for this user?
938 * @param string $password Desired password
941 public function isValidPassword( $password ) {
942 // simple boolean wrapper for getPasswordValidity
943 return $this->getPasswordValidity( $password ) === true;
947 * Given unvalidated password input, return error message on failure.
949 * @param string $password Desired password
950 * @return bool|string|array True on success, string or array of error message on failure
952 public function getPasswordValidity( $password ) {
953 $result = $this->checkPasswordValidity( $password );
954 if ( $result->isGood() ) {
958 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
959 $messages[] = $error['message'];
961 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
962 $messages[] = $warning['message'];
964 if ( count( $messages ) === 1 ) {
972 * Check if this is a valid password for this user
974 * Create a Status object based on the password's validity.
975 * The Status should be set to fatal if the user should not
976 * be allowed to log in, and should have any errors that
977 * would block changing the password.
979 * If the return value of this is not OK, the password
980 * should not be checked. If the return value is not Good,
981 * the password can be checked, but the user should not be
982 * able to set their password to this.
984 * @param string $password Desired password
985 * @param string $purpose one of 'login', 'create', 'reset'
989 public function checkPasswordValidity( $password, $purpose = 'login' ) {
990 global $wgPasswordPolicy;
992 $upp = new UserPasswordPolicy(
993 $wgPasswordPolicy['policies'],
994 $wgPasswordPolicy['checks']
997 $status = Status
::newGood();
998 $result = false; // init $result to false for the internal checks
1000 if ( !Hooks
::run( 'isValidPassword', [ $password, &$result, $this ] ) ) {
1001 $status->error( $result );
1005 if ( $result === false ) {
1006 $status->merge( $upp->checkUserPassword( $this, $password, $purpose ) );
1008 } elseif ( $result === true ) {
1011 $status->error( $result );
1012 return $status; // the isValidPassword hook set a string $result and returned true
1017 * Given unvalidated user input, return a canonical username, or false if
1018 * the username is invalid.
1019 * @param string $name User input
1020 * @param string|bool $validate Type of validation to use:
1021 * - false No validation
1022 * - 'valid' Valid for batch processes
1023 * - 'usable' Valid for batch processes and login
1024 * - 'creatable' Valid for batch processes, login and account creation
1026 * @throws InvalidArgumentException
1027 * @return bool|string
1029 public static function getCanonicalName( $name, $validate = 'valid' ) {
1030 // Force usernames to capital
1032 $name = $wgContLang->ucfirst( $name );
1034 # Reject names containing '#'; these will be cleaned up
1035 # with title normalisation, but then it's too late to
1037 if ( strpos( $name, '#' ) !== false ) {
1041 // Clean up name according to title rules,
1042 // but only when validation is requested (bug 12654)
1043 $t = ( $validate !== false ) ?
1044 Title
::newFromText( $name ) : Title
::makeTitle( NS_USER
, $name );
1045 // Check for invalid titles
1046 if ( is_null( $t ) ) {
1050 // Reject various classes of invalid names
1052 $name = $wgAuth->getCanonicalName( $t->getText() );
1054 switch ( $validate ) {
1058 if ( !User
::isValidUserName( $name ) ) {
1063 if ( !User
::isUsableName( $name ) ) {
1068 if ( !User
::isCreatableName( $name ) ) {
1073 throw new InvalidArgumentException(
1074 'Invalid parameter value for $validate in ' . __METHOD__
);
1080 * Count the number of edits of a user
1082 * @param int $uid User ID to check
1083 * @return int The user's edit count
1085 * @deprecated since 1.21 in favour of User::getEditCount
1087 public static function edits( $uid ) {
1088 wfDeprecated( __METHOD__
, '1.21' );
1089 $user = self
::newFromId( $uid );
1090 return $user->getEditCount();
1094 * Return a random password.
1096 * @deprecated since 1.27, use PasswordFactory::generateRandomPasswordString()
1097 * @return string New random password
1099 public static function randomPassword() {
1100 global $wgMinimalPasswordLength;
1101 return PasswordFactory
::generateRandomPasswordString( $wgMinimalPasswordLength );
1105 * Set cached properties to default.
1107 * @note This no longer clears uncached lazy-initialised properties;
1108 * the constructor does that instead.
1110 * @param string|bool $name
1112 public function loadDefaults( $name = false ) {
1114 $this->mName
= $name;
1115 $this->mRealName
= '';
1117 $this->mOptionOverrides
= null;
1118 $this->mOptionsLoaded
= false;
1120 $loggedOut = $this->mRequest
&& !defined( 'MW_NO_SESSION' )
1121 ?
$this->mRequest
->getSession()->getLoggedOutTimestamp() : 0;
1122 if ( $loggedOut !== 0 ) {
1123 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1125 $this->mTouched
= '1'; # Allow any pages to be cached
1128 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1129 $this->mEmailAuthenticated
= null;
1130 $this->mEmailToken
= '';
1131 $this->mEmailTokenExpires
= null;
1132 $this->mRegistration
= wfTimestamp( TS_MW
);
1133 $this->mGroups
= [];
1135 Hooks
::run( 'UserLoadDefaults', [ $this, $name ] );
1139 * Return whether an item has been loaded.
1141 * @param string $item Item to check. Current possibilities:
1145 * @param string $all 'all' to check if the whole object has been loaded
1146 * or any other string to check if only the item is available (e.g.
1150 public function isItemLoaded( $item, $all = 'all' ) {
1151 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1152 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1156 * Set that an item has been loaded
1158 * @param string $item
1160 protected function setItemLoaded( $item ) {
1161 if ( is_array( $this->mLoadedItems
) ) {
1162 $this->mLoadedItems
[$item] = true;
1167 * Load user data from the session.
1169 * @return bool True if the user is logged in, false otherwise.
1171 private function loadFromSession() {
1174 Hooks
::run( 'UserLoadFromSession', [ $this, &$result ], '1.27' );
1175 if ( $result !== null ) {
1179 // MediaWiki\Session\Session already did the necessary authentication of the user
1180 // returned here, so just use it if applicable.
1181 $session = $this->getRequest()->getSession();
1182 $user = $session->getUser();
1183 if ( $user->isLoggedIn() ) {
1184 $this->loadFromUserObject( $user );
1185 // Other code expects these to be set in the session, so set them.
1186 $session->set( 'wsUserID', $this->getId() );
1187 $session->set( 'wsUserName', $this->getName() );
1188 $session->set( 'wsToken', $this->getToken() );
1196 * Load user and user_group data from the database.
1197 * $this->mId must be set, this is how the user is identified.
1199 * @param integer $flags User::READ_* constant bitfield
1200 * @return bool True if the user exists, false if the user is anonymous
1202 public function loadFromDatabase( $flags = self
::READ_LATEST
) {
1204 $this->mId
= intval( $this->mId
);
1207 if ( !$this->mId
) {
1208 $this->loadDefaults();
1212 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
1213 $db = wfGetDB( $index );
1215 $s = $db->selectRow(
1217 self
::selectFields(),
1218 [ 'user_id' => $this->mId
],
1223 $this->queryFlagsUsed
= $flags;
1224 Hooks
::run( 'UserLoadFromDatabase', [ $this, &$s ] );
1226 if ( $s !== false ) {
1227 // Initialise user table data
1228 $this->loadFromRow( $s );
1229 $this->mGroups
= null; // deferred
1230 $this->getEditCount(); // revalidation for nulls
1235 $this->loadDefaults();
1241 * Initialize this object from a row from the user table.
1243 * @param stdClass $row Row from the user table to load.
1244 * @param array $data Further user data to load into the object
1246 * user_groups Array with groups out of the user_groups table
1247 * user_properties Array with properties out of the user_properties table
1249 protected function loadFromRow( $row, $data = null ) {
1252 $this->mGroups
= null; // deferred
1254 if ( isset( $row->user_name
) ) {
1255 $this->mName
= $row->user_name
;
1256 $this->mFrom
= 'name';
1257 $this->setItemLoaded( 'name' );
1262 if ( isset( $row->user_real_name
) ) {
1263 $this->mRealName
= $row->user_real_name
;
1264 $this->setItemLoaded( 'realname' );
1269 if ( isset( $row->user_id
) ) {
1270 $this->mId
= intval( $row->user_id
);
1271 $this->mFrom
= 'id';
1272 $this->setItemLoaded( 'id' );
1277 if ( isset( $row->user_id
) && isset( $row->user_name
) ) {
1278 self
::$idCacheByName[$row->user_name
] = $row->user_id
;
1281 if ( isset( $row->user_editcount
) ) {
1282 $this->mEditCount
= $row->user_editcount
;
1287 if ( isset( $row->user_touched
) ) {
1288 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1293 if ( isset( $row->user_token
) ) {
1294 // The definition for the column is binary(32), so trim the NULs
1295 // that appends. The previous definition was char(32), so trim
1297 $this->mToken
= rtrim( $row->user_token
, " \0" );
1298 if ( $this->mToken
=== '' ) {
1299 $this->mToken
= null;
1305 if ( isset( $row->user_email
) ) {
1306 $this->mEmail
= $row->user_email
;
1307 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1308 $this->mEmailToken
= $row->user_email_token
;
1309 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1310 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1316 $this->mLoadedItems
= true;
1319 if ( is_array( $data ) ) {
1320 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1321 $this->mGroups
= $data['user_groups'];
1323 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1324 $this->loadOptions( $data['user_properties'] );
1330 * Load the data for this user object from another user object.
1334 protected function loadFromUserObject( $user ) {
1336 $user->loadGroups();
1337 $user->loadOptions();
1338 foreach ( self
::$mCacheVars as $var ) {
1339 $this->$var = $user->$var;
1344 * Load the groups from the database if they aren't already loaded.
1346 private function loadGroups() {
1347 if ( is_null( $this->mGroups
) ) {
1348 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
1349 ?
wfGetDB( DB_MASTER
)
1350 : wfGetDB( DB_SLAVE
);
1351 $res = $db->select( 'user_groups',
1353 [ 'ug_user' => $this->mId
],
1355 $this->mGroups
= [];
1356 foreach ( $res as $row ) {
1357 $this->mGroups
[] = $row->ug_group
;
1363 * Add the user to the group if he/she meets given criteria.
1365 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1366 * possible to remove manually via Special:UserRights. In such case it
1367 * will not be re-added automatically. The user will also not lose the
1368 * group if they no longer meet the criteria.
1370 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1372 * @return array Array of groups the user has been promoted to.
1374 * @see $wgAutopromoteOnce
1376 public function addAutopromoteOnceGroups( $event ) {
1377 global $wgAutopromoteOnceLogInRC, $wgAuth;
1379 if ( wfReadOnly() ||
!$this->getId() ) {
1383 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1384 if ( !count( $toPromote ) ) {
1388 if ( !$this->checkAndSetTouched() ) {
1389 return []; // raced out (bug T48834)
1392 $oldGroups = $this->getGroups(); // previous groups
1393 foreach ( $toPromote as $group ) {
1394 $this->addGroup( $group );
1396 // update groups in external authentication database
1397 Hooks
::run( 'UserGroupsChanged', [ $this, $toPromote, [], false, false ] );
1398 $wgAuth->updateExternalDBGroups( $this, $toPromote );
1400 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1402 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1403 $logEntry->setPerformer( $this );
1404 $logEntry->setTarget( $this->getUserPage() );
1405 $logEntry->setParameters( [
1406 '4::oldgroups' => $oldGroups,
1407 '5::newgroups' => $newGroups,
1409 $logid = $logEntry->insert();
1410 if ( $wgAutopromoteOnceLogInRC ) {
1411 $logEntry->publish( $logid );
1418 * Bump user_touched if it didn't change since this object was loaded
1420 * On success, the mTouched field is updated.
1421 * The user serialization cache is always cleared.
1423 * @return bool Whether user_touched was actually updated
1426 protected function checkAndSetTouched() {
1429 if ( !$this->mId
) {
1430 return false; // anon
1433 // Get a new user_touched that is higher than the old one
1434 $oldTouched = $this->mTouched
;
1435 $newTouched = $this->newTouchedTimestamp();
1437 $dbw = wfGetDB( DB_MASTER
);
1438 $dbw->update( 'user',
1439 [ 'user_touched' => $dbw->timestamp( $newTouched ) ],
1441 'user_id' => $this->mId
,
1442 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
1446 $success = ( $dbw->affectedRows() > 0 );
1449 $this->mTouched
= $newTouched;
1450 $this->clearSharedCache();
1452 // Clears on failure too since that is desired if the cache is stale
1453 $this->clearSharedCache( 'refresh' );
1460 * Clear various cached data stored in this object. The cache of the user table
1461 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1463 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1464 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1466 public function clearInstanceCache( $reloadFrom = false ) {
1467 $this->mNewtalk
= -1;
1468 $this->mDatePreference
= null;
1469 $this->mBlockedby
= -1; # Unset
1470 $this->mHash
= false;
1471 $this->mRights
= null;
1472 $this->mEffectiveGroups
= null;
1473 $this->mImplicitGroups
= null;
1474 $this->mGroups
= null;
1475 $this->mOptions
= null;
1476 $this->mOptionsLoaded
= false;
1477 $this->mEditCount
= null;
1479 if ( $reloadFrom ) {
1480 $this->mLoadedItems
= [];
1481 $this->mFrom
= $reloadFrom;
1486 * Combine the language default options with any site-specific options
1487 * and add the default language variants.
1489 * @return array Array of String options
1491 public static function getDefaultOptions() {
1492 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1494 static $defOpt = null;
1495 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1496 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1497 // mid-request and see that change reflected in the return value of this function.
1498 // Which is insane and would never happen during normal MW operation
1502 $defOpt = $wgDefaultUserOptions;
1503 // Default language setting
1504 $defOpt['language'] = $wgContLang->getCode();
1505 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1506 $defOpt[$langCode == $wgContLang->getCode() ?
'variant' : "variant-$langCode"] = $langCode;
1508 foreach ( SearchEngine
::searchableNamespaces() as $nsnum => $nsname ) {
1509 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1511 $defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1513 Hooks
::run( 'UserGetDefaultOptions', [ &$defOpt ] );
1519 * Get a given default option value.
1521 * @param string $opt Name of option to retrieve
1522 * @return string Default option value
1524 public static function getDefaultOption( $opt ) {
1525 $defOpts = self
::getDefaultOptions();
1526 if ( isset( $defOpts[$opt] ) ) {
1527 return $defOpts[$opt];
1534 * Get blocking information
1535 * @param bool $bFromSlave Whether to check the slave database first.
1536 * To improve performance, non-critical checks are done against slaves.
1537 * Check when actually saving should be done against master.
1539 private function getBlockedStatus( $bFromSlave = true ) {
1540 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1542 if ( -1 != $this->mBlockedby
) {
1546 wfDebug( __METHOD__
. ": checking...\n" );
1548 // Initialize data...
1549 // Otherwise something ends up stomping on $this->mBlockedby when
1550 // things get lazy-loaded later, causing false positive block hits
1551 // due to -1 !== 0. Probably session-related... Nothing should be
1552 // overwriting mBlockedby, surely?
1555 # We only need to worry about passing the IP address to the Block generator if the
1556 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1557 # know which IP address they're actually coming from
1559 if ( !$this->isAllowed( 'ipblock-exempt' ) ) {
1560 // $wgUser->getName() only works after the end of Setup.php. Until
1561 // then, assume it's a logged-out user.
1562 $globalUserName = $wgUser->isSafeToLoad()
1563 ?
$wgUser->getName()
1564 : IP
::sanitizeIP( $wgUser->getRequest()->getIP() );
1565 if ( $this->getName() === $globalUserName ) {
1566 $ip = $this->getRequest()->getIP();
1571 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1574 if ( !$block instanceof Block
&& $ip !== null && !in_array( $ip, $wgProxyWhitelist ) ) {
1576 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1578 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1579 $block->mReason
= wfMessage( 'proxyblockreason' )->text();
1580 $block->setTarget( $ip );
1581 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1583 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1584 $block->mReason
= wfMessage( 'sorbsreason' )->text();
1585 $block->setTarget( $ip );
1589 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1590 if ( !$block instanceof Block
1591 && $wgApplyIpBlocksToXff
1593 && !in_array( $ip, $wgProxyWhitelist )
1595 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1596 $xff = array_map( 'trim', explode( ',', $xff ) );
1597 $xff = array_diff( $xff, [ $ip ] );
1598 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1599 $block = Block
::chooseBlock( $xffblocks, $xff );
1600 if ( $block instanceof Block
) {
1601 # Mangle the reason to alert the user that the block
1602 # originated from matching the X-Forwarded-For header.
1603 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->text();
1607 if ( $block instanceof Block
) {
1608 wfDebug( __METHOD__
. ": Found block.\n" );
1609 $this->mBlock
= $block;
1610 $this->mBlockedby
= $block->getByName();
1611 $this->mBlockreason
= $block->mReason
;
1612 $this->mHideName
= $block->mHideName
;
1613 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1615 $this->mBlockedby
= '';
1616 $this->mHideName
= 0;
1617 $this->mAllowUsertalk
= false;
1621 Hooks
::run( 'GetBlockedStatus', [ &$this ] );
1626 * Whether the given IP is in a DNS blacklist.
1628 * @param string $ip IP to check
1629 * @param bool $checkWhitelist Whether to check the whitelist first
1630 * @return bool True if blacklisted.
1632 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1633 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1635 if ( !$wgEnableDnsBlacklist ) {
1639 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1643 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1647 * Whether the given IP is in a given DNS blacklist.
1649 * @param string $ip IP to check
1650 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1651 * @return bool True if blacklisted.
1653 public function inDnsBlacklist( $ip, $bases ) {
1656 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1657 if ( IP
::isIPv4( $ip ) ) {
1658 // Reverse IP, bug 21255
1659 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1661 foreach ( (array)$bases as $base ) {
1663 // If we have an access key, use that too (ProjectHoneypot, etc.)
1665 if ( is_array( $base ) ) {
1666 if ( count( $base ) >= 2 ) {
1667 // Access key is 1, base URL is 0
1668 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1670 $host = "$ipReversed.{$base[0]}";
1672 $basename = $base[0];
1674 $host = "$ipReversed.$base";
1678 $ipList = gethostbynamel( $host );
1681 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
1685 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
1694 * Check if an IP address is in the local proxy list
1700 public static function isLocallyBlockedProxy( $ip ) {
1701 global $wgProxyList;
1703 if ( !$wgProxyList ) {
1707 if ( !is_array( $wgProxyList ) ) {
1708 // Load from the specified file
1709 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1712 if ( !is_array( $wgProxyList ) ) {
1714 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1716 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1717 // Old-style flipped proxy list
1726 * Is this user subject to rate limiting?
1728 * @return bool True if rate limited
1730 public function isPingLimitable() {
1731 global $wgRateLimitsExcludedIPs;
1732 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1733 // No other good way currently to disable rate limits
1734 // for specific IPs. :P
1735 // But this is a crappy hack and should die.
1738 return !$this->isAllowed( 'noratelimit' );
1742 * Primitive rate limits: enforce maximum actions per time period
1743 * to put a brake on flooding.
1745 * The method generates both a generic profiling point and a per action one
1746 * (suffix being "-$action".
1748 * @note When using a shared cache like memcached, IP-address
1749 * last-hit counters will be shared across wikis.
1751 * @param string $action Action to enforce; 'edit' if unspecified
1752 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1753 * @return bool True if a rate limiter was tripped
1755 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1756 // Call the 'PingLimiter' hook
1758 if ( !Hooks
::run( 'PingLimiter', [ &$this, $action, &$result, $incrBy ] ) ) {
1762 global $wgRateLimits;
1763 if ( !isset( $wgRateLimits[$action] ) ) {
1767 // Some groups shouldn't trigger the ping limiter, ever
1768 if ( !$this->isPingLimitable() ) {
1772 $limits = $wgRateLimits[$action];
1774 $id = $this->getId();
1776 $isNewbie = $this->isNewbie();
1780 if ( isset( $limits['anon'] ) ) {
1781 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1784 // limits for logged-in users
1785 if ( isset( $limits['user'] ) ) {
1786 $userLimit = $limits['user'];
1788 // limits for newbie logged-in users
1789 if ( $isNewbie && isset( $limits['newbie'] ) ) {
1790 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1794 // limits for anons and for newbie logged-in users
1797 if ( isset( $limits['ip'] ) ) {
1798 $ip = $this->getRequest()->getIP();
1799 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1801 // subnet-based limits
1802 if ( isset( $limits['subnet'] ) ) {
1803 $ip = $this->getRequest()->getIP();
1804 $subnet = IP
::getSubnet( $ip );
1805 if ( $subnet !== false ) {
1806 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1811 // Check for group-specific permissions
1812 // If more than one group applies, use the group with the highest limit ratio (max/period)
1813 foreach ( $this->getGroups() as $group ) {
1814 if ( isset( $limits[$group] ) ) {
1815 if ( $userLimit === false
1816 ||
$limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1818 $userLimit = $limits[$group];
1823 // Set the user limit key
1824 if ( $userLimit !== false ) {
1825 list( $max, $period ) = $userLimit;
1826 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
1827 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1830 // ip-based limits for all ping-limitable users
1831 if ( isset( $limits['ip-all'] ) ) {
1832 $ip = $this->getRequest()->getIP();
1833 // ignore if user limit is more permissive
1834 if ( $isNewbie ||
$userLimit === false
1835 ||
$limits['ip-all'][0] / $limits['ip-all'][1] > $userLimit[0] / $userLimit[1] ) {
1836 $keys["mediawiki:limiter:$action:ip-all:$ip"] = $limits['ip-all'];
1840 // subnet-based limits for all ping-limitable users
1841 if ( isset( $limits['subnet-all'] ) ) {
1842 $ip = $this->getRequest()->getIP();
1843 $subnet = IP
::getSubnet( $ip );
1844 if ( $subnet !== false ) {
1845 // ignore if user limit is more permissive
1846 if ( $isNewbie ||
$userLimit === false
1847 ||
$limits['ip-all'][0] / $limits['ip-all'][1]
1848 > $userLimit[0] / $userLimit[1] ) {
1849 $keys["mediawiki:limiter:$action:subnet-all:$subnet"] = $limits['subnet-all'];
1854 $cache = ObjectCache
::getLocalClusterInstance();
1857 foreach ( $keys as $key => $limit ) {
1858 list( $max, $period ) = $limit;
1859 $summary = "(limit $max in {$period}s)";
1860 $count = $cache->get( $key );
1863 if ( $count >= $max ) {
1864 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1865 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1868 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1871 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1872 if ( $incrBy > 0 ) {
1873 $cache->add( $key, 0, intval( $period ) ); // first ping
1876 if ( $incrBy > 0 ) {
1877 $cache->incr( $key, $incrBy );
1885 * Check if user is blocked
1887 * @param bool $bFromSlave Whether to check the slave database instead of
1888 * the master. Hacked from false due to horrible probs on site.
1889 * @return bool True if blocked, false otherwise
1891 public function isBlocked( $bFromSlave = true ) {
1892 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
1896 * Get the block affecting the user, or null if the user is not blocked
1898 * @param bool $bFromSlave Whether to check the slave database instead of the master
1899 * @return Block|null
1901 public function getBlock( $bFromSlave = true ) {
1902 $this->getBlockedStatus( $bFromSlave );
1903 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
1907 * Check if user is blocked from editing a particular article
1909 * @param Title $title Title to check
1910 * @param bool $bFromSlave Whether to check the slave database instead of the master
1913 public function isBlockedFrom( $title, $bFromSlave = false ) {
1914 global $wgBlockAllowsUTEdit;
1916 $blocked = $this->isBlocked( $bFromSlave );
1917 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
1918 // If a user's name is suppressed, they cannot make edits anywhere
1919 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName()
1920 && $title->getNamespace() == NS_USER_TALK
) {
1922 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
1925 Hooks
::run( 'UserIsBlockedFrom', [ $this, $title, &$blocked, &$allowUsertalk ] );
1931 * If user is blocked, return the name of the user who placed the block
1932 * @return string Name of blocker
1934 public function blockedBy() {
1935 $this->getBlockedStatus();
1936 return $this->mBlockedby
;
1940 * If user is blocked, return the specified reason for the block
1941 * @return string Blocking reason
1943 public function blockedFor() {
1944 $this->getBlockedStatus();
1945 return $this->mBlockreason
;
1949 * If user is blocked, return the ID for the block
1950 * @return int Block ID
1952 public function getBlockId() {
1953 $this->getBlockedStatus();
1954 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
1958 * Check if user is blocked on all wikis.
1959 * Do not use for actual edit permission checks!
1960 * This is intended for quick UI checks.
1962 * @param string $ip IP address, uses current client if none given
1963 * @return bool True if blocked, false otherwise
1965 public function isBlockedGlobally( $ip = '' ) {
1966 if ( $this->mBlockedGlobally
!== null ) {
1967 return $this->mBlockedGlobally
;
1969 // User is already an IP?
1970 if ( IP
::isIPAddress( $this->getName() ) ) {
1971 $ip = $this->getName();
1973 $ip = $this->getRequest()->getIP();
1976 Hooks
::run( 'UserIsBlockedGlobally', [ &$this, $ip, &$blocked ] );
1977 $this->mBlockedGlobally
= (bool)$blocked;
1978 return $this->mBlockedGlobally
;
1982 * Check if user account is locked
1984 * @return bool True if locked, false otherwise
1986 public function isLocked() {
1987 if ( $this->mLocked
!== null ) {
1988 return $this->mLocked
;
1991 $authUser = $wgAuth->getUserInstance( $this );
1992 $this->mLocked
= (bool)$authUser->isLocked();
1993 Hooks
::run( 'UserIsLocked', [ $this, &$this->mLocked
] );
1994 return $this->mLocked
;
1998 * Check if user account is hidden
2000 * @return bool True if hidden, false otherwise
2002 public function isHidden() {
2003 if ( $this->mHideName
!== null ) {
2004 return $this->mHideName
;
2006 $this->getBlockedStatus();
2007 if ( !$this->mHideName
) {
2009 $authUser = $wgAuth->getUserInstance( $this );
2010 $this->mHideName
= (bool)$authUser->isHidden();
2011 Hooks
::run( 'UserIsHidden', [ $this, &$this->mHideName
] );
2013 return $this->mHideName
;
2017 * Get the user's ID.
2018 * @return int The user's ID; 0 if the user is anonymous or nonexistent
2020 public function getId() {
2021 if ( $this->mId
=== null && $this->mName
!== null && User
::isIP( $this->mName
) ) {
2022 // Special case, we know the user is anonymous
2024 } elseif ( !$this->isItemLoaded( 'id' ) ) {
2025 // Don't load if this was initialized from an ID
2032 * Set the user and reload all fields according to a given ID
2033 * @param int $v User ID to reload
2035 public function setId( $v ) {
2037 $this->clearInstanceCache( 'id' );
2041 * Get the user name, or the IP of an anonymous user
2042 * @return string User's name or IP address
2044 public function getName() {
2045 if ( $this->isItemLoaded( 'name', 'only' ) ) {
2046 // Special case optimisation
2047 return $this->mName
;
2050 if ( $this->mName
=== false ) {
2052 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
2054 return $this->mName
;
2059 * Set the user name.
2061 * This does not reload fields from the database according to the given
2062 * name. Rather, it is used to create a temporary "nonexistent user" for
2063 * later addition to the database. It can also be used to set the IP
2064 * address for an anonymous user to something other than the current
2067 * @note User::newFromName() has roughly the same function, when the named user
2069 * @param string $str New user name to set
2071 public function setName( $str ) {
2073 $this->mName
= $str;
2077 * Get the user's name escaped by underscores.
2078 * @return string Username escaped by underscores.
2080 public function getTitleKey() {
2081 return str_replace( ' ', '_', $this->getName() );
2085 * Check if the user has new messages.
2086 * @return bool True if the user has new messages
2088 public function getNewtalk() {
2091 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2092 if ( $this->mNewtalk
=== -1 ) {
2093 $this->mNewtalk
= false; # reset talk page status
2095 // Check memcached separately for anons, who have no
2096 // entire User object stored in there.
2097 if ( !$this->mId
) {
2098 global $wgDisableAnonTalk;
2099 if ( $wgDisableAnonTalk ) {
2100 // Anon newtalk disabled by configuration.
2101 $this->mNewtalk
= false;
2103 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
2106 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2110 return (bool)$this->mNewtalk
;
2114 * Return the data needed to construct links for new talk page message
2115 * alerts. If there are new messages, this will return an associative array
2116 * with the following data:
2117 * wiki: The database name of the wiki
2118 * link: Root-relative link to the user's talk page
2119 * rev: The last talk page revision that the user has seen or null. This
2120 * is useful for building diff links.
2121 * If there are no new messages, it returns an empty array.
2122 * @note This function was designed to accomodate multiple talk pages, but
2123 * currently only returns a single link and revision.
2126 public function getNewMessageLinks() {
2128 if ( !Hooks
::run( 'UserRetrieveNewTalks', [ &$this, &$talks ] ) ) {
2130 } elseif ( !$this->getNewtalk() ) {
2133 $utp = $this->getTalkPage();
2134 $dbr = wfGetDB( DB_SLAVE
);
2135 // Get the "last viewed rev" timestamp from the oldest message notification
2136 $timestamp = $dbr->selectField( 'user_newtalk',
2137 'MIN(user_last_timestamp)',
2138 $this->isAnon() ?
[ 'user_ip' => $this->getName() ] : [ 'user_id' => $this->getID() ],
2140 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2141 return [ [ 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ] ];
2145 * Get the revision ID for the last talk page revision viewed by the talk
2147 * @return int|null Revision ID or null
2149 public function getNewMessageRevisionId() {
2150 $newMessageRevisionId = null;
2151 $newMessageLinks = $this->getNewMessageLinks();
2152 if ( $newMessageLinks ) {
2153 // Note: getNewMessageLinks() never returns more than a single link
2154 // and it is always for the same wiki, but we double-check here in
2155 // case that changes some time in the future.
2156 if ( count( $newMessageLinks ) === 1
2157 && $newMessageLinks[0]['wiki'] === wfWikiID()
2158 && $newMessageLinks[0]['rev']
2160 /** @var Revision $newMessageRevision */
2161 $newMessageRevision = $newMessageLinks[0]['rev'];
2162 $newMessageRevisionId = $newMessageRevision->getId();
2165 return $newMessageRevisionId;
2169 * Internal uncached check for new messages
2172 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2173 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2174 * @return bool True if the user has new messages
2176 protected function checkNewtalk( $field, $id ) {
2177 $dbr = wfGetDB( DB_SLAVE
);
2179 $ok = $dbr->selectField( 'user_newtalk', $field, [ $field => $id ], __METHOD__
);
2181 return $ok !== false;
2185 * Add or update the new messages flag
2186 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2187 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2188 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2189 * @return bool True if successful, false otherwise
2191 protected function updateNewtalk( $field, $id, $curRev = null ) {
2192 // Get timestamp of the talk page revision prior to the current one
2193 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2194 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2195 // Mark the user as having new messages since this revision
2196 $dbw = wfGetDB( DB_MASTER
);
2197 $dbw->insert( 'user_newtalk',
2198 [ $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ],
2201 if ( $dbw->affectedRows() ) {
2202 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2205 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2211 * Clear the new messages flag for the given user
2212 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2213 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2214 * @return bool True if successful, false otherwise
2216 protected function deleteNewtalk( $field, $id ) {
2217 $dbw = wfGetDB( DB_MASTER
);
2218 $dbw->delete( 'user_newtalk',
2221 if ( $dbw->affectedRows() ) {
2222 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2225 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2231 * Update the 'You have new messages!' status.
2232 * @param bool $val Whether the user has new messages
2233 * @param Revision $curRev New, as yet unseen revision of the user talk
2234 * page. Ignored if null or !$val.
2236 public function setNewtalk( $val, $curRev = null ) {
2237 if ( wfReadOnly() ) {
2242 $this->mNewtalk
= $val;
2244 if ( $this->isAnon() ) {
2246 $id = $this->getName();
2249 $id = $this->getId();
2253 $changed = $this->updateNewtalk( $field, $id, $curRev );
2255 $changed = $this->deleteNewtalk( $field, $id );
2259 $this->invalidateCache();
2264 * Generate a current or new-future timestamp to be stored in the
2265 * user_touched field when we update things.
2266 * @return string Timestamp in TS_MW format
2268 private function newTouchedTimestamp() {
2269 global $wgClockSkewFudge;
2271 $time = wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2272 if ( $this->mTouched
&& $time <= $this->mTouched
) {
2273 $time = wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $this->mTouched
) +
1 );
2280 * Clear user data from memcached
2282 * Use after applying updates to the database; caller's
2283 * responsibility to update user_touched if appropriate.
2285 * Called implicitly from invalidateCache() and saveSettings().
2287 * @param string $mode Use 'refresh' to clear now; otherwise before DB commit
2289 public function clearSharedCache( $mode = 'changed' ) {
2290 if ( !$this->getId() ) {
2294 $cache = ObjectCache
::getMainWANInstance();
2295 $key = $this->getCacheKey( $cache );
2296 if ( $mode === 'refresh' ) {
2297 $cache->delete( $key, 1 );
2299 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle( function() use ( $cache, $key ) {
2300 $cache->delete( $key );
2306 * Immediately touch the user data cache for this account
2308 * Calls touch() and removes account data from memcached
2310 public function invalidateCache() {
2312 $this->clearSharedCache();
2316 * Update the "touched" timestamp for the user
2318 * This is useful on various login/logout events when making sure that
2319 * a browser or proxy that has multiple tenants does not suffer cache
2320 * pollution where the new user sees the old users content. The value
2321 * of getTouched() is checked when determining 304 vs 200 responses.
2322 * Unlike invalidateCache(), this preserves the User object cache and
2323 * avoids database writes.
2327 public function touch() {
2328 $id = $this->getId();
2330 $key = wfMemcKey( 'user-quicktouched', 'id', $id );
2331 ObjectCache
::getMainWANInstance()->touchCheckKey( $key );
2332 $this->mQuickTouched
= null;
2337 * Validate the cache for this account.
2338 * @param string $timestamp A timestamp in TS_MW format
2341 public function validateCache( $timestamp ) {
2342 return ( $timestamp >= $this->getTouched() );
2346 * Get the user touched timestamp
2348 * Use this value only to validate caches via inequalities
2349 * such as in the case of HTTP If-Modified-Since response logic
2351 * @return string TS_MW Timestamp
2353 public function getTouched() {
2357 if ( $this->mQuickTouched
=== null ) {
2358 $key = wfMemcKey( 'user-quicktouched', 'id', $this->mId
);
2359 $cache = ObjectCache
::getMainWANInstance();
2361 $this->mQuickTouched
= wfTimestamp( TS_MW
, $cache->getCheckKeyTime( $key ) );
2364 return max( $this->mTouched
, $this->mQuickTouched
);
2367 return $this->mTouched
;
2371 * Get the user_touched timestamp field (time of last DB updates)
2372 * @return string TS_MW Timestamp
2375 public function getDBTouched() {
2378 return $this->mTouched
;
2382 * @deprecated Removed in 1.27.
2386 public function getPassword() {
2387 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2391 * @deprecated Removed in 1.27.
2395 public function getTemporaryPassword() {
2396 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2400 * Set the password and reset the random token.
2401 * Calls through to authentication plugin if necessary;
2402 * will have no effect if the auth plugin refuses to
2403 * pass the change through or if the legal password
2406 * As a special case, setting the password to null
2407 * wipes it, so the account cannot be logged in until
2408 * a new password is set, for instance via e-mail.
2410 * @deprecated since 1.27. AuthManager is coming.
2411 * @param string $str New password to set
2412 * @throws PasswordError On failure
2415 public function setPassword( $str ) {
2418 if ( $str !== null ) {
2419 if ( !$wgAuth->allowPasswordChange() ) {
2420 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2423 $status = $this->checkPasswordValidity( $str );
2424 if ( !$status->isGood() ) {
2425 throw new PasswordError( $status->getMessage()->text() );
2429 if ( !$wgAuth->setPassword( $this, $str ) ) {
2430 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2434 $this->setOption( 'watchlisttoken', false );
2435 $this->setPasswordInternal( $str );
2441 * Set the password and reset the random token unconditionally.
2443 * @deprecated since 1.27. AuthManager is coming.
2444 * @param string|null $str New password to set or null to set an invalid
2445 * password hash meaning that the user will not be able to log in
2446 * through the web interface.
2448 public function setInternalPassword( $str ) {
2451 if ( $wgAuth->allowSetLocalPassword() ) {
2453 $this->setOption( 'watchlisttoken', false );
2454 $this->setPasswordInternal( $str );
2459 * Actually set the password and such
2460 * @since 1.27 cannot set a password for a user not in the database
2461 * @param string|null $str New password to set or null to set an invalid
2462 * password hash meaning that the user will not be able to log in
2463 * through the web interface.
2465 private function setPasswordInternal( $str ) {
2466 $id = self
::idFromName( $this->getName(), self
::READ_LATEST
);
2468 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2471 $passwordFactory = new PasswordFactory();
2472 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
2473 $dbw = wfGetDB( DB_MASTER
);
2477 'user_password' => $passwordFactory->newFromPlaintext( $str )->toString(),
2478 'user_newpassword' => PasswordFactory
::newInvalidPassword()->toString(),
2479 'user_newpass_time' => $dbw->timestampOrNull( null ),
2487 // When the main password is changed, invalidate all bot passwords too
2488 BotPassword
::invalidateAllPasswordsForUser( $this->getName() );
2492 * Get the user's current token.
2493 * @param bool $forceCreation Force the generation of a new token if the
2494 * user doesn't have one (default=true for backwards compatibility).
2495 * @return string|null Token
2497 public function getToken( $forceCreation = true ) {
2498 global $wgAuthenticationTokenVersion;
2501 if ( !$this->mToken
&& $forceCreation ) {
2505 if ( !$this->mToken
) {
2506 // The user doesn't have a token, return null to indicate that.
2508 } elseif ( $this->mToken
=== self
::INVALID_TOKEN
) {
2509 // We return a random value here so existing token checks are very
2511 return MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2512 } elseif ( $wgAuthenticationTokenVersion === null ) {
2513 // $wgAuthenticationTokenVersion not in use, so return the raw secret
2514 return $this->mToken
;
2516 // $wgAuthenticationTokenVersion in use, so hmac it.
2517 $ret = MWCryptHash
::hmac( $wgAuthenticationTokenVersion, $this->mToken
, false );
2519 // The raw hash can be overly long. Shorten it up.
2520 $len = max( 32, self
::TOKEN_LENGTH
);
2521 if ( strlen( $ret ) < $len ) {
2522 // Should never happen, even md5 is 128 bits
2523 throw new \
UnexpectedValueException( 'Hmac returned less than 128 bits' );
2525 return substr( $ret, -$len );
2530 * Set the random token (used for persistent authentication)
2531 * Called from loadDefaults() among other places.
2533 * @param string|bool $token If specified, set the token to this value
2535 public function setToken( $token = false ) {
2537 if ( $this->mToken
=== self
::INVALID_TOKEN
) {
2538 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
2539 ->debug( __METHOD__
. ": Ignoring attempt to set token for system user \"$this\"" );
2540 } elseif ( !$token ) {
2541 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2543 $this->mToken
= $token;
2548 * Set the password for a password reminder or new account email
2550 * @deprecated since 1.27, AuthManager is coming
2551 * @param string $str New password to set or null to set an invalid
2552 * password hash meaning that the user will not be able to use it
2553 * @param bool $throttle If true, reset the throttle timestamp to the present
2555 public function setNewpassword( $str, $throttle = true ) {
2556 $id = $this->getId();
2558 throw new LogicException( 'Cannot set new password for a user that is not in the database.' );
2561 $dbw = wfGetDB( DB_MASTER
);
2563 $passwordFactory = new PasswordFactory();
2564 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
2566 'user_newpassword' => $passwordFactory->newFromPlaintext( $str )->toString(),
2569 if ( $str === null ) {
2570 $update['user_newpass_time'] = null;
2571 } elseif ( $throttle ) {
2572 $update['user_newpass_time'] = $dbw->timestamp();
2575 $dbw->update( 'user', $update, [ 'user_id' => $id ], __METHOD__
);
2579 * Has password reminder email been sent within the last
2580 * $wgPasswordReminderResendTime hours?
2583 public function isPasswordReminderThrottled() {
2584 global $wgPasswordReminderResendTime;
2586 if ( !$wgPasswordReminderResendTime ) {
2592 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
2593 ?
wfGetDB( DB_MASTER
)
2594 : wfGetDB( DB_SLAVE
);
2595 $newpassTime = $db->selectField(
2597 'user_newpass_time',
2598 [ 'user_id' => $this->getId() ],
2602 if ( $newpassTime === null ) {
2605 $expiry = wfTimestamp( TS_UNIX
, $newpassTime ) +
$wgPasswordReminderResendTime * 3600;
2606 return time() < $expiry;
2610 * Get the user's e-mail address
2611 * @return string User's email address
2613 public function getEmail() {
2615 Hooks
::run( 'UserGetEmail', [ $this, &$this->mEmail
] );
2616 return $this->mEmail
;
2620 * Get the timestamp of the user's e-mail authentication
2621 * @return string TS_MW timestamp
2623 public function getEmailAuthenticationTimestamp() {
2625 Hooks
::run( 'UserGetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
2626 return $this->mEmailAuthenticated
;
2630 * Set the user's e-mail address
2631 * @param string $str New e-mail address
2633 public function setEmail( $str ) {
2635 if ( $str == $this->mEmail
) {
2638 $this->invalidateEmail();
2639 $this->mEmail
= $str;
2640 Hooks
::run( 'UserSetEmail', [ $this, &$this->mEmail
] );
2644 * Set the user's e-mail address and a confirmation mail if needed.
2647 * @param string $str New e-mail address
2650 public function setEmailWithConfirmation( $str ) {
2651 global $wgEnableEmail, $wgEmailAuthentication;
2653 if ( !$wgEnableEmail ) {
2654 return Status
::newFatal( 'emaildisabled' );
2657 $oldaddr = $this->getEmail();
2658 if ( $str === $oldaddr ) {
2659 return Status
::newGood( true );
2662 $this->setEmail( $str );
2664 if ( $str !== '' && $wgEmailAuthentication ) {
2665 // Send a confirmation request to the new address if needed
2666 $type = $oldaddr != '' ?
'changed' : 'set';
2667 $result = $this->sendConfirmationMail( $type );
2668 if ( $result->isGood() ) {
2669 // Say to the caller that a confirmation mail has been sent
2670 $result->value
= 'eauth';
2673 $result = Status
::newGood( true );
2680 * Get the user's real name
2681 * @return string User's real name
2683 public function getRealName() {
2684 if ( !$this->isItemLoaded( 'realname' ) ) {
2688 return $this->mRealName
;
2692 * Set the user's real name
2693 * @param string $str New real name
2695 public function setRealName( $str ) {
2697 $this->mRealName
= $str;
2701 * Get the user's current setting for a given option.
2703 * @param string $oname The option to check
2704 * @param string $defaultOverride A default value returned if the option does not exist
2705 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2706 * @return string User's current value for the option
2707 * @see getBoolOption()
2708 * @see getIntOption()
2710 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2711 global $wgHiddenPrefs;
2712 $this->loadOptions();
2714 # We want 'disabled' preferences to always behave as the default value for
2715 # users, even if they have set the option explicitly in their settings (ie they
2716 # set it, and then it was disabled removing their ability to change it). But
2717 # we don't want to erase the preferences in the database in case the preference
2718 # is re-enabled again. So don't touch $mOptions, just override the returned value
2719 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2720 return self
::getDefaultOption( $oname );
2723 if ( array_key_exists( $oname, $this->mOptions
) ) {
2724 return $this->mOptions
[$oname];
2726 return $defaultOverride;
2731 * Get all user's options
2733 * @param int $flags Bitwise combination of:
2734 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2735 * to the default value. (Since 1.25)
2738 public function getOptions( $flags = 0 ) {
2739 global $wgHiddenPrefs;
2740 $this->loadOptions();
2741 $options = $this->mOptions
;
2743 # We want 'disabled' preferences to always behave as the default value for
2744 # users, even if they have set the option explicitly in their settings (ie they
2745 # set it, and then it was disabled removing their ability to change it). But
2746 # we don't want to erase the preferences in the database in case the preference
2747 # is re-enabled again. So don't touch $mOptions, just override the returned value
2748 foreach ( $wgHiddenPrefs as $pref ) {
2749 $default = self
::getDefaultOption( $pref );
2750 if ( $default !== null ) {
2751 $options[$pref] = $default;
2755 if ( $flags & self
::GETOPTIONS_EXCLUDE_DEFAULTS
) {
2756 $options = array_diff_assoc( $options, self
::getDefaultOptions() );
2763 * Get the user's current setting for a given option, as a boolean value.
2765 * @param string $oname The option to check
2766 * @return bool User's current value for the option
2769 public function getBoolOption( $oname ) {
2770 return (bool)$this->getOption( $oname );
2774 * Get the user's current setting for a given option, as an integer value.
2776 * @param string $oname The option to check
2777 * @param int $defaultOverride A default value returned if the option does not exist
2778 * @return int User's current value for the option
2781 public function getIntOption( $oname, $defaultOverride = 0 ) {
2782 $val = $this->getOption( $oname );
2784 $val = $defaultOverride;
2786 return intval( $val );
2790 * Set the given option for a user.
2792 * You need to call saveSettings() to actually write to the database.
2794 * @param string $oname The option to set
2795 * @param mixed $val New value to set
2797 public function setOption( $oname, $val ) {
2798 $this->loadOptions();
2800 // Explicitly NULL values should refer to defaults
2801 if ( is_null( $val ) ) {
2802 $val = self
::getDefaultOption( $oname );
2805 $this->mOptions
[$oname] = $val;
2809 * Get a token stored in the preferences (like the watchlist one),
2810 * resetting it if it's empty (and saving changes).
2812 * @param string $oname The option name to retrieve the token from
2813 * @return string|bool User's current value for the option, or false if this option is disabled.
2814 * @see resetTokenFromOption()
2816 * @deprecated 1.26 Applications should use the OAuth extension
2818 public function getTokenFromOption( $oname ) {
2819 global $wgHiddenPrefs;
2821 $id = $this->getId();
2822 if ( !$id ||
in_array( $oname, $wgHiddenPrefs ) ) {
2826 $token = $this->getOption( $oname );
2828 // Default to a value based on the user token to avoid space
2829 // wasted on storing tokens for all users. When this option
2830 // is set manually by the user, only then is it stored.
2831 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
2838 * Reset a token stored in the preferences (like the watchlist one).
2839 * *Does not* save user's preferences (similarly to setOption()).
2841 * @param string $oname The option name to reset the token in
2842 * @return string|bool New token value, or false if this option is disabled.
2843 * @see getTokenFromOption()
2846 public function resetTokenFromOption( $oname ) {
2847 global $wgHiddenPrefs;
2848 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2852 $token = MWCryptRand
::generateHex( 40 );
2853 $this->setOption( $oname, $token );
2858 * Return a list of the types of user options currently returned by
2859 * User::getOptionKinds().
2861 * Currently, the option kinds are:
2862 * - 'registered' - preferences which are registered in core MediaWiki or
2863 * by extensions using the UserGetDefaultOptions hook.
2864 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2865 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2866 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2867 * be used by user scripts.
2868 * - 'special' - "preferences" that are not accessible via User::getOptions
2869 * or User::setOptions.
2870 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2871 * These are usually legacy options, removed in newer versions.
2873 * The API (and possibly others) use this function to determine the possible
2874 * option types for validation purposes, so make sure to update this when a
2875 * new option kind is added.
2877 * @see User::getOptionKinds
2878 * @return array Option kinds
2880 public static function listOptionKinds() {
2883 'registered-multiselect',
2884 'registered-checkmatrix',
2892 * Return an associative array mapping preferences keys to the kind of a preference they're
2893 * used for. Different kinds are handled differently when setting or reading preferences.
2895 * See User::listOptionKinds for the list of valid option types that can be provided.
2897 * @see User::listOptionKinds
2898 * @param IContextSource $context
2899 * @param array $options Assoc. array with options keys to check as keys.
2900 * Defaults to $this->mOptions.
2901 * @return array The key => kind mapping data
2903 public function getOptionKinds( IContextSource
$context, $options = null ) {
2904 $this->loadOptions();
2905 if ( $options === null ) {
2906 $options = $this->mOptions
;
2909 $prefs = Preferences
::getPreferences( $this, $context );
2912 // Pull out the "special" options, so they don't get converted as
2913 // multiselect or checkmatrix.
2914 $specialOptions = array_fill_keys( Preferences
::getSaveBlacklist(), true );
2915 foreach ( $specialOptions as $name => $value ) {
2916 unset( $prefs[$name] );
2919 // Multiselect and checkmatrix options are stored in the database with
2920 // one key per option, each having a boolean value. Extract those keys.
2921 $multiselectOptions = [];
2922 foreach ( $prefs as $name => $info ) {
2923 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2924 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2925 $opts = HTMLFormField
::flattenOptions( $info['options'] );
2926 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2928 foreach ( $opts as $value ) {
2929 $multiselectOptions["$prefix$value"] = true;
2932 unset( $prefs[$name] );
2935 $checkmatrixOptions = [];
2936 foreach ( $prefs as $name => $info ) {
2937 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2938 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2939 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
2940 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
2941 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2943 foreach ( $columns as $column ) {
2944 foreach ( $rows as $row ) {
2945 $checkmatrixOptions["$prefix$column-$row"] = true;
2949 unset( $prefs[$name] );
2953 // $value is ignored
2954 foreach ( $options as $key => $value ) {
2955 if ( isset( $prefs[$key] ) ) {
2956 $mapping[$key] = 'registered';
2957 } elseif ( isset( $multiselectOptions[$key] ) ) {
2958 $mapping[$key] = 'registered-multiselect';
2959 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2960 $mapping[$key] = 'registered-checkmatrix';
2961 } elseif ( isset( $specialOptions[$key] ) ) {
2962 $mapping[$key] = 'special';
2963 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2964 $mapping[$key] = 'userjs';
2966 $mapping[$key] = 'unused';
2974 * Reset certain (or all) options to the site defaults
2976 * The optional parameter determines which kinds of preferences will be reset.
2977 * Supported values are everything that can be reported by getOptionKinds()
2978 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2980 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
2981 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2982 * for backwards-compatibility.
2983 * @param IContextSource|null $context Context source used when $resetKinds
2984 * does not contain 'all', passed to getOptionKinds().
2985 * Defaults to RequestContext::getMain() when null.
2987 public function resetOptions(
2988 $resetKinds = [ 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ],
2989 IContextSource
$context = null
2992 $defaultOptions = self
::getDefaultOptions();
2994 if ( !is_array( $resetKinds ) ) {
2995 $resetKinds = [ $resetKinds ];
2998 if ( in_array( 'all', $resetKinds ) ) {
2999 $newOptions = $defaultOptions;
3001 if ( $context === null ) {
3002 $context = RequestContext
::getMain();
3005 $optionKinds = $this->getOptionKinds( $context );
3006 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
3009 // Use default values for the options that should be deleted, and
3010 // copy old values for the ones that shouldn't.
3011 foreach ( $this->mOptions
as $key => $value ) {
3012 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
3013 if ( array_key_exists( $key, $defaultOptions ) ) {
3014 $newOptions[$key] = $defaultOptions[$key];
3017 $newOptions[$key] = $value;
3022 Hooks
::run( 'UserResetAllOptions', [ $this, &$newOptions, $this->mOptions
, $resetKinds ] );
3024 $this->mOptions
= $newOptions;
3025 $this->mOptionsLoaded
= true;
3029 * Get the user's preferred date format.
3030 * @return string User's preferred date format
3032 public function getDatePreference() {
3033 // Important migration for old data rows
3034 if ( is_null( $this->mDatePreference
) ) {
3036 $value = $this->getOption( 'date' );
3037 $map = $wgLang->getDatePreferenceMigrationMap();
3038 if ( isset( $map[$value] ) ) {
3039 $value = $map[$value];
3041 $this->mDatePreference
= $value;
3043 return $this->mDatePreference
;
3047 * Determine based on the wiki configuration and the user's options,
3048 * whether this user must be over HTTPS no matter what.
3052 public function requiresHTTPS() {
3053 global $wgSecureLogin;
3054 if ( !$wgSecureLogin ) {
3057 $https = $this->getBoolOption( 'prefershttps' );
3058 Hooks
::run( 'UserRequiresHTTPS', [ $this, &$https ] );
3060 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
3067 * Get the user preferred stub threshold
3071 public function getStubThreshold() {
3072 global $wgMaxArticleSize; # Maximum article size, in Kb
3073 $threshold = $this->getIntOption( 'stubthreshold' );
3074 if ( $threshold > $wgMaxArticleSize * 1024 ) {
3075 // If they have set an impossible value, disable the preference
3076 // so we can use the parser cache again.
3083 * Get the permissions this user has.
3084 * @return array Array of String permission names
3086 public function getRights() {
3087 if ( is_null( $this->mRights
) ) {
3088 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
3090 // Deny any rights denied by the user's session, unless this
3091 // endpoint has no sessions.
3092 if ( !defined( 'MW_NO_SESSION' ) ) {
3093 $allowedRights = $this->getRequest()->getSession()->getAllowedUserRights();
3094 if ( $allowedRights !== null ) {
3095 $this->mRights
= array_intersect( $this->mRights
, $allowedRights );
3099 Hooks
::run( 'UserGetRights', [ $this, &$this->mRights
] );
3100 // Force reindexation of rights when a hook has unset one of them
3101 $this->mRights
= array_values( array_unique( $this->mRights
) );
3103 return $this->mRights
;
3107 * Get the list of explicit group memberships this user has.
3108 * The implicit * and user groups are not included.
3109 * @return array Array of String internal group names
3111 public function getGroups() {
3113 $this->loadGroups();
3114 return $this->mGroups
;
3118 * Get the list of implicit group memberships this user has.
3119 * This includes all explicit groups, plus 'user' if logged in,
3120 * '*' for all accounts, and autopromoted groups
3121 * @param bool $recache Whether to avoid the cache
3122 * @return array Array of String internal group names
3124 public function getEffectiveGroups( $recache = false ) {
3125 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
3126 $this->mEffectiveGroups
= array_unique( array_merge(
3127 $this->getGroups(), // explicit groups
3128 $this->getAutomaticGroups( $recache ) // implicit groups
3130 // Hook for additional groups
3131 Hooks
::run( 'UserEffectiveGroups', [ &$this, &$this->mEffectiveGroups
] );
3132 // Force reindexation of groups when a hook has unset one of them
3133 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
3135 return $this->mEffectiveGroups
;
3139 * Get the list of implicit group memberships this user has.
3140 * This includes 'user' if logged in, '*' for all accounts,
3141 * and autopromoted groups
3142 * @param bool $recache Whether to avoid the cache
3143 * @return array Array of String internal group names
3145 public function getAutomaticGroups( $recache = false ) {
3146 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
3147 $this->mImplicitGroups
= [ '*' ];
3148 if ( $this->getId() ) {
3149 $this->mImplicitGroups
[] = 'user';
3151 $this->mImplicitGroups
= array_unique( array_merge(
3152 $this->mImplicitGroups
,
3153 Autopromote
::getAutopromoteGroups( $this )
3157 // Assure data consistency with rights/groups,
3158 // as getEffectiveGroups() depends on this function
3159 $this->mEffectiveGroups
= null;
3162 return $this->mImplicitGroups
;
3166 * Returns the groups the user has belonged to.
3168 * The user may still belong to the returned groups. Compare with getGroups().
3170 * The function will not return groups the user had belonged to before MW 1.17
3172 * @return array Names of the groups the user has belonged to.
3174 public function getFormerGroups() {
3177 if ( is_null( $this->mFormerGroups
) ) {
3178 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3179 ?
wfGetDB( DB_MASTER
)
3180 : wfGetDB( DB_SLAVE
);
3181 $res = $db->select( 'user_former_groups',
3183 [ 'ufg_user' => $this->mId
],
3185 $this->mFormerGroups
= [];
3186 foreach ( $res as $row ) {
3187 $this->mFormerGroups
[] = $row->ufg_group
;
3191 return $this->mFormerGroups
;
3195 * Get the user's edit count.
3196 * @return int|null Null for anonymous users
3198 public function getEditCount() {
3199 if ( !$this->getId() ) {
3203 if ( $this->mEditCount
=== null ) {
3204 /* Populate the count, if it has not been populated yet */
3205 $dbr = wfGetDB( DB_SLAVE
);
3206 // check if the user_editcount field has been initialized
3207 $count = $dbr->selectField(
3208 'user', 'user_editcount',
3209 [ 'user_id' => $this->mId
],
3213 if ( $count === null ) {
3214 // it has not been initialized. do so.
3215 $count = $this->initEditCount();
3217 $this->mEditCount
= $count;
3219 return (int)$this->mEditCount
;
3223 * Add the user to the given group.
3224 * This takes immediate effect.
3225 * @param string $group Name of the group to add
3228 public function addGroup( $group ) {
3231 if ( !Hooks
::run( 'UserAddGroup', [ $this, &$group ] ) ) {
3235 $dbw = wfGetDB( DB_MASTER
);
3236 if ( $this->getId() ) {
3237 $dbw->insert( 'user_groups',
3239 'ug_user' => $this->getID(),
3240 'ug_group' => $group,
3246 $this->loadGroups();
3247 $this->mGroups
[] = $group;
3248 // In case loadGroups was not called before, we now have the right twice.
3249 // Get rid of the duplicate.
3250 $this->mGroups
= array_unique( $this->mGroups
);
3252 // Refresh the groups caches, and clear the rights cache so it will be
3253 // refreshed on the next call to $this->getRights().
3254 $this->getEffectiveGroups( true );
3255 $this->mRights
= null;
3257 $this->invalidateCache();
3263 * Remove the user from the given group.
3264 * This takes immediate effect.
3265 * @param string $group Name of the group to remove
3268 public function removeGroup( $group ) {
3270 if ( !Hooks
::run( 'UserRemoveGroup', [ $this, &$group ] ) ) {
3274 $dbw = wfGetDB( DB_MASTER
);
3275 $dbw->delete( 'user_groups',
3277 'ug_user' => $this->getID(),
3278 'ug_group' => $group,
3281 // Remember that the user was in this group
3282 $dbw->insert( 'user_former_groups',
3284 'ufg_user' => $this->getID(),
3285 'ufg_group' => $group,
3291 $this->loadGroups();
3292 $this->mGroups
= array_diff( $this->mGroups
, [ $group ] );
3294 // Refresh the groups caches, and clear the rights cache so it will be
3295 // refreshed on the next call to $this->getRights().
3296 $this->getEffectiveGroups( true );
3297 $this->mRights
= null;
3299 $this->invalidateCache();
3305 * Get whether the user is logged in
3308 public function isLoggedIn() {
3309 return $this->getID() != 0;
3313 * Get whether the user is anonymous
3316 public function isAnon() {
3317 return !$this->isLoggedIn();
3321 * Check if user is allowed to access a feature / make an action
3323 * @param string ... Permissions to test
3324 * @return bool True if user is allowed to perform *any* of the given actions
3326 public function isAllowedAny() {
3327 $permissions = func_get_args();
3328 foreach ( $permissions as $permission ) {
3329 if ( $this->isAllowed( $permission ) ) {
3338 * @param string ... Permissions to test
3339 * @return bool True if the user is allowed to perform *all* of the given actions
3341 public function isAllowedAll() {
3342 $permissions = func_get_args();
3343 foreach ( $permissions as $permission ) {
3344 if ( !$this->isAllowed( $permission ) ) {
3352 * Internal mechanics of testing a permission
3353 * @param string $action
3356 public function isAllowed( $action = '' ) {
3357 if ( $action === '' ) {
3358 return true; // In the spirit of DWIM
3360 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3361 // by misconfiguration: 0 == 'foo'
3362 return in_array( $action, $this->getRights(), true );
3366 * Check whether to enable recent changes patrol features for this user
3367 * @return bool True or false
3369 public function useRCPatrol() {
3370 global $wgUseRCPatrol;
3371 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3375 * Check whether to enable new pages patrol features for this user
3376 * @return bool True or false
3378 public function useNPPatrol() {
3379 global $wgUseRCPatrol, $wgUseNPPatrol;
3381 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3382 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3387 * Check whether to enable new files patrol features for this user
3388 * @return bool True or false
3390 public function useFilePatrol() {
3391 global $wgUseRCPatrol, $wgUseFilePatrol;
3393 ( $wgUseRCPatrol ||
$wgUseFilePatrol )
3394 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3399 * Get the WebRequest object to use with this object
3401 * @return WebRequest
3403 public function getRequest() {
3404 if ( $this->mRequest
) {
3405 return $this->mRequest
;
3413 * Get a WatchedItem for this user and $title.
3415 * @since 1.22 $checkRights parameter added
3416 * @param Title $title
3417 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3418 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3419 * @return WatchedItem
3421 public function getWatchedItem( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3422 $key = $checkRights . ':' . $title->getNamespace() . ':' . $title->getDBkey();
3424 if ( isset( $this->mWatchedItems
[$key] ) ) {
3425 return $this->mWatchedItems
[$key];
3428 if ( count( $this->mWatchedItems
) >= self
::MAX_WATCHED_ITEMS_CACHE
) {
3429 $this->mWatchedItems
= [];
3432 $this->mWatchedItems
[$key] = WatchedItem
::fromUserTitle( $this, $title, $checkRights );
3433 return $this->mWatchedItems
[$key];
3437 * Check the watched status of an article.
3438 * @since 1.22 $checkRights parameter added
3439 * @param Title $title Title of the article to look at
3440 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3441 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3444 public function isWatched( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3445 return $this->getWatchedItem( $title, $checkRights )->isWatched();
3450 * @since 1.22 $checkRights parameter added
3451 * @param Title $title Title of the article to look at
3452 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3453 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3455 public function addWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3456 $this->getWatchedItem( $title, $checkRights )->addWatch();
3457 $this->invalidateCache();
3461 * Stop watching an article.
3462 * @since 1.22 $checkRights parameter added
3463 * @param Title $title Title of the article to look at
3464 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3465 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3467 public function removeWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3468 $this->getWatchedItem( $title, $checkRights )->removeWatch();
3469 $this->invalidateCache();
3473 * Clear the user's notification timestamp for the given title.
3474 * If e-notif e-mails are on, they will receive notification mails on
3475 * the next change of the page if it's watched etc.
3476 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3477 * @param Title $title Title of the article to look at
3478 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3480 public function clearNotification( &$title, $oldid = 0 ) {
3481 global $wgUseEnotif, $wgShowUpdatedMarker;
3483 // Do nothing if the database is locked to writes
3484 if ( wfReadOnly() ) {
3488 // Do nothing if not allowed to edit the watchlist
3489 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3493 // If we're working on user's talk page, we should update the talk page message indicator
3494 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3495 if ( !Hooks
::run( 'UserClearNewTalkNotification', [ &$this, $oldid ] ) ) {
3499 // Try to update the DB post-send and only if needed...
3500 DeferredUpdates
::addCallableUpdate( function() use ( $title, $oldid ) {
3501 if ( !$this->getNewtalk() ) {
3502 return; // no notifications to clear
3505 // Delete the last notifications (they stack up)
3506 $this->setNewtalk( false );
3508 // If there is a new, unseen, revision, use its timestamp
3510 ?
$title->getNextRevisionID( $oldid, Title
::GAID_FOR_UPDATE
)
3513 $this->setNewtalk( true, Revision
::newFromId( $nextid ) );
3518 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3522 if ( $this->isAnon() ) {
3523 // Nothing else to do...
3527 // Only update the timestamp if the page is being watched.
3528 // The query to find out if it is watched is cached both in memcached and per-invocation,
3529 // and when it does have to be executed, it can be on a slave
3530 // If this is the user's newtalk page, we always update the timestamp
3532 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3536 $this->getWatchedItem( $title )->resetNotificationTimestamp(
3542 * Resets all of the given user's page-change notification timestamps.
3543 * If e-notif e-mails are on, they will receive notification mails on
3544 * the next change of any watched page.
3545 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3547 public function clearAllNotifications() {
3548 if ( wfReadOnly() ) {
3552 // Do nothing if not allowed to edit the watchlist
3553 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3557 global $wgUseEnotif, $wgShowUpdatedMarker;
3558 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3559 $this->setNewtalk( false );
3562 $id = $this->getId();
3564 $dbw = wfGetDB( DB_MASTER
);
3565 $dbw->update( 'watchlist',
3566 [ /* SET */ 'wl_notificationtimestamp' => null ],
3567 [ /* WHERE */ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ],
3570 // We also need to clear here the "you have new message" notification for the own user_talk page;
3571 // it's cleared one page view later in WikiPage::doViewUpdates().
3576 * Set a cookie on the user's client. Wrapper for
3577 * WebResponse::setCookie
3578 * @deprecated since 1.27
3579 * @param string $name Name of the cookie to set
3580 * @param string $value Value to set
3581 * @param int $exp Expiration time, as a UNIX time value;
3582 * if 0 or not specified, use the default $wgCookieExpiration
3583 * @param bool $secure
3584 * true: Force setting the secure attribute when setting the cookie
3585 * false: Force NOT setting the secure attribute when setting the cookie
3586 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3587 * @param array $params Array of options sent passed to WebResponse::setcookie()
3588 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3591 protected function setCookie(
3592 $name, $value, $exp = 0, $secure = null, $params = [], $request = null
3594 wfDeprecated( __METHOD__
, '1.27' );
3595 if ( $request === null ) {
3596 $request = $this->getRequest();
3598 $params['secure'] = $secure;
3599 $request->response()->setCookie( $name, $value, $exp, $params );
3603 * Clear a cookie on the user's client
3604 * @deprecated since 1.27
3605 * @param string $name Name of the cookie to clear
3606 * @param bool $secure
3607 * true: Force setting the secure attribute when setting the cookie
3608 * false: Force NOT setting the secure attribute when setting the cookie
3609 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3610 * @param array $params Array of options sent passed to WebResponse::setcookie()
3612 protected function clearCookie( $name, $secure = null, $params = [] ) {
3613 wfDeprecated( __METHOD__
, '1.27' );
3614 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3618 * Set an extended login cookie on the user's client. The expiry of the cookie
3619 * is controlled by the $wgExtendedLoginCookieExpiration configuration
3622 * @see User::setCookie
3624 * @deprecated since 1.27
3625 * @param string $name Name of the cookie to set
3626 * @param string $value Value to set
3627 * @param bool $secure
3628 * true: Force setting the secure attribute when setting the cookie
3629 * false: Force NOT setting the secure attribute when setting the cookie
3630 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3632 protected function setExtendedLoginCookie( $name, $value, $secure ) {
3633 global $wgExtendedLoginCookieExpiration, $wgCookieExpiration;
3635 wfDeprecated( __METHOD__
, '1.27' );
3638 $exp +
= $wgExtendedLoginCookieExpiration !== null
3639 ?
$wgExtendedLoginCookieExpiration
3640 : $wgCookieExpiration;
3642 $this->setCookie( $name, $value, $exp, $secure );
3646 * Persist this user's session (e.g. set cookies)
3648 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3650 * @param bool $secure Whether to force secure/insecure cookies or use default
3651 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3653 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3655 if ( 0 == $this->mId
) {
3659 $session = $this->getRequest()->getSession();
3660 if ( $request && $session->getRequest() !== $request ) {
3661 $session = $session->sessionWithRequest( $request );
3663 $delay = $session->delaySave();
3665 if ( !$session->getUser()->equals( $this ) ) {
3666 if ( !$session->canSetUser() ) {
3667 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3668 ->warning( __METHOD__
.
3669 ": Cannot save user \"$this\" to a user \"{$session->getUser()}\"'s immutable session"
3673 $session->setUser( $this );
3676 $session->setRememberUser( $rememberMe );
3677 if ( $secure !== null ) {
3678 $session->setForceHTTPS( $secure );
3681 $session->persist();
3683 ScopedCallback
::consume( $delay );
3687 * Log this user out.
3689 public function logout() {
3690 if ( Hooks
::run( 'UserLogout', [ &$this ] ) ) {
3696 * Clear the user's session, and reset the instance cache.
3699 public function doLogout() {
3700 $session = $this->getRequest()->getSession();
3701 if ( !$session->canSetUser() ) {
3702 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3703 ->warning( __METHOD__
. ": Cannot log out of an immutable session" );
3704 } elseif ( !$session->getUser()->equals( $this ) ) {
3705 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3706 ->warning( __METHOD__
.
3707 ": Cannot log user \"$this\" out of a user \"{$session->getUser()}\"'s session"
3709 // But we still may as well make this user object anon
3710 $this->clearInstanceCache( 'defaults' );
3712 $this->clearInstanceCache( 'defaults' );
3713 $delay = $session->delaySave();
3714 $session->setLoggedOutTimestamp( time() );
3715 $session->setUser( new User
);
3716 $session->set( 'wsUserID', 0 ); // Other code expects this
3717 ScopedCallback
::consume( $delay );
3722 * Save this user's settings into the database.
3723 * @todo Only rarely do all these fields need to be set!
3725 public function saveSettings() {
3726 if ( wfReadOnly() ) {
3727 // @TODO: caller should deal with this instead!
3728 // This should really just be an exception.
3729 MWExceptionHandler
::logException( new DBExpectedError(
3731 "Could not update user with ID '{$this->mId}'; DB is read-only."
3737 if ( 0 == $this->mId
) {
3741 // Get a new user_touched that is higher than the old one.
3742 // This will be used for a CAS check as a last-resort safety
3743 // check against race conditions and slave lag.
3744 $oldTouched = $this->mTouched
;
3745 $newTouched = $this->newTouchedTimestamp();
3747 $dbw = wfGetDB( DB_MASTER
);
3748 $dbw->update( 'user',
3750 'user_name' => $this->mName
,
3751 'user_real_name' => $this->mRealName
,
3752 'user_email' => $this->mEmail
,
3753 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3754 'user_touched' => $dbw->timestamp( $newTouched ),
3755 'user_token' => strval( $this->mToken
),
3756 'user_email_token' => $this->mEmailToken
,
3757 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
3759 'user_id' => $this->mId
,
3760 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
3764 if ( !$dbw->affectedRows() ) {
3765 // Maybe the problem was a missed cache update; clear it to be safe
3766 $this->clearSharedCache( 'refresh' );
3767 // User was changed in the meantime or loaded with stale data
3768 $from = ( $this->queryFlagsUsed
& self
::READ_LATEST
) ?
'master' : 'slave';
3769 throw new MWException(
3770 "CAS update failed on user_touched for user ID '{$this->mId}' (read from $from);" .
3771 " the version of the user to be saved is older than the current version."
3775 $this->mTouched
= $newTouched;
3776 $this->saveOptions();
3778 Hooks
::run( 'UserSaveSettings', [ $this ] );
3779 $this->clearSharedCache();
3780 $this->getUserPage()->invalidateCache();
3784 * If only this user's username is known, and it exists, return the user ID.
3786 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
3789 public function idForName( $flags = 0 ) {
3790 $s = trim( $this->getName() );
3795 $db = ( ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
)
3796 ?
wfGetDB( DB_MASTER
)
3797 : wfGetDB( DB_SLAVE
);
3799 $options = ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
)
3800 ?
[ 'LOCK IN SHARE MODE' ]
3803 $id = $db->selectField( 'user',
3804 'user_id', [ 'user_name' => $s ], __METHOD__
, $options );
3810 * Add a user to the database, return the user object
3812 * @param string $name Username to add
3813 * @param array $params Array of Strings Non-default parameters to save to
3814 * the database as user_* fields:
3815 * - email: The user's email address.
3816 * - email_authenticated: The email authentication timestamp.
3817 * - real_name: The user's real name.
3818 * - options: An associative array of non-default options.
3819 * - token: Random authentication token. Do not set.
3820 * - registration: Registration timestamp. Do not set.
3822 * @return User|null User object, or null if the username already exists.
3824 public static function createNew( $name, $params = [] ) {
3825 foreach ( [ 'password', 'newpassword', 'newpass_time', 'password_expires' ] as $field ) {
3826 if ( isset( $params[$field] ) ) {
3827 wfDeprecated( __METHOD__
. " with param '$field'", '1.27' );
3828 unset( $params[$field] );
3834 $user->setToken(); // init token
3835 if ( isset( $params['options'] ) ) {
3836 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
3837 unset( $params['options'] );
3839 $dbw = wfGetDB( DB_MASTER
);
3840 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3842 $noPass = PasswordFactory
::newInvalidPassword()->toString();
3845 'user_id' => $seqVal,
3846 'user_name' => $name,
3847 'user_password' => $noPass,
3848 'user_newpassword' => $noPass,
3849 'user_email' => $user->mEmail
,
3850 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
3851 'user_real_name' => $user->mRealName
,
3852 'user_token' => strval( $user->mToken
),
3853 'user_registration' => $dbw->timestamp( $user->mRegistration
),
3854 'user_editcount' => 0,
3855 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
3857 foreach ( $params as $name => $value ) {
3858 $fields["user_$name"] = $value;
3860 $dbw->insert( 'user', $fields, __METHOD__
, [ 'IGNORE' ] );
3861 if ( $dbw->affectedRows() ) {
3862 $newUser = User
::newFromId( $dbw->insertId() );
3870 * Add this existing user object to the database. If the user already
3871 * exists, a fatal status object is returned, and the user object is
3872 * initialised with the data from the database.
3874 * Previously, this function generated a DB error due to a key conflict
3875 * if the user already existed. Many extension callers use this function
3876 * in code along the lines of:
3878 * $user = User::newFromName( $name );
3879 * if ( !$user->isLoggedIn() ) {
3880 * $user->addToDatabase();
3882 * // do something with $user...
3884 * However, this was vulnerable to a race condition (bug 16020). By
3885 * initialising the user object if the user exists, we aim to support this
3886 * calling sequence as far as possible.
3888 * Note that if the user exists, this function will acquire a write lock,
3889 * so it is still advisable to make the call conditional on isLoggedIn(),
3890 * and to commit the transaction after calling.
3892 * @throws MWException
3895 public function addToDatabase() {
3897 if ( !$this->mToken
) {
3898 $this->setToken(); // init token
3901 $this->mTouched
= $this->newTouchedTimestamp();
3903 $noPass = PasswordFactory
::newInvalidPassword()->toString();
3905 $dbw = wfGetDB( DB_MASTER
);
3906 $inWrite = $dbw->writesOrCallbacksPending();
3907 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3908 $dbw->insert( 'user',
3910 'user_id' => $seqVal,
3911 'user_name' => $this->mName
,
3912 'user_password' => $noPass,
3913 'user_newpassword' => $noPass,
3914 'user_email' => $this->mEmail
,
3915 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3916 'user_real_name' => $this->mRealName
,
3917 'user_token' => strval( $this->mToken
),
3918 'user_registration' => $dbw->timestamp( $this->mRegistration
),
3919 'user_editcount' => 0,
3920 'user_touched' => $dbw->timestamp( $this->mTouched
),
3924 if ( !$dbw->affectedRows() ) {
3925 // The queries below cannot happen in the same REPEATABLE-READ snapshot.
3926 // Handle this by COMMIT, if possible, or by LOCK IN SHARE MODE otherwise.
3928 // Can't commit due to pending writes that may need atomicity.
3929 // This may cause some lock contention unlike the case below.
3930 $options = [ 'LOCK IN SHARE MODE' ];
3931 $flags = self
::READ_LOCKING
;
3933 // Often, this case happens early in views before any writes when
3934 // using CentralAuth. It's should be OK to commit and break the snapshot.
3935 $dbw->commit( __METHOD__
, 'flush' );
3937 $flags = self
::READ_LATEST
;
3939 $this->mId
= $dbw->selectField( 'user', 'user_id',
3940 [ 'user_name' => $this->mName
], __METHOD__
, $options );
3943 if ( $this->loadFromDatabase( $flags ) ) {
3948 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
3949 "to insert user '{$this->mName}' row, but it was not present in select!" );
3951 return Status
::newFatal( 'userexists' );
3953 $this->mId
= $dbw->insertId();
3954 self
::$idCacheByName[$this->mName
] = $this->mId
;
3956 // Clear instance cache other than user table data, which is already accurate
3957 $this->clearInstanceCache();
3959 $this->saveOptions();
3960 return Status
::newGood();
3964 * If this user is logged-in and blocked,
3965 * block any IP address they've successfully logged in from.
3966 * @return bool A block was spread
3968 public function spreadAnyEditBlock() {
3969 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3970 return $this->spreadBlock();
3976 * If this (non-anonymous) user is blocked,
3977 * block the IP address they've successfully logged in from.
3978 * @return bool A block was spread
3980 protected function spreadBlock() {
3981 wfDebug( __METHOD__
. "()\n" );
3983 if ( $this->mId
== 0 ) {
3987 $userblock = Block
::newFromTarget( $this->getName() );
3988 if ( !$userblock ) {
3992 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3996 * Get whether the user is explicitly blocked from account creation.
3997 * @return bool|Block
3999 public function isBlockedFromCreateAccount() {
4000 $this->getBlockedStatus();
4001 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
4002 return $this->mBlock
;
4005 # bug 13611: if the IP address the user is trying to create an account from is
4006 # blocked with createaccount disabled, prevent new account creation there even
4007 # when the user is logged in
4008 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
4009 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
4011 return $this->mBlockedFromCreateAccount
instanceof Block
4012 && $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
4013 ?
$this->mBlockedFromCreateAccount
4018 * Get whether the user is blocked from using Special:Emailuser.
4021 public function isBlockedFromEmailuser() {
4022 $this->getBlockedStatus();
4023 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
4027 * Get whether the user is allowed to create an account.
4030 public function isAllowedToCreateAccount() {
4031 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
4035 * Get this user's personal page title.
4037 * @return Title User's personal page title
4039 public function getUserPage() {
4040 return Title
::makeTitle( NS_USER
, $this->getName() );
4044 * Get this user's talk page title.
4046 * @return Title User's talk page title
4048 public function getTalkPage() {
4049 $title = $this->getUserPage();
4050 return $title->getTalkPage();
4054 * Determine whether the user is a newbie. Newbies are either
4055 * anonymous IPs, or the most recently created accounts.
4058 public function isNewbie() {
4059 return !$this->isAllowed( 'autoconfirmed' );
4063 * Check to see if the given clear-text password is one of the accepted passwords
4064 * @deprecated since 1.27. AuthManager is coming.
4065 * @param string $password User password
4066 * @return bool True if the given password is correct, otherwise False
4068 public function checkPassword( $password ) {
4069 global $wgAuth, $wgLegacyEncoding;
4073 // Some passwords will give a fatal Status, which means there is
4074 // some sort of technical or security reason for this password to
4075 // be completely invalid and should never be checked (e.g., T64685)
4076 if ( !$this->checkPasswordValidity( $password )->isOK() ) {
4080 // Certain authentication plugins do NOT want to save
4081 // domain passwords in a mysql database, so we should
4082 // check this (in case $wgAuth->strict() is false).
4083 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
4085 } elseif ( $wgAuth->strict() ) {
4086 // Auth plugin doesn't allow local authentication
4088 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
4089 // Auth plugin doesn't allow local authentication for this user name
4093 $passwordFactory = new PasswordFactory();
4094 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4095 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
4096 ?
wfGetDB( DB_MASTER
)
4097 : wfGetDB( DB_SLAVE
);
4100 $mPassword = $passwordFactory->newFromCiphertext( $db->selectField(
4101 'user', 'user_password', [ 'user_id' => $this->getId() ], __METHOD__
4103 } catch ( PasswordError
$e ) {
4104 wfDebug( 'Invalid password hash found in database.' );
4105 $mPassword = PasswordFactory
::newInvalidPassword();
4108 if ( !$mPassword->equals( $password ) ) {
4109 if ( $wgLegacyEncoding ) {
4110 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
4111 // Check for this with iconv
4112 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
4113 if ( $cp1252Password === $password ||
!$mPassword->equals( $cp1252Password ) ) {
4121 if ( $passwordFactory->needsUpdate( $mPassword ) && !wfReadOnly() ) {
4122 $this->setPasswordInternal( $password );
4129 * Check if the given clear-text password matches the temporary password
4130 * sent by e-mail for password reset operations.
4132 * @deprecated since 1.27. AuthManager is coming.
4133 * @param string $plaintext
4134 * @return bool True if matches, false otherwise
4136 public function checkTemporaryPassword( $plaintext ) {
4137 global $wgNewPasswordExpiry;
4141 $passwordFactory = new PasswordFactory();
4142 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4143 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
4144 ?
wfGetDB( DB_MASTER
)
4145 : wfGetDB( DB_SLAVE
);
4147 $row = $db->selectRow(
4149 [ 'user_newpassword', 'user_newpass_time' ],
4150 [ 'user_id' => $this->getId() ],
4154 $newPassword = $passwordFactory->newFromCiphertext( $row->user_newpassword
);
4155 } catch ( PasswordError
$e ) {
4156 wfDebug( 'Invalid password hash found in database.' );
4157 $newPassword = PasswordFactory
::newInvalidPassword();
4160 if ( $newPassword->equals( $plaintext ) ) {
4161 if ( is_null( $row->user_newpass_time
) ) {
4164 $expiry = wfTimestamp( TS_UNIX
, $row->user_newpass_time
) +
$wgNewPasswordExpiry;
4165 return ( time() < $expiry );
4172 * Initialize (if necessary) and return a session token value
4173 * which can be used in edit forms to show that the user's
4174 * login credentials aren't being hijacked with a foreign form
4178 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4179 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4180 * @return MediaWiki\\Session\\Token The new edit token
4182 public function getEditTokenObject( $salt = '', $request = null ) {
4183 if ( $this->isAnon() ) {
4184 return new LoggedOutEditToken();
4188 $request = $this->getRequest();
4190 return $request->getSession()->getToken( $salt );
4194 * Initialize (if necessary) and return a session token value
4195 * which can be used in edit forms to show that the user's
4196 * login credentials aren't being hijacked with a foreign form
4200 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4201 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4202 * @return string The new edit token
4204 public function getEditToken( $salt = '', $request = null ) {
4205 return $this->getEditTokenObject( $salt, $request )->toString();
4209 * Get the embedded timestamp from a token.
4210 * @deprecated since 1.27, use \\MediaWiki\\Session\\Token::getTimestamp instead.
4211 * @param string $val Input token
4214 public static function getEditTokenTimestamp( $val ) {
4215 wfDeprecated( __METHOD__
, '1.27' );
4216 return MediaWiki\Session\Token
::getTimestamp( $val );
4220 * Check given value against the token value stored in the session.
4221 * A match should confirm that the form was submitted from the
4222 * user's own login session, not a form submission from a third-party
4225 * @param string $val Input value to compare
4226 * @param string $salt Optional function-specific data for hashing
4227 * @param WebRequest|null $request Object to use or null to use $wgRequest
4228 * @param int $maxage Fail tokens older than this, in seconds
4229 * @return bool Whether the token matches
4231 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4232 return $this->getEditTokenObject( $salt, $request )->match( $val, $maxage );
4236 * Check given value against the token value stored in the session,
4237 * ignoring the suffix.
4239 * @param string $val Input value to compare
4240 * @param string $salt Optional function-specific data for hashing
4241 * @param WebRequest|null $request Object to use or null to use $wgRequest
4242 * @param int $maxage Fail tokens older than this, in seconds
4243 * @return bool Whether the token matches
4245 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4246 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . self
::EDIT_TOKEN_SUFFIX
;
4247 return $this->matchEditToken( $val, $salt, $request, $maxage );
4251 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4252 * mail to the user's given address.
4254 * @param string $type Message to send, either "created", "changed" or "set"
4257 public function sendConfirmationMail( $type = 'created' ) {
4259 $expiration = null; // gets passed-by-ref and defined in next line.
4260 $token = $this->confirmationToken( $expiration );
4261 $url = $this->confirmationTokenUrl( $token );
4262 $invalidateURL = $this->invalidationTokenUrl( $token );
4263 $this->saveSettings();
4265 if ( $type == 'created' ||
$type === false ) {
4266 $message = 'confirmemail_body';
4267 } elseif ( $type === true ) {
4268 $message = 'confirmemail_body_changed';
4270 // Messages: confirmemail_body_changed, confirmemail_body_set
4271 $message = 'confirmemail_body_' . $type;
4274 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4275 wfMessage( $message,
4276 $this->getRequest()->getIP(),
4279 $wgLang->userTimeAndDate( $expiration, $this ),
4281 $wgLang->userDate( $expiration, $this ),
4282 $wgLang->userTime( $expiration, $this ) )->text() );
4286 * Send an e-mail to this user's account. Does not check for
4287 * confirmed status or validity.
4289 * @param string $subject Message subject
4290 * @param string $body Message body
4291 * @param User|null $from Optional sending user; if unspecified, default
4292 * $wgPasswordSender will be used.
4293 * @param string $replyto Reply-To address
4296 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4297 global $wgPasswordSender;
4299 if ( $from instanceof User
) {
4300 $sender = MailAddress
::newFromUser( $from );
4302 $sender = new MailAddress( $wgPasswordSender,
4303 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4305 $to = MailAddress
::newFromUser( $this );
4307 return UserMailer
::send( $to, $sender, $subject, $body, [
4308 'replyTo' => $replyto,
4313 * Generate, store, and return a new e-mail confirmation code.
4314 * A hash (unsalted, since it's used as a key) is stored.
4316 * @note Call saveSettings() after calling this function to commit
4317 * this change to the database.
4319 * @param string &$expiration Accepts the expiration time
4320 * @return string New token
4322 protected function confirmationToken( &$expiration ) {
4323 global $wgUserEmailConfirmationTokenExpiry;
4325 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4326 $expiration = wfTimestamp( TS_MW
, $expires );
4328 $token = MWCryptRand
::generateHex( 32 );
4329 $hash = md5( $token );
4330 $this->mEmailToken
= $hash;
4331 $this->mEmailTokenExpires
= $expiration;
4336 * Return a URL the user can use to confirm their email address.
4337 * @param string $token Accepts the email confirmation token
4338 * @return string New token URL
4340 protected function confirmationTokenUrl( $token ) {
4341 return $this->getTokenUrl( 'ConfirmEmail', $token );
4345 * Return a URL the user can use to invalidate their email address.
4346 * @param string $token Accepts the email confirmation token
4347 * @return string New token URL
4349 protected function invalidationTokenUrl( $token ) {
4350 return $this->getTokenUrl( 'InvalidateEmail', $token );
4354 * Internal function to format the e-mail validation/invalidation URLs.
4355 * This uses a quickie hack to use the
4356 * hardcoded English names of the Special: pages, for ASCII safety.
4358 * @note Since these URLs get dropped directly into emails, using the
4359 * short English names avoids insanely long URL-encoded links, which
4360 * also sometimes can get corrupted in some browsers/mailers
4361 * (bug 6957 with Gmail and Internet Explorer).
4363 * @param string $page Special page
4364 * @param string $token Token
4365 * @return string Formatted URL
4367 protected function getTokenUrl( $page, $token ) {
4368 // Hack to bypass localization of 'Special:'
4369 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4370 return $title->getCanonicalURL();
4374 * Mark the e-mail address confirmed.
4376 * @note Call saveSettings() after calling this function to commit the change.
4380 public function confirmEmail() {
4381 // Check if it's already confirmed, so we don't touch the database
4382 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4383 if ( !$this->isEmailConfirmed() ) {
4384 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4385 Hooks
::run( 'ConfirmEmailComplete', [ $this ] );
4391 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4392 * address if it was already confirmed.
4394 * @note Call saveSettings() after calling this function to commit the change.
4395 * @return bool Returns true
4397 public function invalidateEmail() {
4399 $this->mEmailToken
= null;
4400 $this->mEmailTokenExpires
= null;
4401 $this->setEmailAuthenticationTimestamp( null );
4403 Hooks
::run( 'InvalidateEmailComplete', [ $this ] );
4408 * Set the e-mail authentication timestamp.
4409 * @param string $timestamp TS_MW timestamp
4411 public function setEmailAuthenticationTimestamp( $timestamp ) {
4413 $this->mEmailAuthenticated
= $timestamp;
4414 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
4418 * Is this user allowed to send e-mails within limits of current
4419 * site configuration?
4422 public function canSendEmail() {
4423 global $wgEnableEmail, $wgEnableUserEmail;
4424 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4427 $canSend = $this->isEmailConfirmed();
4428 Hooks
::run( 'UserCanSendEmail', [ &$this, &$canSend ] );
4433 * Is this user allowed to receive e-mails within limits of current
4434 * site configuration?
4437 public function canReceiveEmail() {
4438 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4442 * Is this user's e-mail address valid-looking and confirmed within
4443 * limits of the current site configuration?
4445 * @note If $wgEmailAuthentication is on, this may require the user to have
4446 * confirmed their address by returning a code or using a password
4447 * sent to the address from the wiki.
4451 public function isEmailConfirmed() {
4452 global $wgEmailAuthentication;
4455 if ( Hooks
::run( 'EmailConfirmed', [ &$this, &$confirmed ] ) ) {
4456 if ( $this->isAnon() ) {
4459 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4462 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4472 * Check whether there is an outstanding request for e-mail confirmation.
4475 public function isEmailConfirmationPending() {
4476 global $wgEmailAuthentication;
4477 return $wgEmailAuthentication &&
4478 !$this->isEmailConfirmed() &&
4479 $this->mEmailToken
&&
4480 $this->mEmailTokenExpires
> wfTimestamp();
4484 * Get the timestamp of account creation.
4486 * @return string|bool|null Timestamp of account creation, false for
4487 * non-existent/anonymous user accounts, or null if existing account
4488 * but information is not in database.
4490 public function getRegistration() {
4491 if ( $this->isAnon() ) {
4495 return $this->mRegistration
;
4499 * Get the timestamp of the first edit
4501 * @return string|bool Timestamp of first edit, or false for
4502 * non-existent/anonymous user accounts.
4504 public function getFirstEditTimestamp() {
4505 if ( $this->getId() == 0 ) {
4506 return false; // anons
4508 $dbr = wfGetDB( DB_SLAVE
);
4509 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4510 [ 'rev_user' => $this->getId() ],
4512 [ 'ORDER BY' => 'rev_timestamp ASC' ]
4515 return false; // no edits
4517 return wfTimestamp( TS_MW
, $time );
4521 * Get the permissions associated with a given list of groups
4523 * @param array $groups Array of Strings List of internal group names
4524 * @return array Array of Strings List of permission key names for given groups combined
4526 public static function getGroupPermissions( $groups ) {
4527 global $wgGroupPermissions, $wgRevokePermissions;
4529 // grant every granted permission first
4530 foreach ( $groups as $group ) {
4531 if ( isset( $wgGroupPermissions[$group] ) ) {
4532 $rights = array_merge( $rights,
4533 // array_filter removes empty items
4534 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4537 // now revoke the revoked permissions
4538 foreach ( $groups as $group ) {
4539 if ( isset( $wgRevokePermissions[$group] ) ) {
4540 $rights = array_diff( $rights,
4541 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4544 return array_unique( $rights );
4548 * Get all the groups who have a given permission
4550 * @param string $role Role to check
4551 * @return array Array of Strings List of internal group names with the given permission
4553 public static function getGroupsWithPermission( $role ) {
4554 global $wgGroupPermissions;
4555 $allowedGroups = [];
4556 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4557 if ( self
::groupHasPermission( $group, $role ) ) {
4558 $allowedGroups[] = $group;
4561 return $allowedGroups;
4565 * Check, if the given group has the given permission
4567 * If you're wanting to check whether all users have a permission, use
4568 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4572 * @param string $group Group to check
4573 * @param string $role Role to check
4576 public static function groupHasPermission( $group, $role ) {
4577 global $wgGroupPermissions, $wgRevokePermissions;
4578 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4579 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4583 * Check if all users may be assumed to have the given permission
4585 * We generally assume so if the right is granted to '*' and isn't revoked
4586 * on any group. It doesn't attempt to take grants or other extension
4587 * limitations on rights into account in the general case, though, as that
4588 * would require it to always return false and defeat the purpose.
4589 * Specifically, session-based rights restrictions (such as OAuth or bot
4590 * passwords) are applied based on the current session.
4593 * @param string $right Right to check
4596 public static function isEveryoneAllowed( $right ) {
4597 global $wgGroupPermissions, $wgRevokePermissions;
4600 // Use the cached results, except in unit tests which rely on
4601 // being able change the permission mid-request
4602 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4603 return $cache[$right];
4606 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4607 $cache[$right] = false;
4611 // If it's revoked anywhere, then everyone doesn't have it
4612 foreach ( $wgRevokePermissions as $rights ) {
4613 if ( isset( $rights[$right] ) && $rights[$right] ) {
4614 $cache[$right] = false;
4619 // Remove any rights that aren't allowed to the global-session user,
4620 // unless there are no sessions for this endpoint.
4621 if ( !defined( 'MW_NO_SESSION' ) ) {
4622 $allowedRights = SessionManager
::getGlobalSession()->getAllowedUserRights();
4623 if ( $allowedRights !== null && !in_array( $right, $allowedRights, true ) ) {
4624 $cache[$right] = false;
4629 // Allow extensions to say false
4630 if ( !Hooks
::run( 'UserIsEveryoneAllowed', [ $right ] ) ) {
4631 $cache[$right] = false;
4635 $cache[$right] = true;
4640 * Get the localized descriptive name for a group, if it exists
4642 * @param string $group Internal group name
4643 * @return string Localized descriptive group name
4645 public static function getGroupName( $group ) {
4646 $msg = wfMessage( "group-$group" );
4647 return $msg->isBlank() ?
$group : $msg->text();
4651 * Get the localized descriptive name for a member of a group, if it exists
4653 * @param string $group Internal group name
4654 * @param string $username Username for gender (since 1.19)
4655 * @return string Localized name for group member
4657 public static function getGroupMember( $group, $username = '#' ) {
4658 $msg = wfMessage( "group-$group-member", $username );
4659 return $msg->isBlank() ?
$group : $msg->text();
4663 * Return the set of defined explicit groups.
4664 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4665 * are not included, as they are defined automatically, not in the database.
4666 * @return array Array of internal group names
4668 public static function getAllGroups() {
4669 global $wgGroupPermissions, $wgRevokePermissions;
4671 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4672 self
::getImplicitGroups()
4677 * Get a list of all available permissions.
4678 * @return string[] Array of permission names
4680 public static function getAllRights() {
4681 if ( self
::$mAllRights === false ) {
4682 global $wgAvailableRights;
4683 if ( count( $wgAvailableRights ) ) {
4684 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
4686 self
::$mAllRights = self
::$mCoreRights;
4688 Hooks
::run( 'UserGetAllRights', [ &self
::$mAllRights ] );
4690 return self
::$mAllRights;
4694 * Get a list of implicit groups
4695 * @return array Array of Strings Array of internal group names
4697 public static function getImplicitGroups() {
4698 global $wgImplicitGroups;
4700 $groups = $wgImplicitGroups;
4701 # Deprecated, use $wgImplicitGroups instead
4702 Hooks
::run( 'UserGetImplicitGroups', [ &$groups ], '1.25' );
4708 * Get the title of a page describing a particular group
4710 * @param string $group Internal group name
4711 * @return Title|bool Title of the page if it exists, false otherwise
4713 public static function getGroupPage( $group ) {
4714 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4715 if ( $msg->exists() ) {
4716 $title = Title
::newFromText( $msg->text() );
4717 if ( is_object( $title ) ) {
4725 * Create a link to the group in HTML, if available;
4726 * else return the group name.
4728 * @param string $group Internal name of the group
4729 * @param string $text The text of the link
4730 * @return string HTML link to the group
4732 public static function makeGroupLinkHTML( $group, $text = '' ) {
4733 if ( $text == '' ) {
4734 $text = self
::getGroupName( $group );
4736 $title = self
::getGroupPage( $group );
4738 return Linker
::link( $title, htmlspecialchars( $text ) );
4740 return htmlspecialchars( $text );
4745 * Create a link to the group in Wikitext, if available;
4746 * else return the group name.
4748 * @param string $group Internal name of the group
4749 * @param string $text The text of the link
4750 * @return string Wikilink to the group
4752 public static function makeGroupLinkWiki( $group, $text = '' ) {
4753 if ( $text == '' ) {
4754 $text = self
::getGroupName( $group );
4756 $title = self
::getGroupPage( $group );
4758 $page = $title->getFullText();
4759 return "[[$page|$text]]";
4766 * Returns an array of the groups that a particular group can add/remove.
4768 * @param string $group The group to check for whether it can add/remove
4769 * @return array Array( 'add' => array( addablegroups ),
4770 * 'remove' => array( removablegroups ),
4771 * 'add-self' => array( addablegroups to self),
4772 * 'remove-self' => array( removable groups from self) )
4774 public static function changeableByGroup( $group ) {
4775 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4784 if ( empty( $wgAddGroups[$group] ) ) {
4785 // Don't add anything to $groups
4786 } elseif ( $wgAddGroups[$group] === true ) {
4787 // You get everything
4788 $groups['add'] = self
::getAllGroups();
4789 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4790 $groups['add'] = $wgAddGroups[$group];
4793 // Same thing for remove
4794 if ( empty( $wgRemoveGroups[$group] ) ) {
4796 } elseif ( $wgRemoveGroups[$group] === true ) {
4797 $groups['remove'] = self
::getAllGroups();
4798 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4799 $groups['remove'] = $wgRemoveGroups[$group];
4802 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4803 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4804 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4805 if ( is_int( $key ) ) {
4806 $wgGroupsAddToSelf['user'][] = $value;
4811 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
4812 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4813 if ( is_int( $key ) ) {
4814 $wgGroupsRemoveFromSelf['user'][] = $value;
4819 // Now figure out what groups the user can add to him/herself
4820 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4822 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4823 // No idea WHY this would be used, but it's there
4824 $groups['add-self'] = User
::getAllGroups();
4825 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4826 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4829 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4831 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4832 $groups['remove-self'] = User
::getAllGroups();
4833 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4834 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4841 * Returns an array of groups that this user can add and remove
4842 * @return array Array( 'add' => array( addablegroups ),
4843 * 'remove' => array( removablegroups ),
4844 * 'add-self' => array( addablegroups to self),
4845 * 'remove-self' => array( removable groups from self) )
4847 public function changeableGroups() {
4848 if ( $this->isAllowed( 'userrights' ) ) {
4849 // This group gives the right to modify everything (reverse-
4850 // compatibility with old "userrights lets you change
4852 // Using array_merge to make the groups reindexed
4853 $all = array_merge( User
::getAllGroups() );
4862 // Okay, it's not so simple, we will have to go through the arrays
4869 $addergroups = $this->getEffectiveGroups();
4871 foreach ( $addergroups as $addergroup ) {
4872 $groups = array_merge_recursive(
4873 $groups, $this->changeableByGroup( $addergroup )
4875 $groups['add'] = array_unique( $groups['add'] );
4876 $groups['remove'] = array_unique( $groups['remove'] );
4877 $groups['add-self'] = array_unique( $groups['add-self'] );
4878 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4884 * Deferred version of incEditCountImmediate()
4886 public function incEditCount() {
4887 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle( function() {
4888 $this->incEditCountImmediate();
4893 * Increment the user's edit-count field.
4894 * Will have no effect for anonymous users.
4897 public function incEditCountImmediate() {
4898 if ( $this->isAnon() ) {
4902 $dbw = wfGetDB( DB_MASTER
);
4903 // No rows will be "affected" if user_editcount is NULL
4906 [ 'user_editcount=user_editcount+1' ],
4907 [ 'user_id' => $this->getId(), 'user_editcount IS NOT NULL' ],
4910 // Lazy initialization check...
4911 if ( $dbw->affectedRows() == 0 ) {
4912 // Now here's a goddamn hack...
4913 $dbr = wfGetDB( DB_SLAVE
);
4914 if ( $dbr !== $dbw ) {
4915 // If we actually have a slave server, the count is
4916 // at least one behind because the current transaction
4917 // has not been committed and replicated.
4918 $this->initEditCount( 1 );
4920 // But if DB_SLAVE is selecting the master, then the
4921 // count we just read includes the revision that was
4922 // just added in the working transaction.
4923 $this->initEditCount();
4926 // Edit count in user cache too
4927 $this->invalidateCache();
4931 * Initialize user_editcount from data out of the revision table
4933 * @param int $add Edits to add to the count from the revision table
4934 * @return int Number of edits
4936 protected function initEditCount( $add = 0 ) {
4937 // Pull from a slave to be less cruel to servers
4938 // Accuracy isn't the point anyway here
4939 $dbr = wfGetDB( DB_SLAVE
);
4940 $count = (int)$dbr->selectField(
4943 [ 'rev_user' => $this->getId() ],
4946 $count = $count +
$add;
4948 $dbw = wfGetDB( DB_MASTER
);
4951 [ 'user_editcount' => $count ],
4952 [ 'user_id' => $this->getId() ],
4960 * Get the description of a given right
4962 * @param string $right Right to query
4963 * @return string Localized description of the right
4965 public static function getRightDescription( $right ) {
4966 $key = "right-$right";
4967 $msg = wfMessage( $key );
4968 return $msg->isBlank() ?
$right : $msg->text();
4972 * Make a new-style password hash
4974 * @param string $password Plain-text password
4975 * @param bool|string $salt Optional salt, may be random or the user ID.
4976 * If unspecified or false, will generate one automatically
4977 * @return string Password hash
4978 * @deprecated since 1.24, use Password class
4980 public static function crypt( $password, $salt = false ) {
4981 wfDeprecated( __METHOD__
, '1.24' );
4982 $passwordFactory = new PasswordFactory();
4983 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4984 $hash = $passwordFactory->newFromPlaintext( $password );
4985 return $hash->toString();
4989 * Compare a password hash with a plain-text password. Requires the user
4990 * ID if there's a chance that the hash is an old-style hash.
4992 * @param string $hash Password hash
4993 * @param string $password Plain-text password to compare
4994 * @param string|bool $userId User ID for old-style password salt
4997 * @deprecated since 1.24, use Password class
4999 public static function comparePasswords( $hash, $password, $userId = false ) {
5000 wfDeprecated( __METHOD__
, '1.24' );
5002 // Check for *really* old password hashes that don't even have a type
5003 // The old hash format was just an md5 hex hash, with no type information
5004 if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) {
5005 global $wgPasswordSalt;
5006 if ( $wgPasswordSalt ) {
5007 $password = ":B:{$userId}:{$hash}";
5009 $password = ":A:{$hash}";
5013 $passwordFactory = new PasswordFactory();
5014 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
5015 $hash = $passwordFactory->newFromCiphertext( $hash );
5016 return $hash->equals( $password );
5020 * Add a newuser log entry for this user.
5021 * Before 1.19 the return value was always true.
5023 * @param string|bool $action Account creation type.
5024 * - String, one of the following values:
5025 * - 'create' for an anonymous user creating an account for himself.
5026 * This will force the action's performer to be the created user itself,
5027 * no matter the value of $wgUser
5028 * - 'create2' for a logged in user creating an account for someone else
5029 * - 'byemail' when the created user will receive its password by e-mail
5030 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
5031 * - Boolean means whether the account was created by e-mail (deprecated):
5032 * - true will be converted to 'byemail'
5033 * - false will be converted to 'create' if this object is the same as
5034 * $wgUser and to 'create2' otherwise
5036 * @param string $reason User supplied reason
5038 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
5040 public function addNewUserLogEntry( $action = false, $reason = '' ) {
5041 global $wgUser, $wgNewUserLog;
5042 if ( empty( $wgNewUserLog ) ) {
5043 return true; // disabled
5046 if ( $action === true ) {
5047 $action = 'byemail';
5048 } elseif ( $action === false ) {
5049 if ( $this->equals( $wgUser ) ) {
5052 $action = 'create2';
5056 if ( $action === 'create' ||
$action === 'autocreate' ) {
5059 $performer = $wgUser;
5062 $logEntry = new ManualLogEntry( 'newusers', $action );
5063 $logEntry->setPerformer( $performer );
5064 $logEntry->setTarget( $this->getUserPage() );
5065 $logEntry->setComment( $reason );
5066 $logEntry->setParameters( [
5067 '4::userid' => $this->getId(),
5069 $logid = $logEntry->insert();
5071 if ( $action !== 'autocreate' ) {
5072 $logEntry->publish( $logid );
5079 * Add an autocreate newuser log entry for this user
5080 * Used by things like CentralAuth and perhaps other authplugins.
5081 * Consider calling addNewUserLogEntry() directly instead.
5085 public function addNewUserLogEntryAutoCreate() {
5086 $this->addNewUserLogEntry( 'autocreate' );
5092 * Load the user options either from cache, the database or an array
5094 * @param array $data Rows for the current user out of the user_properties table
5096 protected function loadOptions( $data = null ) {
5101 if ( $this->mOptionsLoaded
) {
5105 $this->mOptions
= self
::getDefaultOptions();
5107 if ( !$this->getId() ) {
5108 // For unlogged-in users, load language/variant options from request.
5109 // There's no need to do it for logged-in users: they can set preferences,
5110 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5111 // so don't override user's choice (especially when the user chooses site default).
5112 $variant = $wgContLang->getDefaultVariant();
5113 $this->mOptions
['variant'] = $variant;
5114 $this->mOptions
['language'] = $variant;
5115 $this->mOptionsLoaded
= true;
5119 // Maybe load from the object
5120 if ( !is_null( $this->mOptionOverrides
) ) {
5121 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5122 foreach ( $this->mOptionOverrides
as $key => $value ) {
5123 $this->mOptions
[$key] = $value;
5126 if ( !is_array( $data ) ) {
5127 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5128 // Load from database
5129 $dbr = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
5130 ?
wfGetDB( DB_MASTER
)
5131 : wfGetDB( DB_SLAVE
);
5133 $res = $dbr->select(
5135 [ 'up_property', 'up_value' ],
5136 [ 'up_user' => $this->getId() ],
5140 $this->mOptionOverrides
= [];
5142 foreach ( $res as $row ) {
5143 $data[$row->up_property
] = $row->up_value
;
5146 foreach ( $data as $property => $value ) {
5147 $this->mOptionOverrides
[$property] = $value;
5148 $this->mOptions
[$property] = $value;
5152 $this->mOptionsLoaded
= true;
5154 Hooks
::run( 'UserLoadOptions', [ $this, &$this->mOptions
] );
5158 * Saves the non-default options for this user, as previously set e.g. via
5159 * setOption(), in the database's "user_properties" (preferences) table.
5160 * Usually used via saveSettings().
5162 protected function saveOptions() {
5163 $this->loadOptions();
5165 // Not using getOptions(), to keep hidden preferences in database
5166 $saveOptions = $this->mOptions
;
5168 // Allow hooks to abort, for instance to save to a global profile.
5169 // Reset options to default state before saving.
5170 if ( !Hooks
::run( 'UserSaveOptions', [ $this, &$saveOptions ] ) ) {
5174 $userId = $this->getId();
5176 $insert_rows = []; // all the new preference rows
5177 foreach ( $saveOptions as $key => $value ) {
5178 // Don't bother storing default values
5179 $defaultOption = self
::getDefaultOption( $key );
5180 if ( ( $defaultOption === null && $value !== false && $value !== null )
5181 ||
$value != $defaultOption
5184 'up_user' => $userId,
5185 'up_property' => $key,
5186 'up_value' => $value,
5191 $dbw = wfGetDB( DB_MASTER
);
5193 $res = $dbw->select( 'user_properties',
5194 [ 'up_property', 'up_value' ], [ 'up_user' => $userId ], __METHOD__
);
5196 // Find prior rows that need to be removed or updated. These rows will
5197 // all be deleted (the later so that INSERT IGNORE applies the new values).
5199 foreach ( $res as $row ) {
5200 if ( !isset( $saveOptions[$row->up_property
] )
5201 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
5203 $keysDelete[] = $row->up_property
;
5207 if ( count( $keysDelete ) ) {
5208 // Do the DELETE by PRIMARY KEY for prior rows.
5209 // In the past a very large portion of calls to this function are for setting
5210 // 'rememberpassword' for new accounts (a preference that has since been removed).
5211 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5212 // caused gap locks on [max user ID,+infinity) which caused high contention since
5213 // updates would pile up on each other as they are for higher (newer) user IDs.
5214 // It might not be necessary these days, but it shouldn't hurt either.
5215 $dbw->delete( 'user_properties',
5216 [ 'up_user' => $userId, 'up_property' => $keysDelete ], __METHOD__
);
5218 // Insert the new preference rows
5219 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, [ 'IGNORE' ] );
5223 * Lazily instantiate and return a factory object for making passwords
5225 * @deprecated since 1.27, create a PasswordFactory directly instead
5226 * @return PasswordFactory
5228 public static function getPasswordFactory() {
5229 wfDeprecated( __METHOD__
, '1.27' );
5230 $ret = new PasswordFactory();
5231 $ret->init( RequestContext
::getMain()->getConfig() );
5236 * Provide an array of HTML5 attributes to put on an input element
5237 * intended for the user to enter a new password. This may include
5238 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
5240 * Do *not* use this when asking the user to enter his current password!
5241 * Regardless of configuration, users may have invalid passwords for whatever
5242 * reason (e.g., they were set before requirements were tightened up).
5243 * Only use it when asking for a new password, like on account creation or
5246 * Obviously, you still need to do server-side checking.
5248 * NOTE: A combination of bugs in various browsers means that this function
5249 * actually just returns array() unconditionally at the moment. May as
5250 * well keep it around for when the browser bugs get fixed, though.
5252 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
5254 * @deprecated since 1.27
5255 * @return array Array of HTML attributes suitable for feeding to
5256 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
5257 * That will get confused by the boolean attribute syntax used.)
5259 public static function passwordChangeInputAttribs() {
5260 global $wgMinimalPasswordLength;
5262 if ( $wgMinimalPasswordLength == 0 ) {
5266 # Note that the pattern requirement will always be satisfied if the
5267 # input is empty, so we need required in all cases.
5269 # @todo FIXME: Bug 23769: This needs to not claim the password is required
5270 # if e-mail confirmation is being used. Since HTML5 input validation
5271 # is b0rked anyway in some browsers, just return nothing. When it's
5272 # re-enabled, fix this code to not output required for e-mail
5274 # $ret = array( 'required' );
5277 # We can't actually do this right now, because Opera 9.6 will print out
5278 # the entered password visibly in its error message! When other
5279 # browsers add support for this attribute, or Opera fixes its support,
5280 # we can add support with a version check to avoid doing this on Opera
5281 # versions where it will be a problem. Reported to Opera as
5282 # DSK-262266, but they don't have a public bug tracker for us to follow.
5284 if ( $wgMinimalPasswordLength > 1 ) {
5285 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
5286 $ret['title'] = wfMessage( 'passwordtooshort' )
5287 ->numParams( $wgMinimalPasswordLength )->text();
5295 * Return the list of user fields that should be selected to create
5296 * a new user object.
5299 public static function selectFields() {
5307 'user_email_authenticated',
5309 'user_email_token_expires',
5310 'user_registration',
5316 * Factory function for fatal permission-denied errors
5319 * @param string $permission User right required
5322 static function newFatalPermissionDeniedStatus( $permission ) {
5325 $groups = array_map(
5326 [ 'User', 'makeGroupLinkWiki' ],
5327 User
::getGroupsWithPermission( $permission )
5331 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5333 return Status
::newFatal( 'badaccess-group0' );
5338 * Get a new instance of this user that was loaded from the master via a locking read
5340 * Use this instead of the main context User when updating that user. This avoids races
5341 * where that user was loaded from a slave or even the master but without proper locks.
5343 * @return User|null Returns null if the user was not found in the DB
5346 public function getInstanceForUpdate() {
5347 if ( !$this->getId() ) {
5348 return null; // anon
5351 $user = self
::newFromId( $this->getId() );
5352 if ( !$user->loadFromId( self
::READ_EXCLUSIVE
) ) {
5360 * Checks if two user objects point to the same user.
5366 public function equals( User
$user ) {
5367 return $this->getName() === $user->getName();