MediaWiki  1.32.5
User Class Reference

The User object encapsulates all of the user-specific settings (user_id, name, rights, email address, options, last login time). More...

Inheritance diagram for User:
Collaboration diagram for User:

Public Member Functions

 __construct ()
 Lightweight constructor for an anonymous user. More...
 
 __toString ()
 
 getMutableCacheKeys (WANObjectCache $cache)
 
 isSafeToLoad ()
 Test if it's safe to load this User object. More...
 
 load ( $flags=self::READ_NORMAL)
 Load the user table data for this object from the source given by mFrom. More...
 
 loadFromId ( $flags=self::READ_NORMAL)
 Load user table data, given mId has already been set. More...
 
- Public Member Functions inherited from MediaWiki\User\UserIdentity
 getActorId ()
 

Static Public Member Functions

static purge ( $wikiId, $userId)
 

Public Attributes

Block $mBlock
 
string $mBlockedby
 
string $mEmail
 
string $mEmailAuthenticated
 
 $mFrom
 String Initialization data source if mLoadedItems!==true. More...
 
bool $mHideName
 
int $mId
 Cache variables. More...
 
string $mName
 
array $mOptions
 
 $mOptionsLoaded
 Bool Whether the cache variables have been loaded. More...
 
string $mRealName
 
array $mRights
 
string $mTouched
 TS_MW timestamp from the DB. More...
 
const CHECK_USER_RIGHTS = true
 
const EDIT_TOKEN_SUFFIX = Token::SUFFIX
 Global constant made accessible as class constants so that autoloader magic can be used. More...
 
const GETOPTIONS_EXCLUDE_DEFAULTS = 1
 Exclude user options that are set to their default value. More...
 
const IGNORE_USER_RIGHTS = false
 
const INVALID_TOKEN = '*** INVALID ***'
 @const string An invalid value for user_token More...
 
const TOKEN_LENGTH = 32
 @const int Number of characters in user_token field. More...
 
const VERSION = 12
 @const int Serialized record version. More...
 
- Public Attributes inherited from IDBAccessObject
const READ_LOCKING = self::READ_LATEST | 2
 Constants for object loading bitfield flags (higher => higher QoS) More...
 
const READ_NONE = -1
 

Static Public Attributes

static $idCacheByName = []
 

Protected Member Functions

 getCacheKey (WANObjectCache $cache)
 
 loadFromCache ()
 Load user data from shared cache, given mId has already been set. More...
 

Protected Attributes

int null $mActorId
 
bool $mAllowUsertalk
 
string $mBlockreason
 
string $mDatePreference
 
int $mEditCount
 
array $mEffectiveGroups
 
string $mEmailToken
 
string $mEmailTokenExpires
 
array $mFormerGroups
 
Block $mGlobalBlock
 
UserGroupMembership[] $mGroupMemberships
 Associative array of (group name => UserGroupMembership object) More...
 
string $mHash
 
array $mImplicitGroups
 
 $mLoadedItems = []
 Array with already loaded items or true if all items have been loaded. More...
 
bool $mLocked
 
 $mNewtalk
 Lazy-initialized variables, invalidated with clearInstanceCache. More...
 
array $mOptionOverrides
 
string $mQuickTouched
 TS_MW timestamp from cache. More...
 
string $mRegistration
 
string $mToken
 
int $queryFlagsUsed = self::READ_NORMAL
 User::READ_* constant bitfield used to load data. More...
 

Static Protected Attributes

static $mAllRights = false
 String Cached results of getAllRights() More...
 
static $mCacheVars
 Array of Strings List of member variables which are saved to the shared cache (memcached). More...
 
static $mCoreRights
 Array of Strings Core rights. More...
 

Private Attributes

Block $mBlockedFromCreateAccount = false
 
WebRequest $mRequest
 

newFrom*() static factory methods

 isIPRange ()
 Is the user an IP range? More...
 
 isValidPassword ( $password)
 Is the input a valid password for this user? More...
 
 getPasswordValidity ( $password)
 Given unvalidated password input, return error message on failure. More...
 
 checkPasswordValidity ( $password)
 Check if this is a valid password for this user. More...
 
 loadDefaults ( $name=false)
 Set cached properties to default. More...
 
 isItemLoaded ( $item, $all='all')
 Return whether an item has been loaded. More...
 
 trackBlockWithCookie ()
 Set the 'BlockID' cookie depending on block type and user authentication status. More...
 
 loadFromDatabase ( $flags=self::READ_LATEST)
 Load user and user_group data from the database. More...
 
 addAutopromoteOnceGroups ( $event)
 Add the user to the group if he/she meets given criteria. More...
 
 clearInstanceCache ( $reloadFrom=false)
 Clear various cached data stored in this object. More...
 
 isDnsBlacklisted ( $ip, $checkWhitelist=false)
 Whether the given IP is in a DNS blacklist. More...
 
 inDnsBlacklist ( $ip, $bases)
 Whether the given IP is in a given DNS blacklist. More...
 
 isPingLimitable ()
 Is this user subject to rate limiting? More...
 
 pingLimiter ( $action='edit', $incrBy=1)
 Primitive rate limits: enforce maximum actions per time period to put a brake on flooding. More...
 
 isBlocked ( $bFromSlave=true)
 Check if user is blocked. More...
 
 getBlock ( $bFromSlave=true)
 Get the block affecting the user, or null if the user is not blocked. More...
 
 isBlockedFrom ( $title, $bFromSlave=false)
 Check if user is blocked from editing a particular article. More...
 
 blockedBy ()
 If user is blocked, return the name of the user who placed the block. More...
 
 blockedFor ()
 If user is blocked, return the specified reason for the block. More...
 
 getBlockId ()
 If user is blocked, return the ID for the block. More...
 
 isBlockedGlobally ( $ip='')
 Check if user is blocked on all wikis. More...
 
 getGlobalBlock ( $ip='')
 Check if user is blocked on all wikis. More...
 
 isLocked ()
 Check if user account is locked. More...
 
 isHidden ()
 Check if user account is hidden. More...
 
 getId ()
 Get the user's ID. More...
 
 setId ( $v)
 Set the user and reload all fields according to a given ID. More...
 
 getName ()
 Get the user name, or the IP of an anonymous user. More...
 
 setName ( $str)
 Set the user name. More...
 
 getActorId (IDatabase $dbw=null)
 Get the user's actor ID. More...
 
 getTitleKey ()
 Get the user's name escaped by underscores. More...
 
 getNewtalk ()
 Check if the user has new messages. More...
 
 getNewMessageLinks ()
 Return the data needed to construct links for new talk page message alerts. More...
 
 getNewMessageRevisionId ()
 Get the revision ID for the last talk page revision viewed by the talk page owner. More...
 
 setNewtalk ( $val, $curRev=null)
 Update the 'You have new messages!' status. More...
 
 clearSharedCache ( $mode='changed')
 Clear user data from memcached. More...
 
 invalidateCache ()
 Immediately touch the user data cache for this account. More...
 
 touch ()
 Update the "touched" timestamp for the user. More...
 
 validateCache ( $timestamp)
 Validate the cache for this account. More...
 
 getTouched ()
 Get the user touched timestamp. More...
 
 getDBTouched ()
 Get the user_touched timestamp field (time of last DB updates) More...
 
 setPassword ( $str)
 Set the password and reset the random token. More...
 
 setInternalPassword ( $str)
 Set the password and reset the random token unconditionally. More...
 
 changeAuthenticationData (array $data)
 Changes credentials of the user. More...
 
 getToken ( $forceCreation=true)
 Get the user's current token. More...
 
 setToken ( $token=false)
 Set the random token (used for persistent authentication) Called from loadDefaults() among other places. More...
 
 setNewpassword ( $str, $throttle=true)
 Set the password for a password reminder or new account email. More...
 
 getEmail ()
 Get the user's e-mail address. More...
 
 getEmailAuthenticationTimestamp ()
 Get the timestamp of the user's e-mail authentication. More...
 
 setEmail ( $str)
 Set the user's e-mail address. More...
 
 setEmailWithConfirmation ( $str)
 Set the user's e-mail address and a confirmation mail if needed. More...
 
 getRealName ()
 Get the user's real name. More...
 
 setRealName ( $str)
 Set the user's real name. More...
 
 getOption ( $oname, $defaultOverride=null, $ignoreHidden=false)
 Get the user's current setting for a given option. More...
 
 getOptions ( $flags=0)
 Get all user's options. More...
 
 getBoolOption ( $oname)
 Get the user's current setting for a given option, as a boolean value. More...
 
 getIntOption ( $oname, $defaultOverride=0)
 Get the user's current setting for a given option, as an integer value. More...
 
 setOption ( $oname, $val)
 Set the given option for a user. More...
 
 getTokenFromOption ( $oname)
 Get a token stored in the preferences (like the watchlist one), resetting it if it's empty (and saving changes). More...
 
 resetTokenFromOption ( $oname)
 Reset a token stored in the preferences (like the watchlist one). More...
 
 getOptionKinds (IContextSource $context, $options=null)
 Return an associative array mapping preferences keys to the kind of a preference they're used for. More...
 
 resetOptions ( $resetKinds=[ 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused'], IContextSource $context=null)
 Reset certain (or all) options to the site defaults. More...
 
 getDatePreference ()
 Get the user's preferred date format. More...
 
 requiresHTTPS ()
 Determine based on the wiki configuration and the user's options, whether this user must be over HTTPS no matter what. More...
 
 getStubThreshold ()
 Get the user preferred stub threshold. More...
 
 getRights ()
 Get the permissions this user has. More...
 
 getGroups ()
 Get the list of explicit group memberships this user has. More...
 
 getGroupMemberships ()
 Get the list of explicit group memberships this user has, stored as UserGroupMembership objects. More...
 
 getEffectiveGroups ( $recache=false)
 Get the list of implicit group memberships this user has. More...
 
 getAutomaticGroups ( $recache=false)
 Get the list of implicit group memberships this user has. More...
 
 getFormerGroups ()
 Returns the groups the user has belonged to. More...
 
 getEditCount ()
 Get the user's edit count. More...
 
 addGroup ( $group, $expiry=null)
 Add the user to the given group. More...
 
 removeGroup ( $group)
 Remove the user from the given group. More...
 
 isLoggedIn ()
 Get whether the user is logged in. More...
 
 isAnon ()
 Get whether the user is anonymous. More...
 
 isBot ()
 
 isAllowedAny ()
 Check if user is allowed to access a feature / make an action. More...
 
 isAllowedAll ()
 
 isAllowed ( $action='')
 Internal mechanics of testing a permission. More...
 
 useRCPatrol ()
 Check whether to enable recent changes patrol features for this user. More...
 
 useNPPatrol ()
 Check whether to enable new pages patrol features for this user. More...
 
 useFilePatrol ()
 Check whether to enable new files patrol features for this user. More...
 
 getRequest ()
 Get the WebRequest object to use with this object. More...
 
 isWatched ( $title, $checkRights=self::CHECK_USER_RIGHTS)
 Check the watched status of an article. More...
 
 addWatch ( $title, $checkRights=self::CHECK_USER_RIGHTS)
 Watch an article. More...
 
 removeWatch ( $title, $checkRights=self::CHECK_USER_RIGHTS)
 Stop watching an article. More...
 
 clearNotification (&$title, $oldid=0)
 Clear the user's notification timestamp for the given title. More...
 
 clearAllNotifications ()
 Resets all of the given user's page-change notification timestamps. More...
 
 getExperienceLevel ()
 Compute experienced level based on edit count and registration date. More...
 
 setCookies ( $request=null, $secure=null, $rememberMe=false)
 Persist this user's session (e.g. More...
 
 logout ()
 Log this user out. More...
 
 doLogout ()
 Clear the user's session, and reset the instance cache. More...
 
 saveSettings ()
 Save this user's settings into the database. More...
 
 idForName ( $flags=0)
 If only this user's username is known, and it exists, return the user ID. More...
 
 addToDatabase ()
 Add this existing user object to the database. More...
 
 spreadAnyEditBlock ()
 If this user is logged-in and blocked, block any IP address they've successfully logged in from. More...
 
 isBlockedFromCreateAccount ()
 Get whether the user is explicitly blocked from account creation. More...
 
 isBlockedFromEmailuser ()
 Get whether the user is blocked from using Special:Emailuser. More...
 
 isAllowedToCreateAccount ()
 Get whether the user is allowed to create an account. More...
 
 getUserPage ()
 Get this user's personal page title. More...
 
 getTalkPage ()
 Get this user's talk page title. More...
 
 isNewbie ()
 Determine whether the user is a newbie. More...
 
 checkPassword ( $password)
 Check to see if the given clear-text password is one of the accepted passwords. More...
 
 checkTemporaryPassword ( $plaintext)
 Check if the given clear-text password matches the temporary password sent by e-mail for password reset operations. More...
 
 getEditTokenObject ( $salt='', $request=null)
 Initialize (if necessary) and return a session token value which can be used in edit forms to show that the user's login credentials aren't being hijacked with a foreign form submission. More...
 
 getEditToken ( $salt='', $request=null)
 Initialize (if necessary) and return a session token value which can be used in edit forms to show that the user's login credentials aren't being hijacked with a foreign form submission. More...
 
 matchEditToken ( $val, $salt='', $request=null, $maxage=null)
 Check given value against the token value stored in the session. More...
 
 matchEditTokenNoSuffix ( $val, $salt='', $request=null, $maxage=null)
 Check given value against the token value stored in the session, ignoring the suffix. More...
 
 sendConfirmationMail ( $type='created')
 Generate a new e-mail confirmation token and send a confirmation/invalidation mail to the user's given address. More...
 
 sendMail ( $subject, $body, $from=null, $replyto=null)
 Send an e-mail to this user's account. More...
 
 confirmEmail ()
 Mark the e-mail address confirmed. More...
 
 invalidateEmail ()
 Invalidate the user's e-mail confirmation, and unauthenticate the e-mail address if it was already confirmed. More...
 
 setEmailAuthenticationTimestamp ( $timestamp)
 Set the e-mail authentication timestamp. More...
 
 canSendEmail ()
 Is this user allowed to send e-mails within limits of current site configuration? More...
 
 canReceiveEmail ()
 Is this user allowed to receive e-mails within limits of current site configuration? More...
 
 isEmailConfirmed ()
 Is this user's e-mail address valid-looking and confirmed within limits of the current site configuration? More...
 
 isEmailConfirmationPending ()
 Check whether there is an outstanding request for e-mail confirmation. More...
 
 getRegistration ()
 Get the timestamp of account creation. More...
 
 getFirstEditTimestamp ()
 Get the timestamp of the first edit. More...
 
 changeableGroups ()
 Returns an array of groups that this user can add and remove. More...
 
 incEditCount ()
 Deferred version of incEditCountImmediate() More...
 
 incEditCountImmediate ()
 Increment the user's edit-count field. More...
 
 addNewUserLogEntry ( $action=false, $reason='')
 Add a newuser log entry for this user. More...
 
 addNewUserLogEntryAutoCreate ()
 Add an autocreate newuser log entry for this user Used by things like CentralAuth and perhaps other authplugins. More...
 
 getInstanceForUpdate ()
 Get a new instance of this user that was loaded from the master via a locking read. More...
 
 equals (UserIdentity $user)
 Checks if two user objects point to the same user. More...
 
static newFromName ( $name, $validate='valid')
 Static factory method for creation from username. More...
 
static newFromId ( $id)
 Static factory method for creation from a given user ID. More...
 
static newFromActorId ( $id)
 Static factory method for creation from a given actor ID. More...
 
static newFromIdentity (UserIdentity $identity)
 Returns a User object corresponding to the given UserIdentity. More...
 
static newFromAnyId ( $userId, $userName, $actorId)
 Static factory method for creation from an ID, name, and/or actor ID. More...
 
static newFromConfirmationCode ( $code, $flags=0)
 Factory method to fetch whichever user has a given email confirmation code. More...
 
static newFromSession (WebRequest $request=null)
 Create a new user object using data from session. More...
 
static newFromRow ( $row, $data=null)
 Create a new user object from a user row. More...
 
static newSystemUser ( $name, $options=[])
 Static factory method for creation of a "system" user from username. More...
 
static whoIs ( $id)
 Get the username corresponding to a given user ID. More...
 
static whoIsReal ( $id)
 Get the real name of a user given their user ID. More...
 
static idFromName ( $name, $flags=self::READ_NORMAL)
 Get database id given a user name. More...
 
static resetIdByNameCache ()
 Reset the cache used in idFromName(). More...
 
static isIP ( $name)
 Does the string match an anonymous IP address? More...
 
static isValidUserName ( $name)
 Is the input a valid username? More...
 
static isUsableName ( $name)
 Usernames which fail to pass this function will be blocked from user login and new account registrations, but may be used internally by batch processes. More...
 
static findUsersByGroup ( $groups, $limit=5000, $after=null)
 Return the users who are members of the given group(s). More...
 
static isCreatableName ( $name)
 Usernames which fail to pass this function will be blocked from new account registrations, but may be used internally either by batch processes or by user accounts which have already been created. More...
 
static getCanonicalName ( $name, $validate='valid')
 Given unvalidated user input, return a canonical username, or false if the username is invalid. More...
 
static randomPassword ()
 Return a random password. More...
 
static getDefaultOptions ()
 Combine the language default options with any site-specific options and add the default language variants. More...
 
static getDefaultOption ( $opt)
 Get a given default option value. More...
 
static isLocallyBlockedProxy ( $ip)
 Check if an IP address is in the local proxy list. More...
 
static listOptionKinds ()
 Return a list of the types of user options currently returned by User::getOptionKinds(). More...
 
static createNew ( $name, $params=[])
 Add a user to the database, return the user object. More...
 
static getGroupPermissions ( $groups)
 Get the permissions associated with a given list of groups. More...
 
static getGroupsWithPermission ( $role)
 Get all the groups who have a given permission. More...
 
static groupHasPermission ( $group, $role)
 Check, if the given group has the given permission. More...
 
static isEveryoneAllowed ( $right)
 Check if all users may be assumed to have the given permission. More...
 
static getGroupName ( $group)
 Get the localized descriptive name for a group, if it exists. More...
 
static getGroupMember ( $group, $username='#')
 Get the localized descriptive name for a member of a group, if it exists. More...
 
static getAllGroups ()
 Return the set of defined explicit groups. More...
 
static getAllRights ()
 Get a list of all available permissions. More...
 
static getImplicitGroups ()
 Get a list of implicit groups TODO: Should we deprecate this? It's trivial, but we don't want to encourage use of globals. More...
 
static getGroupPage ( $group)
 Get the title of a page describing a particular group. More...
 
static makeGroupLinkHTML ( $group, $text='')
 Create a link to the group in HTML, if available; else return the group name. More...
 
static makeGroupLinkWiki ( $group, $text='')
 Create a link to the group in Wikitext, if available; else return the group name. More...
 
static changeableByGroup ( $group)
 Returns an array of the groups that a particular group can add/remove. More...
 
static getRightDescription ( $right)
 Get the description of a given right. More...
 
static getGrantName ( $grant)
 Get the name of a given grant. More...
 
static selectFields ()
 Return the list of user fields that should be selected to create a new user object. More...
 
static getQueryInfo ()
 Return the tables, fields, and join conditions to be selected to create a new user object. More...
 
static newFatalPermissionDeniedStatus ( $permission)
 Factory function for fatal permission-denied errors. More...
 
 setItemLoaded ( $item)
 Set that an item has been loaded. More...
 
 loadFromRow ( $row, $data=null)
 Initialize this object from a row from the user table. More...
 
 loadFromUserObject ( $user)
 Load the data for this user object from another user object. More...
 
 makeUpdateConditions (Database $db, array $conditions)
 Builds update conditions. More...
 
 checkAndSetTouched ()
 Bump user_touched if it didn't change since this object was loaded. More...
 
 getBlockFromCookieValue ( $blockCookieVal)
 Try to load a Block from an ID given in a cookie value. More...
 
 checkNewtalk ( $field, $id)
 Internal uncached check for new messages. More...
 
 updateNewtalk ( $field, $id, $curRev=null)
 Add or update the new messages flag. More...
 
 deleteNewtalk ( $field, $id)
 Clear the new messages flag for the given user. More...
 
 spreadBlock ()
 If this (non-anonymous) user is blocked, block the IP address they've successfully logged in from. More...
 
 confirmationToken (&$expiration)
 Generate, store, and return a new e-mail confirmation code. More...
 
 confirmationTokenUrl ( $token)
 Return a URL the user can use to confirm their email address. More...
 
 invalidationTokenUrl ( $token)
 Return a URL the user can use to invalidate their email address. More...
 
 getTokenUrl ( $page, $token)
 Internal function to format the e-mail validation/invalidation URLs. More...
 
 initEditCount ( $add=0)
 Initialize user_editcount from data out of the revision table. More...
 
 loadOptions ( $data=null)
 Load the user options either from cache, the database or an array. More...
 
 saveOptions ()
 Saves the non-default options for this user, as previously set e.g. More...
 
 loadFromSession ()
 Load user data from the session. More...
 
 loadGroups ()
 Load the groups from the database if they aren't already loaded. More...
 
 getBlockedStatus ( $bFromSlave=true)
 Get blocking information. More...
 
 newTouchedTimestamp ()
 Generate a current or new-future timestamp to be stored in the user_touched field when we update things. More...
 
 setPasswordInternal ( $str)
 Actually set the password and such. More...
 
 updateActorId (IDatabase $dbw)
 Update the actor ID after an insert. More...
 

Detailed Description

The User object encapsulates all of the user-specific settings (user_id, name, rights, email address, options, last login time).

Client classes use the getXXX() functions to access these fields. These functions do all the work of determining whether the user is logged in, whether the requested option can be satisfied from cookies or whether a database query is needed. Most of the settings needed for rendering normal pages are set in the cookie to minimize use of the database.

Definition at line 47 of file User.php.

Constructor & Destructor Documentation

◆ __construct()

User::__construct ( )

Lightweight constructor for an anonymous user.

Use the User::newFrom* factory functions for other kinds of users.

See also
newFromName()
newFromId()
newFromActorId()
newFromConfirmationCode()
newFromSession()
newFromRow()

Definition at line 322 of file User.php.

References clearInstanceCache().

Member Function Documentation

◆ __toString()

User::__toString ( )
Returns
string

Definition at line 329 of file User.php.

References getName().

◆ addAutopromoteOnceGroups()

User::addAutopromoteOnceGroups (   $event)

Add the user to the group if he/she meets given criteria.

Contrary to autopromotion by \ref $wgAutopromote, the group will be possible to remove manually via Special:UserRights. In such case it will not be re-added automatically. The user will also not lose the group if they no longer meet the criteria.

Parameters
string$eventKey in $wgAutopromoteOnce (each one has groups/criteria)
Returns
array Array of groups the user has been promoted to.
See also
$wgAutopromoteOnce

Definition at line 1640 of file User.php.

References $wgAutopromoteOnceLogInRC, addGroup(), as, checkAndSetTouched(), captcha-old\count, Autopromote\getAutopromoteOnceGroups(), getGroupMemberships(), getGroups(), getId(), getUserPage(), Hooks\run(), and wfReadOnly().

Referenced by MediaWiki\Storage\PageUpdater\saveRevision().

◆ addGroup()

User::addGroup (   $group,
  $expiry = null 
)

Add the user to the given group.

This takes immediate effect. If the user is already in the group, the expiry time will be updated to the new expiry time. (If $expiry is omitted or null, the membership will be altered to never expire.)

Parameters
string$groupName of the group to add
string | null$expiryOptional expiry timestamp in any format acceptable to wfTimestamp(), or null if the group assignment should not expire
Returns
bool

Definition at line 3727 of file User.php.

References getEffectiveGroups(), invalidateCache(), load(), loadGroups(), Hooks\run(), and wfTimestamp().

Referenced by addAutopromoteOnceGroups().

◆ addNewUserLogEntry()

User::addNewUserLogEntry (   $action = false,
  $reason = '' 
)

Add a newuser log entry for this user.

Before 1.19 the return value was always true.

Deprecated:
since 1.27, AuthManager handles logging
Parameters
string | bool$actionAccount creation type.
  • String, one of the following values:
    • 'create' for an anonymous user creating an account for himself. This will force the action's performer to be the created user itself, no matter the value of $wgUser
    • 'create2' for a logged in user creating an account for someone else
    • 'byemail' when the created user will receive its password by e-mail
    • 'autocreate' when the user is automatically created (such as by CentralAuth).
  • Boolean means whether the account was created by e-mail (deprecated):
    • true will be converted to 'byemail'
    • false will be converted to 'create' if this object is the same as $wgUser and to 'create2' otherwise
string$reasonUser supplied reason
Returns
bool true

Definition at line 5462 of file User.php.

Referenced by addNewUserLogEntryAutoCreate().

◆ addNewUserLogEntryAutoCreate()

User::addNewUserLogEntryAutoCreate ( )

Add an autocreate newuser log entry for this user Used by things like CentralAuth and perhaps other authplugins.

Consider calling addNewUserLogEntry() directly instead.

Deprecated:
since 1.27, AuthManager handles logging
Returns
bool

Definition at line 5474 of file User.php.

References addNewUserLogEntry().

◆ addToDatabase()

User::addToDatabase ( )

Add this existing user object to the database.

If the user already exists, a fatal status object is returned, and the user object is initialised with the data from the database.

Previously, this function generated a DB error due to a key conflict if the user already existed. Many extension callers use this function in code along the lines of:

$user = User::newFromName( $name ); if ( !$user->isLoggedIn() ) { $user->addToDatabase(); } // do something with $user...

However, this was vulnerable to a race condition (T18020). By initialising the user object if the user exists, we aim to support this calling sequence as far as possible.

Note that if the user exists, this function will acquire a write lock, so it is still advisable to make the call conditional on isLoggedIn(), and to commit the transaction after calling.

Exceptions
MWException
Returns
Status

Definition at line 4377 of file User.php.

References $fname, $mId, $mName, $mRealName, clearInstanceCache(), DB_MASTER, load(), loadFromDatabase(), StatusValue\newFatal(), StatusValue\newGood(), PasswordFactory\newInvalidPassword(), newTouchedTimestamp(), saveOptions(), setToken(), updateActorId(), and wfGetDB().

Referenced by UserTest\testActorId().

◆ addWatch()

User::addWatch (   $title,
  $checkRights = self::CHECK_USER_RIGHTS 
)

Watch an article.

Since
1.22 $checkRights parameter added
Parameters
Title$titleTitle of the article to look at
bool$checkRightsWhether to check 'viewmywatchlist'/'editmywatchlist' rights. Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.

Definition at line 3934 of file User.php.

References $title, invalidateCache(), and isAllowed().

Referenced by LocalFile\recordUpload().

◆ blockedBy()

User::blockedBy ( )

If user is blocked, return the name of the user who placed the block.

Returns
string Name of blocker

Definition at line 2323 of file User.php.

References $mBlockedby, and getBlockedStatus().

Referenced by SpecialBlock\checkUnblockSelf(), and UserTest\testBlockInstanceCache().

◆ blockedFor()

User::blockedFor ( )

If user is blocked, return the specified reason for the block.

Returns
string Blocking reason

Definition at line 2332 of file User.php.

References $mBlockreason, and getBlockedStatus().

Referenced by UserTest\testBlockInstanceCache().

◆ canReceiveEmail()

User::canReceiveEmail ( )

Is this user allowed to receive e-mails within limits of current site configuration?

Returns
bool

Definition at line 4868 of file User.php.

References getOption(), and isEmailConfirmed().

◆ canSendEmail()

User::canSendEmail ( )

Is this user allowed to send e-mails within limits of current site configuration?

Returns
bool

Definition at line 4851 of file User.php.

References $user, $wgEnableEmail, $wgEnableUserEmail, isAllowed(), isEmailConfirmed(), and Hooks\run().

◆ changeableByGroup()

static User::changeableByGroup (   $group)
static

Returns an array of the groups that a particular group can add/remove.

Parameters
string$groupThe group to check for whether it can add/remove
Returns
array Array( 'add' => array( addablegroups ), 'remove' => array( removablegroups ), 'add-self' => array( addablegroups to self), 'remove-self' => array( removable groups from self) )

Definition at line 5214 of file User.php.

References $value, $wgAddGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf, $wgRemoveGroups, as, and getAllGroups().

Referenced by changeableGroups().

◆ changeableGroups()

User::changeableGroups ( )

Returns an array of groups that this user can add and remove.

Returns
array Array( 'add' => array( addablegroups ), 'remove' => array( removablegroups ), 'add-self' => array( addablegroups to self), 'remove-self' => array( removable groups from self) )

Definition at line 5287 of file User.php.

References as, changeableByGroup(), getEffectiveGroups(), and isAllowed().

◆ changeAuthenticationData()

User::changeAuthenticationData ( array  $data)

Changes credentials of the user.

This is a convenience wrapper around AuthManager::changeAuthenticationData. Note that this can return a status that isOK() but not isGood() on certain types of failures, e.g. when no provider handled the change.

Parameters
array$dataA set of authentication data in fieldname => value format. This is the same data you would pass the changeauthenticationdata API - 'username', 'password' etc.
Returns
Status
Since
1.27

Definition at line 2959 of file User.php.

References $req, as, StatusValue\newGood(), and true.

Referenced by setPasswordInternal().

◆ checkAndSetTouched()

User::checkAndSetTouched ( )
protected

Bump user_touched if it didn't change since this object was loaded.

On success, the mTouched field is updated. The user serialization cache is always cleared.

Returns
bool Whether user_touched was actually updated
Since
1.26

Definition at line 1710 of file User.php.

References $success, clearSharedCache(), DB_MASTER, load(), makeUpdateConditions(), newTouchedTimestamp(), and wfGetDB().

Referenced by addAutopromoteOnceGroups(), and UserTest\testCheckAndSetTouched().

◆ checkNewtalk()

User::checkNewtalk (   $field,
  $id 
)
protected

Internal uncached check for new messages.

See also
getNewtalk()
Parameters
string$field'user_ip' for anonymous users, 'user_id' otherwise
string | int$idUser's IP address for anonymous users, User ID otherwise
Returns
bool True if the user has new messages

Definition at line 2665 of file User.php.

References $dbr, DB_REPLICA, and wfGetDB().

Referenced by getNewtalk().

◆ checkPassword()

User::checkPassword (   $password)

Check to see if the given clear-text password is one of the accepted passwords.

Deprecated:
since 1.27, use AuthManager instead
Parameters
string$passwordUser password
Returns
bool True if the given password is correct, otherwise False

Definition at line 4568 of file User.php.

References $res, MediaWiki\Logger\LoggerFactory\getInstance(), getName(), and wfDeprecated().

Referenced by checkTemporaryPassword().

◆ checkPasswordValidity()

User::checkPasswordValidity (   $password)

Check if this is a valid password for this user.

Create a Status object based on the password's validity. The Status should be set to fatal if the user should not be allowed to log in, and should have any errors that would block changing the password.

If the return value of this is not OK, the password should not be checked. If the return value is not Good, the password can be checked, but the user should not be able to set their password to this.

Parameters
string$passwordDesired password
Returns
Status
Since
1.23

Definition at line 1198 of file User.php.

References $wgPasswordPolicy, StatusValue\newGood(), and Hooks\run().

Referenced by getPasswordValidity(), and UserTest\testCheckPasswordValidity().

◆ checkTemporaryPassword()

User::checkTemporaryPassword (   $plaintext)

Check if the given clear-text password matches the temporary password sent by e-mail for password reset operations.

Deprecated:
since 1.27, use AuthManager instead
Parameters
string$plaintext
Returns
bool True if matches, false otherwise

Definition at line 4603 of file User.php.

References checkPassword(), and wfDeprecated().

◆ clearAllNotifications()

User::clearAllNotifications ( )

Resets all of the given user's page-change notification timestamps.

If e-notif e-mails are on, they will receive notification mails on the next change of any watched page.

Note
If the user doesn't have 'editmywatchlist', this will do nothing.

Definition at line 4036 of file User.php.

References $wgShowUpdatedMarker, $wgUseEnotif, getId(), isAllowed(), setNewtalk(), and wfReadOnly().

◆ clearInstanceCache()

User::clearInstanceCache (   $reloadFrom = false)

Clear various cached data stored in this object.

The cache of the user table data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.

Parameters
bool | string$reloadFromReload user and user_groups table data from a given source. May be "name", "id", "actor", "defaults", "session", or false for no reload.

Definition at line 1748 of file User.php.

Referenced by __construct(), addToDatabase(), doLogout(), setId(), and UserTest\testBlockInstanceCache().

◆ clearNotification()

User::clearNotification ( $title,
  $oldid = 0 
)

Clear the user's notification timestamp for the given title.

If e-notif e-mails are on, they will receive notification mails on the next change of the page if it's watched etc.

Note
If the user doesn't have 'editmywatchlist', this will do nothing.
Parameters
Title&$titleTitle of the article to look at
int$oldidThe revision id being viewed. If not given or 0, latest revision is assumed.

Definition at line 3968 of file User.php.

References $title, $user, $wgShowUpdatedMarker, $wgUseEnotif, DeferredUpdates\addCallableUpdate(), Title\GAID_FOR_UPDATE, getName(), getNewtalk(), isAllowed(), isAnon(), Revision\newFromId(), NS_USER_TALK, Hooks\run(), setNewtalk(), use, and wfReadOnly().

◆ clearSharedCache()

User::clearSharedCache (   $mode = 'changed')

Clear user data from memcached.

Use after applying updates to the database; caller's responsibility to update user_touched if appropriate.

Called implicitly from invalidateCache() and saveSettings().

Parameters
string$modeUse 'refresh' to clear now; otherwise before DB commit

Definition at line 2778 of file User.php.

References $cache, DB_MASTER, getCacheKey(), getId(), ObjectCache\getMainWANInstance(), and use.

Referenced by checkAndSetTouched(), invalidateCache(), and saveSettings().

◆ confirmationToken()

User::confirmationToken ( $expiration)
protected

Generate, store, and return a new e-mail confirmation code.

A hash (unsalted, since it's used as a key) is stored.

Note
Call saveSettings() after calling this function to commit this change to the database.
Parameters
string&$expirationAccepts the expiration time
Returns
string New token

Definition at line 4751 of file User.php.

References $wgUserEmailConfirmationTokenExpiry, MWCryptRand\generateHex(), load(), and wfTimestamp().

Referenced by sendConfirmationMail().

◆ confirmationTokenUrl()

User::confirmationTokenUrl (   $token)
protected

Return a URL the user can use to confirm their email address.

Parameters
string$tokenAccepts the email confirmation token
Returns
string New token URL

Definition at line 4769 of file User.php.

References getTokenUrl().

Referenced by sendConfirmationMail().

◆ confirmEmail()

User::confirmEmail ( )

Mark the e-mail address confirmed.

Note
Call saveSettings() after calling this function to commit the change.
Returns
bool

Definition at line 4809 of file User.php.

References isEmailConfirmed(), Hooks\run(), setEmailAuthenticationTimestamp(), and wfTimestampNow().

◆ createNew()

static User::createNew (   $name,
  $params = [] 
)
static

Add a user to the database, return the user object.

Parameters
string$nameUsername to add
array$paramsArray of Strings Non-default parameters to save to the database as user_* fields:
  • email: The user's email address.
  • email_authenticated: The email authentication timestamp.
  • real_name: The user's real name.
  • options: An associative array of non-default options.
  • token: Random authentication token. Do not set.
  • registration: Registration timestamp. Do not set.
Returns
User|null User object, or null if the username already exists.

Definition at line 4301 of file User.php.

References $fname, $name, $params, $user, $value, array(), as, DB_MASTER, newFromId(), PasswordFactory\newInvalidPassword(), use, User, wfDeprecated(), and wfGetDB().

Referenced by UserWrapper\__construct(), TestUser\__construct(), ApiQueryUserContribsTest\addDBDataOnce(), ChangesListSpecialPageTest\createUsers(), newSystemUser(), TitlePermissionTest\setUp(), UserTest\testActorId(), CoreParserFunctionsTest\testGender(), ImportTest\testUnknownUserHandling(), and RevisionDbTestBase\testUserWasLastToEdit().

◆ deleteNewtalk()

User::deleteNewtalk (   $field,
  $id 
)
protected

Clear the new messages flag for the given user.

Parameters
string$field'user_ip' for anonymous users, 'user_id' otherwise
string | int$idUser's IP address for anonymous users, User ID otherwise
Returns
bool True if successful, false otherwise

Definition at line 2705 of file User.php.

References DB_MASTER, wfDebug(), and wfGetDB().

Referenced by setNewtalk().

◆ doLogout()

User::doLogout ( )

Clear the user's session, and reset the instance cache.

See also
logout()

Definition at line 4152 of file User.php.

References clearInstanceCache(), MediaWiki\Logger\LoggerFactory\getInstance(), and getRequest().

Referenced by logout().

◆ equals()

User::equals ( UserIdentity  $user)

Checks if two user objects point to the same user.

Since
1.25 ; takes a UserIdentity instead of a User since 1.32
Parameters
UserIdentity$user
Returns
bool

Implements MediaWiki\User\UserIdentity.

Definition at line 5740 of file User.php.

References MediaWiki\User\UserIdentity\getName(), and getName().

Referenced by UserTest\testFindUsersByGroup().

◆ findUsersByGroup()

static User::findUsersByGroup (   $groups,
  $limit = 5000,
  $after = null 
)
static

Return the users who are members of the given group(s).

In case of multiple groups, users who are members of at least one of them are returned.

Parameters
string | array$groupsA single group name or an array of group names
int$limitMax number of users to return. The actual limit will never exceed 5000 records; larger values are ignored.
int | null$afterID the user to start after
Returns
UserArrayFromResult

Definition at line 1081 of file User.php.

References $dbr, array(), DB_REPLICA, UserArray\newFromIDs(), and wfGetDB().

Referenced by EmptyUserGroup\execute(), and UserTest\testFindUsersByGroup().

◆ getActorId()

User::getActorId ( IDatabase  $dbw = null)

Get the user's actor ID.

Since
1.31
Parameters
IDatabase | null$dbwAssign a new actor ID, using this DB handle, if none exists
Returns
int The actor's ID, or 0 if no actor ID exists and $dbw was null

Definition at line 2500 of file User.php.

References $mActorId, $options, $wgActorTableSchemaMigrationStage, DBAccessObjectUtils\getDBOptions(), getId(), getName(), invalidateCache(), isItemLoaded(), list, load(), SCHEMA_COMPAT_WRITE_NEW, setItemLoaded(), string, and wfGetDB().

Referenced by LocalFile\recordUpload2(), UserTest\testActorId(), UserTest\testNewFromAnyId(), and UserTest\testNewFromIdentity().

◆ getAllGroups()

static User::getAllGroups ( )
static

Return the set of defined explicit groups.

The implicit groups (by default *, 'user' and 'autoconfirmed') are not included, as they are defined automatically, not in the database.

Returns
array Array of internal group names

Definition at line 5107 of file User.php.

References $wgGroupPermissions, and $wgRevokePermissions.

Referenced by UsersPager\__construct(), SpecialActiveUsers\buildForm(), changeableByGroup(), CreateAndPromote\execute(), SpecialListGroupRights\formatPermissions(), ApiUserrights\getAllGroups(), UsersPager\getAllGroups(), UserrightsPage\getAllGroups(), ApiQueryContributors\getAllowedParams(), ApiQueryAllUsers\getAllowedParams(), SpecialListUsers\getSubpagesForPrefixSearch(), and ApiQuerySiteinfoTest\testUserGroups().

◆ getAllRights()

static User::getAllRights ( )
static

◆ getAutomaticGroups()

User::getAutomaticGroups (   $recache = false)

Get the list of implicit group memberships this user has.

This includes 'user' if logged in, '*' for all accounts, and autopromoted groups

Parameters
bool$recacheWhether to avoid the cache
Returns
array Array of String internal group names

Definition at line 3639 of file User.php.

References $mImplicitGroups, Autopromote\getAutopromoteGroups(), and getId().

Referenced by getEffectiveGroups().

◆ getBlock()

User::getBlock (   $bFromSlave = true)

Get the block affecting the user, or null if the user is not blocked.

Parameters
bool$bFromSlaveWhether to check the replica DB instead of the master
Returns
Block|null

Definition at line 2290 of file User.php.

References getBlockedStatus().

Referenced by isBlocked(), UserTest\testBlockInstanceCache(), and trackBlockWithCookie().

◆ getBlockedStatus()

User::getBlockedStatus (   $bFromSlave = true)
private

Get blocking information.

Parameters
bool$bFromSlaveWhether to check the replica DB first. To improve performance, non-critical checks are done against replica DBs. Check when actually saving should be done against master.

Definition at line 1833 of file User.php.

References $wgApplyIpBlocksToXff, $wgProxyWhitelist, $wgSoftBlockRanges, Block\chooseBlock(), getBlockFromCookieValue(), Block\getBlocksForIPList(), RequestContext\getMain(), getName(), getRequest(), isAllowed(), isAnon(), isDnsBlacklisted(), IP\isInRanges(), load(), Block\newFromTarget(), plain, Hooks\run(), IP\sanitizeIP(), text, wfDebug(), and wfMessage().

Referenced by blockedBy(), blockedFor(), getBlock(), getBlockId(), isBlockedFromCreateAccount(), isBlockedFromEmailuser(), and isHidden().

◆ getBlockFromCookieValue()

User::getBlockFromCookieValue (   $blockCookieVal)
protected

Try to load a Block from an ID given in a cookie value.

Parameters
string | null$blockCookieValThe cookie value to check.
Returns
Block|bool The Block object, or false if none could be loaded.

Definition at line 1949 of file User.php.

References Block\clearCookie(), Block\getIdFromCookieValue(), RequestContext\getMain(), getRequest(), isLoggedIn(), Block\newFromID(), true, Block\TYPE_IP, Block\TYPE_RANGE, and Block\TYPE_USER.

Referenced by getBlockedStatus().

◆ getBlockId()

User::getBlockId ( )

If user is blocked, return the ID for the block.

Returns
int Block ID

Definition at line 2341 of file User.php.

References false, and getBlockedStatus().

Referenced by UserTest\testAutoblockCookiesDisabled().

◆ getBoolOption()

User::getBoolOption (   $oname)

Get the user's current setting for a given option, as a boolean value.

Parameters
string$onameThe option to check
Returns
bool User's current value for the option
See also
getOption()

Definition at line 3230 of file User.php.

References getOption().

Referenced by requiresHTTPS().

◆ getCacheKey()

User::getCacheKey ( WANObjectCache  $cache)
protected
Since
1.27
Parameters
WANObjectCache$cache
Returns
string

Definition at line 505 of file User.php.

References $cache, and $mId.

Referenced by clearSharedCache(), getMutableCacheKeys(), and loadFromCache().

◆ getCanonicalName()

static User::getCanonicalName (   $name,
  $validate = 'valid' 
)
static

Given unvalidated user input, return a canonical username, or false if the username is invalid.

Parameters
string$nameUser input
string | bool$validateType of validation to use:
  • false No validation
  • 'valid' Valid for batch processes
  • 'usable' Valid for batch processes and login
  • 'creatable' Valid for batch processes, login and account creation
Exceptions
InvalidArgumentException
Returns
bool|string

Definition at line 1238 of file User.php.

References $name, $t, false, Title\makeTitle(), Title\newFromText(), and NS_USER.

Referenced by SimpleCaptcha\badLoginPerUserKey(), MediaWiki\Auth\AuthPluginPrimaryAuthenticationProvider\beginPrimaryAccountCreation(), MediaWiki\Auth\LocalPasswordPrimaryAuthenticationProvider\beginPrimaryAuthentication(), MediaWiki\Auth\TemporaryPasswordPrimaryAuthenticationProvider\beginPrimaryAuthentication(), MediaWiki\Auth\AuthPluginPrimaryAuthenticationProvider\beginPrimaryAuthentication(), LoginForm\clearLoginThrottle(), ApiQueryUserContribs\execute(), DeletedContributionsPage\execute(), RollbackEdits\execute(), UserrightsPage\execute(), ApiQueryUsers\execute(), UserrightsPage\fetchUser(), ApiRollback\getRbUser(), LoginForm\incrementLoginThrottle(), DeleteLocalPasswords\initialize(), newFromName(), newSystemUser(), ApiQueryBlocks\prepareUsername(), MediaWiki\Auth\LocalPasswordPrimaryAuthenticationProvider\providerAllowsAuthenticationDataChange(), MediaWiki\Auth\TemporaryPasswordPrimaryAuthenticationProvider\providerAllowsAuthenticationDataChange(), MediaWiki\Auth\AuthPluginPrimaryAuthenticationProvider\providerAllowsAuthenticationDataChange(), MediaWiki\Auth\LocalPasswordPrimaryAuthenticationProvider\providerChangeAuthenticationData(), MediaWiki\Auth\TemporaryPasswordPrimaryAuthenticationProvider\providerChangeAuthenticationData(), MediaWiki\Auth\AuthPluginPrimaryAuthenticationProvider\providerChangeAuthenticationData(), MediaWiki\Auth\AbstractPrimaryAuthenticationProvider\providerNormalizeUsername(), MediaWiki\Auth\AuthPluginPrimaryAuthenticationProvider\providerRevokeAccessForUser(), WebInstallerName\submit(), MediaWiki\Session\CookieSessionProvider\suggestLoginUsername(), UserTest\testGetCanonicalName(), MediaWiki\Auth\LocalPasswordPrimaryAuthenticationProvider\testUserCanAuthenticate(), MediaWiki\Auth\TemporaryPasswordPrimaryAuthenticationProvider\testUserCanAuthenticate(), MediaWiki\Auth\AuthPluginPrimaryAuthenticationProvider\testUserCanAuthenticate(), MediaWiki\Auth\LocalPasswordPrimaryAuthenticationProvider\testUserExists(), MediaWiki\Auth\TemporaryPasswordPrimaryAuthenticationProvider\testUserExists(), MediaWiki\Auth\AuthPluginPrimaryAuthenticationProvider\testUserExists(), and ApiBase\validateUser().

◆ getDatePreference()

User::getDatePreference ( )

Get the user's preferred date format.

Returns
string User's preferred date format

Definition at line 3494 of file User.php.

References $mDatePreference, $value, $wgLang, and getOption().

Referenced by Language\getHumanTimestampInternal().

◆ getDBTouched()

User::getDBTouched ( )

Get the user_touched timestamp field (time of last DB updates)

Returns
string TS_MW Timestamp
Since
1.26

Definition at line 2873 of file User.php.

References $mTouched, and load().

Referenced by UserTest\testCheckAndSetTouched().

◆ getDefaultOption()

static User::getDefaultOption (   $opt)
static

Get a given default option value.

Parameters
string$optName of option to retrieve
Returns
string Default option value

Definition at line 1818 of file User.php.

References $opt, and getDefaultOptions().

Referenced by ConvertUserOptions\convertOptionBatch(), Language\dateFormat(), CoreParserFunctions\gender(), GenderCache\getDefault(), ParserOptions\getDefaults(), ImagePage\getImageLimitsFromOption(), getOption(), getOptions(), Linker\makeImageLink(), CreatePdfThumbnailsJob\run(), saveOptions(), and setOption().

◆ getDefaultOptions()

◆ getEditCount()

User::getEditCount ( )

Get the user's edit count.

Returns
int|null Null for anonymous users

Definition at line 3692 of file User.php.

References $dbr, $mEditCount, DB_REPLICA, getId(), initEditCount(), and wfGetDB().

Referenced by getExperienceLevel(), incEditCountImmediate(), loadFromDatabase(), UserTest\testGetEditCount(), and UserTest\testGetEditCountForAnons().

◆ getEditToken()

User::getEditToken (   $salt = '',
  $request = null 
)

Initialize (if necessary) and return a session token value which can be used in edit forms to show that the user's login credentials aren't being hijacked with a foreign form submission.

The $salt for 'edit' and 'csrf' tokens is the default (empty string).

Since
1.19
Parameters
string | array$saltArray of Strings Optional function-specific data for hashing
WebRequest | null$requestWebRequest object to use or null to use $wgRequest
Returns
string The new edit token

Definition at line 4644 of file User.php.

References $request, and getEditTokenObject().

◆ getEditTokenObject()

User::getEditTokenObject (   $salt = '',
  $request = null 
)

Initialize (if necessary) and return a session token value which can be used in edit forms to show that the user's login credentials aren't being hijacked with a foreign form submission.

Since
1.27
Parameters
string | array$saltArray of Strings Optional function-specific data for hashing
WebRequest | null$requestWebRequest object to use or null to use $wgRequest
Returns
MediaWiki\Session\Token The new edit token

Definition at line 4620 of file User.php.

References $request, getRequest(), and isAnon().

Referenced by getEditToken(), and matchEditToken().

◆ getEffectiveGroups()

User::getEffectiveGroups (   $recache = false)

Get the list of implicit group memberships this user has.

This includes all explicit groups, plus 'user' if logged in, '*' for all accounts, and autopromoted groups

Parameters
bool$recacheWhether to avoid the cache
Returns
array Array of String internal group names

Definition at line 3616 of file User.php.

References $mEffectiveGroups, $user, getAutomaticGroups(), getGroups(), and Hooks\run().

Referenced by addGroup(), changeableGroups(), getRights(), and removeGroup().

◆ getEmail()

User::getEmail ( )

Get the user's e-mail address.

Returns
string User's email address

Definition at line 3052 of file User.php.

References $mEmail, load(), and Hooks\run().

Referenced by setEmailWithConfirmation().

◆ getEmailAuthenticationTimestamp()

User::getEmailAuthenticationTimestamp ( )

Get the timestamp of the user's e-mail authentication.

Returns
string TS_MW timestamp

Definition at line 3062 of file User.php.

References $mEmailAuthenticated, load(), and Hooks\run().

Referenced by isEmailConfirmed().

◆ getExperienceLevel()

User::getExperienceLevel ( )

Compute experienced level based on edit count and registration date.

Returns
string 'newcomer', 'learner', or 'experienced'

Definition at line 4065 of file User.php.

References $wgExperiencedUserEdits, $wgExperiencedUserMemberSince, $wgLearnerEdits, $wgLearnerMemberSince, getEditCount(), getRegistration(), isAnon(), and wfTimestamp().

Referenced by UserTest\testExperienceLevel(), and UserTest\testExperienceLevelAnon().

◆ getFirstEditTimestamp()

User::getFirstEditTimestamp ( )

Get the timestamp of the first edit.

Returns
string|bool Timestamp of first edit, or false for non-existent/anonymous user accounts.

Definition at line 4937 of file User.php.

References $dbr, $time, DB_REPLICA, getId(), ActorMigration\newMigration(), wfGetDB(), and wfTimestamp().

◆ getFormerGroups()

User::getFormerGroups ( )

Returns the groups the user has belonged to.

The user may still belong to the returned groups. Compare with getGroups().

The function will not return groups the user had belonged to before MW 1.17

Returns
array Names of the groups the user has belonged to.

Definition at line 3668 of file User.php.

References $mFormerGroups, $res, as, DB_MASTER, DB_REPLICA, load(), and wfGetDB().

◆ getGlobalBlock()

User::getGlobalBlock (   $ip = '')

Check if user is blocked on all wikis.

Do not use for actual edit permission checks! This is intended for quick UI checks.

Parameters
string$ipIP address, uses current client if none given
Returns
Block|null Block object if blocked, null otherwise
Exceptions
FatalError
MWException

Definition at line 2368 of file User.php.

References $user, getName(), getRequest(), IP\isIPAddress(), and Hooks\run().

Referenced by isBlockedGlobally().

◆ getGrantName()

static User::getGrantName (   $grant)
static

Get the name of a given grant.

Since
1.29
Parameters
string$grantGrant to query
Returns
string Localized name of the grant

Definition at line 5436 of file User.php.

References wfMessage().

Referenced by SpecialListGrants\execute().

◆ getGroupMember()

static User::getGroupMember (   $group,
  $username = '#' 
)
static

Get the localized descriptive name for a member of a group, if it exists.

Deprecated:
since 1.29 Use UserGroupMembership::getGroupMemberName instead
Parameters
string$groupInternal group name
string$usernameUsername for gender (since 1.19)
Returns
string Localized name for group member

Definition at line 5096 of file User.php.

References $username, UserGroupMembership\getGroupMemberName(), and wfDeprecated().

◆ getGroupMemberships()

User::getGroupMemberships ( )

Get the list of explicit group memberships this user has, stored as UserGroupMembership objects.

Implicit groups are not included.

Returns
UserGroupMembership[] Associative array of (group name => UserGroupMembership object)
Since
1.29

Definition at line 3603 of file User.php.

References $mGroupMemberships, load(), and loadGroups().

Referenced by addAutopromoteOnceGroups().

◆ getGroupName()

static User::getGroupName (   $group)
static

Get the localized descriptive name for a group, if it exists.

Deprecated:
since 1.29 Use UserGroupMembership::getGroupName instead
Parameters
string$groupInternal group name
Returns
string Localized descriptive group name

Definition at line 5083 of file User.php.

References UserGroupMembership\getGroupName(), and wfDeprecated().

◆ getGroupPage()

static User::getGroupPage (   $group)
static

Get the title of a page describing a particular group.

Deprecated:
since 1.29 Use UserGroupMembership::getGroupPage instead
Parameters
string$groupInternal group name
Returns
Title|bool Title of the page if it exists, false otherwise

Definition at line 5150 of file User.php.

References UserGroupMembership\getGroupPage(), and wfDeprecated().

◆ getGroupPermissions()

static User::getGroupPermissions (   $groups)
static

Get the permissions associated with a given list of groups.

Parameters
array$groupsArray of Strings List of internal group names
Returns
array Array of Strings List of permission key names for given groups combined

Definition at line 4963 of file User.php.

References $wgGroupPermissions, $wgRevokePermissions, and as.

Referenced by Autopromote\checkCondition(), ApiQueryAllUsers\execute(), getRights(), UserTest\testGroupPermissions(), UserTest\testRevokePermissions(), and wfStreamThumb().

◆ getGroups()

User::getGroups ( )

Get the list of explicit group memberships this user has.

The implicit * and user groups are not included.

Returns
array Array of String internal group names

Definition at line 3590 of file User.php.

References load(), and loadGroups().

Referenced by addAutopromoteOnceGroups(), getEffectiveGroups(), isBot(), and pingLimiter().

◆ getGroupsWithPermission()

static User::getGroupsWithPermission (   $role)
static

Get all the groups who have a given permission.

Parameters
string$roleRole to check
Returns
array Array of Strings List of internal group names with the given permission

Definition at line 4990 of file User.php.

References $wgGroupPermissions, and as.

Referenced by PermissionsError\__construct(), ApiQueryAllUsers\execute(), ApiQueryContributors\execute(), NewFilesPager\getQueryInfo(), ContribsPager\getQueryInfo(), MWNamespace\getRestrictionLevels(), ApiMain\modifyHelp(), RebuildRecentchanges\rebuildRecentChangesTablePass4(), ApiQueryAllImages\run(), and UserTest\testGetGroupsWithPermission().

◆ getId()

◆ getImplicitGroups()

static User::getImplicitGroups ( )
static

Get a list of implicit groups TODO: Should we deprecate this? It's trivial, but we don't want to encourage use of globals.

Returns
array Array of Strings Array of internal group names

Definition at line 5138 of file User.php.

References $wgImplicitGroups.

◆ getInstanceForUpdate()

User::getInstanceForUpdate ( )

Get a new instance of this user that was loaded from the master via a locking read.

Use this instead of the main context User when updating that user. This avoids races where that user was loaded from a replica DB or even the master but without proper locks.

Returns
User|null Returns null if the user was not found in the DB
Since
1.27

Definition at line 5720 of file User.php.

References $user, getId(), and newFromId().

◆ getIntOption()

User::getIntOption (   $oname,
  $defaultOverride = 0 
)

Get the user's current setting for a given option, as an integer value.

Parameters
string$onameThe option to check
int$defaultOverrideA default value returned if the option does not exist
Returns
int User's current value for the option
See also
getOption()

Definition at line 3242 of file User.php.

References getOption().

Referenced by getStubThreshold().

◆ getMutableCacheKeys()

User::getMutableCacheKeys ( WANObjectCache  $cache)
Parameters
WANObjectCache$cache
Returns
string[]
Since
1.28

Definition at line 517 of file User.php.

References getCacheKey(), and getId().

◆ getName()

◆ getNewMessageLinks()

User::getNewMessageLinks ( )

Return the data needed to construct links for new talk page message alerts.

If there are new messages, this will return an associative array with the following data: wiki: The database name of the wiki link: Root-relative link to the user's talk page rev: The last talk page revision that the user has seen or null. This is useful for building diff links. If there are no new messages, it returns an empty array.

Note
This function was designed to accomodate multiple talk pages, but currently only returns a single link and revision.
Returns
array

Definition at line 2613 of file User.php.

References $dbr, $rev, $user, DB_REPLICA, getId(), getName(), getNewtalk(), getTalkPage(), isAnon(), Revision\loadFromTimestamp(), Hooks\run(), wfGetDB(), and wfWikiID().

Referenced by getNewMessageRevisionId().

◆ getNewMessageRevisionId()

User::getNewMessageRevisionId ( )

Get the revision ID for the last talk page revision viewed by the talk page owner.

Returns
int|null Revision ID or null

Definition at line 2638 of file User.php.

References captcha-old\count, getNewMessageLinks(), and wfWikiID().

◆ getNewtalk()

User::getNewtalk ( )

Check if the user has new messages.

Returns
bool True if the user has new messages

Definition at line 2575 of file User.php.

References $mNewtalk, $wgDisableAnonTalk, checkNewtalk(), getName(), load(), and page.

Referenced by clearNotification(), and getNewMessageLinks().

◆ getOption()

User::getOption (   $oname,
  $defaultOverride = null,
  $ignoreHidden = false 
)

Get the user's current setting for a given option.

Parameters
string$onameThe option to check
string | array | null$defaultOverrideA default value returned if the option does not exist
bool$ignoreHiddenWhether to ignore the effects of $wgHiddenPrefs
Returns
string|array|int|null User's current value for the option
See also
getBoolOption()
getIntOption()

Reimplemented in PPFuzzUser.

Definition at line 3171 of file User.php.

References $wgHiddenPrefs, getDefaultOption(), and loadOptions().

Referenced by canReceiveEmail(), getBoolOption(), getDatePreference(), getIntOption(), RequestContext\getLanguage(), getTokenFromOption(), and UserTest\testOptions().

◆ getOptionKinds()

User::getOptionKinds ( IContextSource  $context,
  $options = null 
)

Return an associative array mapping preferences keys to the kind of a preference they're used for.

Different kinds are handled differently when setting or reading preferences.

See User::listOptionKinds for the list of valid option types that can be provided.

See also
User::listOptionKinds
Parameters
IContextSource$context
array | null$optionsAssoc. array with options keys to check as keys. Defaults to $this->mOptions.
Returns
array The key => kind mapping data

Definition at line 3364 of file User.php.

References $context, $mOptions, $name, $options, $rows, $value, as, class, HTMLFormField\flattenOptions(), loadOptions(), and true.

Referenced by resetOptions().

◆ getOptions()

User::getOptions (   $flags = 0)

Get all user's options.

Parameters
int$flagsBitwise combination of: User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set to the default value. (Since 1.25)
Returns
array

Definition at line 3199 of file User.php.

References $mOptions, $options, $wgHiddenPrefs, as, getDefaultOption(), and loadOptions().

◆ getPasswordValidity()

User::getPasswordValidity (   $password)

Given unvalidated password input, return error message on failure.

Parameters
string$passwordDesired password
Returns
bool|string|array True on success, string or array of error message on failure

Definition at line 1162 of file User.php.

References $messages, as, checkPasswordValidity(), and captcha-old\count.

Referenced by isValidPassword(), and UserTest\testCheckPasswordValidity().

◆ getQueryInfo()

static User::getQueryInfo ( )
static

Return the tables, fields, and join conditions to be selected to create a new user object.

Since
1.31
Returns
array With three keys:
  • tables: (string[]) to include in the $table to IDatabase->select()
  • fields: (string[]) to include in the $vars to IDatabase->select()
  • joins: (array) to include in the $join_conds to IDatabase->select()

Definition at line 5654 of file User.php.

References $ret, $wgActorTableSchemaMigrationStage, SCHEMA_COMPAT_NEW, and SCHEMA_COMPAT_READ_NEW.

Referenced by ApiQueryUsers\execute(), PasswordReset\getUsersByEmail(), loadFromDatabase(), UserArray\newFromIDs(), UserArray\newFromNames(), newSystemUser(), RebuildRecentchanges\rebuildRecentChangesTablePass4(), and UserTest\testExperienceLevel().

◆ getRealName()

User::getRealName ( )

Get the user's real name.

Returns
string User's real name

Definition at line 3144 of file User.php.

References $mRealName, isItemLoaded(), and load().

Referenced by CreditsAction\userLink().

◆ getRegistration()

User::getRegistration ( )

Get the timestamp of account creation.

Returns
string|bool|null Timestamp of account creation, false for non-existent/anonymous user accounts, or null if existing account but information is not in database.

Definition at line 4923 of file User.php.

References $mRegistration, isAnon(), and load().

Referenced by getExperienceLevel().

◆ getRequest()

◆ getRightDescription()

static User::getRightDescription (   $right)
static

Get the description of a given right.

Since
1.29
Parameters
string$rightRight to query
Returns
string Localized description of the right

Definition at line 5423 of file User.php.

References wfMessage().

Referenced by SpecialListGrants\execute(), SpecialListGroupRights\formatPermissions(), and SpecialListGroupRights\outputNamespaceProtectionInfo().

◆ getRights()

User::getRights ( )

Get the permissions this user has.

Returns
string[] permission names

Definition at line 3548 of file User.php.

References $mRights, getEffectiveGroups(), getGroupPermissions(), RequestContext\getMain(), getRequest(), isBlocked(), isLoggedIn(), Hooks\run(), and User.

Referenced by isAllowed(), and UserTest\testUserGetRightsHooks().

◆ getStubThreshold()

User::getStubThreshold ( )

Get the user preferred stub threshold.

Returns
int

Definition at line 3533 of file User.php.

References $wgMaxArticleSize, article, getIntOption(), and in.

Referenced by MediaWiki\Linker\LinkRendererFactory\createForUser().

◆ getTalkPage()

User::getTalkPage ( )

Get this user's talk page title.

Returns
Title User's talk page title

Definition at line 4548 of file User.php.

References $title, and getUserPage().

Referenced by getNewMessageLinks().

◆ getTitleKey()

User::getTitleKey ( )

Get the user's name escaped by underscores.

Returns
string Username escaped by underscores.

Definition at line 2567 of file User.php.

References getName().

◆ getToken()

User::getToken (   $forceCreation = true)

Get the user's current token.

Parameters
bool$forceCreationForce the generation of a new token if the user doesn't have one (default=true for backwards compatibility).
Returns
string|null Token

Definition at line 2986 of file User.php.

References $mToken, $ret, $wgAuthenticationTokenVersion, MWCryptRand\generateHex(), MWCryptHash\hmac(), load(), and setToken().

Referenced by getTokenFromOption(), and loadFromSession().

◆ getTokenFromOption()

User::getTokenFromOption (   $oname)

Get a token stored in the preferences (like the watchlist one), resetting it if it's empty (and saving changes).

Parameters
string$onameThe option name to retrieve the token from
Returns
string|bool User's current value for the option, or false if this option is disabled.
See also
resetTokenFromOption()
getOption()
Deprecated:
since 1.26 Applications should use the OAuth extension

Definition at line 3279 of file User.php.

References $wgHiddenPrefs, getId(), getOption(), and getToken().

◆ getTokenUrl()

User::getTokenUrl (   $page,
  $token 
)
protected

Internal function to format the e-mail validation/invalidation URLs.

This uses a quickie hack to use the hardcoded English names of the Special: pages, for ASCII safety.

Note
Since these URLs get dropped directly into emails, using the short English names avoids insanely long URL-encoded links, which also sometimes can get corrupted in some browsers/mailers (T8957 with Gmail and Internet Explorer).
Parameters
string$pageSpecial page
string$token
Returns
string Formatted URL

Definition at line 4796 of file User.php.

References $title, Title\makeTitle(), and NS_MAIN.

Referenced by confirmationTokenUrl(), and invalidationTokenUrl().

◆ getTouched()

User::getTouched ( )

Get the user touched timestamp.

Use this value only to validate caches via inequalities such as in the case of HTTP If-Modified-Since response logic

Returns
string TS_MW Timestamp

Definition at line 2851 of file User.php.

References $cache, $mTouched, load(), and wfTimestamp().

Referenced by validateCache().

◆ getUserPage()

User::getUserPage ( )

Get this user's personal page title.

Returns
Title User's personal page title

Definition at line 4539 of file User.php.

References getName(), Title\makeTitle(), and NS_USER.

Referenced by addAutopromoteOnceGroups(), Block\getPermissionsError(), getTalkPage(), and saveSettings().

◆ groupHasPermission()

static User::groupHasPermission (   $group,
  $role 
)
static

Check, if the given group has the given permission.

If you're wanting to check whether all users have a permission, use User::isEveryoneAllowed() instead. That properly checks if it's revoked from anyone.

Since
1.21
Parameters
string$groupGroup to check
string$roleRole to check
Returns
bool

Definition at line 5013 of file User.php.

References $wgGroupPermissions, and $wgRevokePermissions.

Referenced by SkinTemplate\buildPersonalUrls(), Title\checkQuickPermissions(), SpecialNewpages\filterLinks(), MonoBookTemplate\getBox(), NewPagesPager\getQueryInfo(), SpecialCreateAccount\isRestricted(), and SpecialPage\isRestricted().

◆ idForName()

User::idForName (   $flags = 0)

If only this user's username is known, and it exists, return the user ID.

Parameters
int$flagsBitfield of User:READ_* constants; useful for existence checks
Returns
int

Definition at line 4266 of file User.php.

References $options, $s, DB_MASTER, DB_REPLICA, getName(), IDBAccessObject\READ_LOCKING, and wfGetDB().

◆ idFromName()

static User::idFromName (   $name,
  $flags = self::READ_NORMAL 
)
static

◆ incEditCount()

User::incEditCount ( )

Deferred version of incEditCountImmediate()

This function, rather than incEditCountImmediate(), should be used for most cases as it avoids potential deadlocks caused by concurrent editing.

Definition at line 5329 of file User.php.

References DB_MASTER, incEditCountImmediate(), and wfGetDB().

Referenced by MediaWiki\Storage\PageUpdater\doCreate(), MediaWiki\Storage\PageUpdater\doModify(), UserTest\testGetEditCount(), UserTest\testGetEditCountForAnons(), and UserTest\testIncEditCount().

◆ incEditCountImmediate()

User::incEditCountImmediate ( )

Increment the user's edit-count field.

Will have no effect for anonymous users.

Since
1.26

Definition at line 5343 of file User.php.

References $dbr, DB_MASTER, DB_REPLICA, getEditCount(), getId(), initEditCount(), invalidateCache(), isAnon(), and wfGetDB().

Referenced by incEditCount().

◆ inDnsBlacklist()

User::inDnsBlacklist (   $ip,
  $bases 
)

Whether the given IP is in a given DNS blacklist.

Parameters
string$ipIP to check
string | array$basesArray of Strings: URL of the DNS blacklist
Returns
bool True if blacklisted.

Definition at line 2021 of file User.php.

References $base, array(), as, captcha-old\count, IP\isIPv4(), and wfDebugLog().

Referenced by isDnsBlacklisted().

◆ initEditCount()

User::initEditCount (   $add = 0)
protected

Initialize user_editcount from data out of the revision table.

Parameters
int$addEdits to add to the count from the revision table
Returns
int Number of edits

Definition at line 5390 of file User.php.

References $dbr, DB_MASTER, DB_REPLICA, getId(), ActorMigration\newMigration(), and wfGetDB().

Referenced by getEditCount(), and incEditCountImmediate().

◆ invalidateCache()

User::invalidateCache ( )

Immediately touch the user data cache for this account.

Calls touch() and removes account data from memcached

Definition at line 2807 of file User.php.

References clearSharedCache(), and touch().

Referenced by addGroup(), addWatch(), getActorId(), incEditCountImmediate(), removeGroup(), removeWatch(), and setNewtalk().

◆ invalidateEmail()

User::invalidateEmail ( )

Invalidate the user's e-mail confirmation, and unauthenticate the e-mail address if it was already confirmed.

Note
Call saveSettings() after calling this function to commit the change.
Returns
bool Returns true

Definition at line 4826 of file User.php.

References load(), Hooks\run(), and setEmailAuthenticationTimestamp().

Referenced by setEmail().

◆ invalidationTokenUrl()

User::invalidationTokenUrl (   $token)
protected

Return a URL the user can use to invalidate their email address.

Parameters
string$tokenAccepts the email confirmation token
Returns
string New token URL

Definition at line 4778 of file User.php.

References getTokenUrl().

Referenced by sendConfirmationMail().

◆ isAllowed()

◆ isAllowedAll()

User::isAllowedAll ( )
Parameters
string$permissions,...Permissions to test
Returns
bool True if the user is allowed to perform all of the given actions

Definition at line 3841 of file User.php.

References as, and isAllowed().

◆ isAllowedAny()

User::isAllowedAny ( )

Check if user is allowed to access a feature / make an action.

Parameters
string$permissions,...Permissions to test
Returns
bool True if user is allowed to perform any of the given actions

Definition at line 3826 of file User.php.

References as, and isAllowed().

Referenced by WikiPage\commitRollback(), useFilePatrol(), useNPPatrol(), and useRCPatrol().

◆ isAllowedToCreateAccount()

User::isAllowedToCreateAccount ( )

Get whether the user is allowed to create an account.

Returns
bool

Definition at line 4530 of file User.php.

References isAllowed(), and isBlockedFromCreateAccount().

◆ isAnon()

◆ isBlocked()

User::isBlocked (   $bFromSlave = true)

Check if user is blocked.

Parameters
bool$bFromSlaveWhether to check the replica DB instead of the master. Hacked from false due to horrible probs on site.
Returns
bool True if blocked, false otherwise

Definition at line 2280 of file User.php.

References getBlock().

Referenced by Action\checkCanExecute(), FormSpecialPage\checkExecutePermissions(), SpecialBlock\checkUnblockSelf(), getRights(), isBlockedFrom(), spreadAnyEditBlock(), UserTest\testAutoblockCookiesDisabled(), and UserTest\testIpBlockCookieIgnoredWhenUserLoggedIn().

◆ isBlockedFrom()

User::isBlockedFrom (   $title,
  $bFromSlave = false 
)

Check if user is blocked from editing a particular article.

Parameters
Title$titleTitle to check
bool$bFromSlaveWhether to check the replica DB instead of the master
Returns
bool

Definition at line 2302 of file User.php.

References $title, $wgBlockAllowsUTEdit, false, getName(), isBlocked(), NS_USER_TALK, Hooks\run(), and wfDebug().

Referenced by UserTest\testBlockInstanceCache().

◆ isBlockedFromCreateAccount()

User::isBlockedFromCreateAccount ( )

Get whether the user is explicitly blocked from account creation.

Returns
bool|Block

Definition at line 4499 of file User.php.

References $mBlock, getBlockedStatus(), getRequest(), isAllowed(), Block\newFromTarget(), and Block\prevents().

Referenced by MediaWiki\Auth\AuthManager\checkAccountCreatePermissions(), and isAllowedToCreateAccount().

◆ isBlockedFromEmailuser()

User::isBlockedFromEmailuser ( )

Get whether the user is blocked from using Special:Emailuser.

Returns
bool

Definition at line 4521 of file User.php.

References getBlockedStatus().

◆ isBlockedGlobally()

User::isBlockedGlobally (   $ip = '')

Check if user is blocked on all wikis.

Do not use for actual edit permission checks! This is intended for quick UI checks.

Parameters
string$ipIP address, uses current client if none given
Returns
bool True if blocked, false otherwise

Definition at line 2354 of file User.php.

References getGlobalBlock().

◆ isBot()

User::isBot ( )
Returns
bool Whether this user is flagged as being a bot role account
Since
1.28

Definition at line 3809 of file User.php.

References getGroups(), isAllowed(), and Hooks\run().

◆ isCreatableName()

static User::isCreatableName (   $name)
static

Usernames which fail to pass this function will be blocked from new account registrations, but may be used internally either by batch processes or by user accounts which have already been created.

Additional blacklisting may be added here rather than in isValidUserName() to avoid disrupting existing accounts.

Parameters
string$nameString to match
Returns
bool

Definition at line 1121 of file User.php.

References $name, $wgInvalidUsernameCharacters, isUsableName(), and wfDebugLog().

Referenced by MediaWiki\Auth\AuthManager\autoCreateUser(), and SpecialRenameuser\execute().

◆ isDnsBlacklisted()

User::isDnsBlacklisted (   $ip,
  $checkWhitelist = false 
)

Whether the given IP is in a DNS blacklist.

Parameters
string$ipIP to check
bool$checkWhitelistWhether to check the whitelist first
Returns
bool True if blacklisted.

Definition at line 2000 of file User.php.

References $wgDnsBlacklistUrls, $wgEnableDnsBlacklist, $wgProxyWhitelist, and inDnsBlacklist().

Referenced by MediaWiki\Auth\AuthManager\checkAccountCreatePermissions(), and getBlockedStatus().

◆ isEmailConfirmationPending()

User::isEmailConfirmationPending ( )

Check whether there is an outstanding request for e-mail confirmation.

Returns
bool

Definition at line 4908 of file User.php.

References $wgEmailAuthentication, isEmailConfirmed(), and wfTimestamp().

◆ isEmailConfirmed()

User::isEmailConfirmed ( )

Is this user's e-mail address valid-looking and confirmed within limits of the current site configuration?

Note
If $wgEmailAuthentication is on, this may require the user to have confirmed their address by returning a code or using a password sent to the address from the wiki.
Returns
bool

Definition at line 4882 of file User.php.

References $user, $wgEmailAuthentication, getEmailAuthenticationTimestamp(), isAnon(), load(), and Hooks\run().

Referenced by canReceiveEmail(), canSendEmail(), confirmEmail(), and isEmailConfirmationPending().

◆ isEveryoneAllowed()

static User::isEveryoneAllowed (   $right)
static

Check if all users may be assumed to have the given permission.

We generally assume so if the right is granted to '*' and isn't revoked on any group. It doesn't attempt to take grants or other extension limitations on rights into account in the general case, though, as that would require it to always return false and defeat the purpose. Specifically, session-based rights restrictions (such as OAuth or bot passwords) are applied based on the current session.

Since
1.22
Parameters
string$rightRight to check
Returns
bool

Definition at line 5033 of file User.php.

References $cache, $wgGroupPermissions, $wgRevokePermissions, as, and Hooks\run().

Referenced by ApiMain\checkExecutePermissions(), Title\checkReadPermissions(), RawAction\onView(), AjaxDispatcher\performAction(), and ApiMain\setCacheMode().

◆ isHidden()

User::isHidden ( )

Check if user account is hidden.

Returns
bool True if hidden, false otherwise

Definition at line 2418 of file User.php.

References $mHideName, $user, getBlockedStatus(), and Hooks\run().

Referenced by UserTest\testBlockInstanceCache().

◆ isIP()

static User::isIP (   $name)
static

Does the string match an anonymous IP address?

This function exists for username validation, in order to reject usernames which are similar in form to IP addresses. Strings such as 300.300.300.300 will return true because it looks like an IP address, despite not being strictly valid.

We match "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.xxx" as an anonymous IP address because the usemod software would "cloak" anonymous IP addresses like this, if we allowed accounts like this to be created new users could get the old edits of these anonymous users.

Parameters
string$nameName to match
Returns
bool

Definition at line 971 of file User.php.

References $name, and IP\isIPv6().

Referenced by ImageListPager\__construct(), SpecialContributions\contributionsSub(), MediaWiki\Storage\DerivedPageDataUpdater\doUpdates(), ApiQueryUserContribs\execute(), RollbackEdits\execute(), SearchNearMatcher\getNearMatchInternal(), ApiRollback\getRbUser(), Skin\getRelevantUser(), ReassignEdits\initialiseUser(), ApiQueryBlocks\prepareUsername(), EditPage\showIntro(), and Article\showMissingArticle().

◆ isIPRange()

User::isIPRange ( )

Is the user an IP range?

Since
1.30
Returns
bool

Definition at line 982 of file User.php.

References IP\isValidRange().

◆ isItemLoaded()

User::isItemLoaded (   $item,
  $all = 'all' 
)

Return whether an item has been loaded.

Parameters
string$itemItem to check. Current possibilities:
  • id
  • name
  • realname
string$all'all' to check if the whole object has been loaded or any other string to check if only the item is available (e.g. for optimisation)
Returns
bool

Definition at line 1346 of file User.php.

References true.

Referenced by getActorId(), getId(), getName(), and getRealName().

◆ isLocallyBlockedProxy()

static User::isLocallyBlockedProxy (   $ip)
static

Check if an IP address is in the local proxy list.

Parameters
string$ip
Returns
bool

Definition at line 2067 of file User.php.

References $value, $wgProxyList, as, file, IP\isIPAddress(), and wfDeprecated().

Referenced by UserTest\testIsLocallyBlockedProxy().

◆ isLocked()

User::isLocked ( )

Check if user account is locked.

Returns
bool True if locked, false otherwise

Definition at line 2401 of file User.php.

References $mLocked, $user, and Hooks\run().

◆ isLoggedIn()

User::isLoggedIn ( )

◆ isNewbie()

User::isNewbie ( )

Determine whether the user is a newbie.

Newbies are either anonymous IPs, or the most recently created accounts.

Returns
bool

Definition at line 4558 of file User.php.

References isAllowed().

Referenced by pingLimiter().

◆ isPingLimitable()

User::isPingLimitable ( )

Is this user subject to rate limiting?

Returns
bool True if rate limited

Definition at line 2113 of file User.php.

References $wgRateLimitsExcludedIPs, getRequest(), isAllowed(), and IP\isInRanges().

Referenced by pingLimiter(), and UserTest\testIsPingLimitable().

◆ isSafeToLoad()

User::isSafeToLoad ( )

Test if it's safe to load this User object.

You should typically check this before using $wgUser or RequestContext::getUser in a method that might be called before the system has been fully initialized. If the object is unsafe, you should use an anonymous user: \code $user = $wgUser->isSafeToLoad() ? $wgUser : new User; \endcode

Since
1.27
Returns
bool

Definition at line 347 of file User.php.

References $wgFullyInitialised.

◆ isUsableName()

static User::isUsableName (   $name)
static

Usernames which fail to pass this function will be blocked from user login and new account registrations, but may be used internally by batch processes.

If an account already exists in this form, login will be blocked by a failure to pass this function.

Parameters
string$nameName to match
Returns
bool

Definition at line 1046 of file User.php.

References $name, $wgReservedUsernames, as, Hooks\run(), and wfMessage().

Referenced by MediaWiki\Session\UserInfo\__construct(), MigrateActors\addActorsForRows(), ExternalUserNames\applyPrefix(), MediaWiki\Auth\AuthManager\beginAccountLink(), CleanupUsersWithNoId\cleanup(), ApiBlock\execute(), isCreatableName(), and Block\setBlocker().

◆ isValidPassword()

User::isValidPassword (   $password)

Is the input a valid password for this user?

Parameters
string$passwordDesired password
Returns
bool

Definition at line 1151 of file User.php.

References getPasswordValidity().

Referenced by UserTest\testCheckPasswordValidity().

◆ isValidUserName()

static User::isValidUserName (   $name)
static

Is the input a valid username?

Checks if the input is a valid username, we don't want an empty string, an IP address, anything that contains slashes (would mess up subpages), is longer than the maximum allowed username size or doesn't begin with a capital letter.

Parameters
string$nameName to match
Returns
bool

Definition at line 997 of file User.php.

References $name, $wgMaxNameChars, and(), Title\newFromText(), and use.

Referenced by GenderCache\doQuery(), CheckUsernames\execute(), and MediaWiki\Session\SessionBackend\save().

◆ isWatched()

User::isWatched (   $title,
  $checkRights = self::CHECK_USER_RIGHTS 
)

Check the watched status of an article.

Since
1.22 $checkRights parameter added
Parameters
Title$titleTitle of the article to look at
bool$checkRightsWhether to check 'viewmywatchlist'/'editmywatchlist' rights. Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
Returns
bool

Definition at line 3920 of file User.php.

References $title, and isAllowed().

◆ listOptionKinds()

static User::listOptionKinds ( )
static

Return a list of the types of user options currently returned by User::getOptionKinds().

Currently, the option kinds are:

  • 'registered' - preferences which are registered in core MediaWiki or by extensions using the UserGetDefaultOptions hook.
  • 'registered-multiselect' - as above, using the 'multiselect' type.
  • 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
  • 'userjs' - preferences with names starting with 'userjs-', intended to be used by user scripts.
  • 'special' - "preferences" that are not accessible via User::getOptions or User::setOptions.
  • 'unused' - preferences about which MediaWiki doesn't know anything. These are usually legacy options, removed in newer versions.

The API (and possibly others) use this function to determine the possible option types for validation purposes, so make sure to update this when a new option kind is added.

See also
User::getOptionKinds
Returns
array Option kinds

Definition at line 3341 of file User.php.

Referenced by ApiOptions\getAllowedParams().

◆ load()

◆ loadDefaults()

User::loadDefaults (   $name = false)

Set cached properties to default.

Note
This no longer clears uncached lazy-initialised properties; the constructor does that instead.
Parameters
string | bool$name

Definition at line 1307 of file User.php.

References $name, any, pages, Hooks\run(), and wfTimestamp().

Referenced by PPFuzzUser\load(), load(), loadFromDatabase(), and loadFromId().

◆ loadFromCache()

User::loadFromCache ( )
protected

Load user data from shared cache, given mId has already been set.

Returns
bool True
Since
1.25

Definition at line 529 of file User.php.

References $cache, $name, array(), as, DB_REPLICA, getCacheKey(), ObjectCache\getMainWANInstance(), loadFromDatabase(), loadGroups(), loadOptions(), use, VERSION, wfDebug(), wfGetDB(), and wfTimestamp().

Referenced by loadFromId().

◆ loadFromDatabase()

User::loadFromDatabase (   $flags = self::READ_LATEST)

Load user and user_group data from the database.

$this->mId must be set, this is how the user is identified.

Parameters
int$flagsUser::READ_* constant bitfield
Returns
bool True if the user exists, false if the user is anonymous

Definition at line 1436 of file User.php.

References $options, $s, DBAccessObjectUtils\getDBOptions(), getEditCount(), getQueryInfo(), list, loadDefaults(), loadFromRow(), Hooks\run(), and wfGetDB().

Referenced by addToDatabase(), loadFromCache(), and loadFromId().

◆ loadFromId()

User::loadFromId (   $flags = self::READ_NORMAL)

Load user table data, given mId has already been set.

Parameters
int$flagsUser::READ_* constant bitfield
Returns
bool False if the ID does not exist, true otherwise

Definition at line 464 of file User.php.

References DBAccessObjectUtils\hasFlags(), loadDefaults(), loadFromCache(), and loadFromDatabase().

Referenced by load().

◆ loadFromRow()

User::loadFromRow (   $row,
  $data = null 
)
protected

Initialize this object from a row from the user table.

Parameters
stdClass$rowRow from the user table to load.
array | null$dataFurther user data to load into the object

user_groups Array of arrays or stdClass result rows out of the user_groups table. Previously you were supposed to pass an array of strings here, but we also need expiry info nowadays, so an array of strings is ignored. user_properties Array with properties out of the user_properties table

Definition at line 1488 of file User.php.

References $wgActorTableSchemaMigrationStage, as, captcha-old\count, if, loadOptions(), UserGroupMembership\newFromRow(), SCHEMA_COMPAT_NEW, setItemLoaded(), wfTimestamp(), and wfTimestampOrNull().

Referenced by loadFromDatabase().

◆ loadFromSession()

User::loadFromSession ( )
private

Load user data from the session.

Returns
bool True if the user is logged in, false otherwise.

Definition at line 1367 of file User.php.

References $user, getId(), getName(), getRequest(), getToken(), loadFromUserObject(), Hooks\run(), and trackBlockWithCookie().

Referenced by load().

◆ loadFromUserObject()

User::loadFromUserObject (   $user)
protected

Load the data for this user object from another user object.

Parameters
User$user

Definition at line 1606 of file User.php.

References $user, and as.

Referenced by loadFromSession().

◆ loadGroups()

User::loadGroups ( )
private

Load the groups from the database if they aren't already loaded.

Definition at line 1616 of file User.php.

References DB_MASTER, DB_REPLICA, UserGroupMembership\getMembershipsForUser(), and wfGetDB().

Referenced by addGroup(), getGroupMemberships(), getGroups(), loadFromCache(), and removeGroup().

◆ loadOptions()

User::loadOptions (   $data = null)
protected

Load the user options either from cache, the database or an array.

Parameters
array | null$dataRows for the current user out of the user_properties table

Definition at line 5485 of file User.php.

References $dbr, $property, $res, $value, as, DB_MASTER, DB_REPLICA, getDefaultOptions(), getId(), load(), LanguageCode\replaceDeprecatedCodes(), Hooks\run(), wfDebug(), and wfGetDB().

Referenced by getOption(), getOptionKinds(), getOptions(), loadFromCache(), loadFromRow(), saveOptions(), and setOption().

◆ logout()

User::logout ( )

Log this user out.

Definition at line 4140 of file User.php.

References $user, doLogout(), and Hooks\run().

◆ makeGroupLinkHTML()

static User::makeGroupLinkHTML (   $group,
  $text = '' 
)
static

Create a link to the group in HTML, if available; else return the group name.

Deprecated:
since 1.29 Use UserGroupMembership::getLink instead, or make the link yourself if you need custom text
Parameters
string$groupInternal name of the group
string$textThe text of the link
Returns
string HTML link to the group

Definition at line 5165 of file User.php.

References $title, UserGroupMembership\getGroupName(), UserGroupMembership\getGroupPage(), and wfDeprecated().

◆ makeGroupLinkWiki()

static User::makeGroupLinkWiki (   $group,
  $text = '' 
)
static

Create a link to the group in Wikitext, if available; else return the group name.

Deprecated:
since 1.29 Use UserGroupMembership::getLink instead, or make the link yourself if you need custom text
Parameters
string$groupInternal name of the group
string$textThe text of the link
Returns
string Wikilink to the group

Definition at line 5190 of file User.php.

References $title, UserGroupMembership\getGroupName(), UserGroupMembership\getGroupPage(), and wfDeprecated().

◆ makeUpdateConditions()

User::makeUpdateConditions ( Database  $db,
array  $conditions 
)
protected

Builds update conditions.

Additional conditions may be added to $conditions to protected against race conditions using a compare-and-set (CAS) mechanism based on comparing $this->mTouched with the user_touched field.

Parameters
Database$db
array$conditionsWHERE conditions for use with Database::update
Returns
array WHERE conditions for use with Database::update

Definition at line 1692 of file User.php.

References Wikimedia\Rdbms\Database\timestamp().

Referenced by checkAndSetTouched(), and saveSettings().

◆ matchEditToken()

User::matchEditToken (   $val,
  $salt = '',
  $request = null,
  $maxage = null 
)

Check given value against the token value stored in the session.

A match should confirm that the form was submitted from the user's own login session, not a form submission from a third-party site.

Parameters
string$valInput value to compare
string | array$saltOptional function-specific data for hashing
WebRequest | null$requestObject to use or null to use $wgRequest
int | null$maxageFail tokens older than this, in seconds
Returns
bool Whether the token matches

Definition at line 4660 of file User.php.

References $request, and getEditTokenObject().

Referenced by matchEditTokenNoSuffix().

◆ matchEditTokenNoSuffix()

User::matchEditTokenNoSuffix (   $val,
  $salt = '',
  $request = null,
  $maxage = null 
)

Check given value against the token value stored in the session, ignoring the suffix.

Parameters
string$valInput value to compare
string | array$saltOptional function-specific data for hashing
WebRequest | null$requestObject to use or null to use $wgRequest
int | null$maxageFail tokens older than this, in seconds
Returns
bool Whether the token matches

Definition at line 4674 of file User.php.

References $request, and matchEditToken().

◆ newFatalPermissionDeniedStatus()

static User::newFatalPermissionDeniedStatus (   $permission)
static

Factory function for fatal permission-denied errors.

Since
1.22
Parameters
string$permissionUser right required
Returns
Status

Definition at line 5696 of file User.php.

References $wgLang, as, captcha-old\count, UserGroupMembership\getLink(), RequestContext\getMain(), and StatusValue\newFatal().

Referenced by ApiUpload\checkPermissions(), WatchAction\doUnwatch(), WatchAction\doWatch(), and Title\missingPermissionError().

◆ newFromActorId()

static User::newFromActorId (   $id)
static

Static factory method for creation from a given actor ID.

Since
1.31
Parameters
int$idValid actor ID
Returns
User The corresponding User object

Definition at line 630 of file User.php.

References $wgActorTableSchemaMigrationStage, SCHEMA_COMPAT_NEW, and User.

Referenced by DatabaseLogEntry\getPerformer(), RecentChange\getPerformer(), RCDatabaseLogEntry\getPerformer(), and UserTest\testActorId().

◆ newFromAnyId()

◆ newFromConfirmationCode()

static User::newFromConfirmationCode (   $code,
  $flags = 0 
)
static

Factory method to fetch whichever user has a given email confirmation code.

This code is generated when an account is created or its e-mail address has changed.

If the code is invalid or has expired, returns NULL.

Parameters
string$codeConfirmation code
int$flagsUser::READ_* bitfield
Returns
User|null

Definition at line 732 of file User.php.

References $code, DB_MASTER, DB_REPLICA, newFromId(), and wfGetDB().

Referenced by EmailConfirmation\attemptConfirm(), and EmailInvalidation\attemptInvalidate().

◆ newFromId()

static User::newFromId (   $id)
static

Static factory method for creation from a given user ID.

Parameters
int$idValid user ID
Returns
User The corresponding User object

Definition at line 615 of file User.php.

References User.

Referenced by RenameuserSQL\__construct(), Block\__construct(), Installer\__construct(), CategoryMembershipChangeTest\addDBDataOnce(), LogPage\addEntry(), SpecialBlock\checkUnblockSelf(), MediaWiki\Auth\AuthManager\continueAccountCreation(), createNew(), SpecialRedirect\dispatchUser(), ApiQueryRecentChangesIntegrationTest\doAnonPageEdit(), ApiQueryWatchlistIntegrationTest\doAnonPageEdit(), PopulateLogSearch\doDBUpdates(), RemoveInvalidEmails\execute(), FixUserRegistration\execute(), MigrateUserGroup\execute(), RemoveUnusedAccounts\execute(), ChangePassword\execute(), ResetUserEmail\execute(), ApiQueryAllUsers\execute(), WrapOldPasswords\execute(), ActiveUsersPager\formatRow(), NewFilesPager\formatRow(), ApiUnblockTest\getBlockFromParams(), WikiPage\getContributors(), UsersPager\getGroupMemberships(), getInstanceForUpdate(), NewUsersLogFormatter\getMessageParameters(), DatabaseLogEntry\getPerformer(), RecentChange\getPerformer(), RCDatabaseLogEntry\getPerformer(), ReplaceAll\getUser(), CategoryMembershipChange\getUser(), RequestContext\importScopedSession(), ManualLogEntry\insert(), EnhancedChangesListTest\newEnhancedChangesList(), newFromConfirmationCode(), MediaWiki\Session\UserInfo\newFromId(), SpecialSearchTest\newUserWithSearchNS(), RenameuserSQL\rename(), DeletePageJob\run(), EnotifNotifyJob\run(), ReplaceTextJob\run(), RefreshLinksJob\runForTitle(), TitlePermissionTest\setUp(), Skin\showEmailUser(), UserOptionsMaintenance\showUsageStats(), UserTest\testActorId(), UserTest\testEquals(), LanguageConverterTest\testGetPreferredVariantHeaderUserVsUrl(), UserTest\testIncEditCount(), SpecialPageTest\testRequireLoginAnon(), ApiQueryRecentChangesIntegrationTest\testUserPropParameter(), ApiQueryWatchlistIntegrationTest\testUserPropParameter(), UserOptionsMaintenance\updateOptions(), ResetUserTokens\updateUser(), and Linker\userToolLinks().

◆ newFromIdentity()

◆ newFromName()

static User::newFromName (   $name,
  $validate = 'valid' 
)
static

Static factory method for creation from username.

This is slightly less efficient than newFromId(), so use newFromId() if you have both an ID and a name handy.

Parameters
string$nameUsername, validated by Title::newFromText()
string | bool$validateValidate username. Takes the same parameters as User::getCanonicalName(), except that true is accepted as an alias for 'valid', for BC.
Returns
User|bool User object, or false if the username is invalid (e.g. if it contains illegal characters or is an IP address). If the username is not present in the database, the result will be a user object with a name, zero user ID and default settings.

Definition at line 592 of file User.php.

References $name, getCanonicalName(), and User.

Referenced by UserWrapper\__construct(), TestUser\__construct(), ImageListPager\__construct(), EmailNotification\actuallyNotifyOnPageChange(), MediaWiki\Tests\Maintenance\BackupDumperLoggerTest\addDBData(), SpecialMyLanguageTest\addDBDataOnce(), ApiQueryUserContribsTest\addDBDataOnce(), BlockTest\addXffBlocks(), EditPageTest\assertEdit(), MediaWiki\Auth\AuthManager\beginAccountCreation(), MediaWiki\Auth\AuthManager\beginAuthentication(), MediaWiki\Auth\AuthPluginPrimaryAuthenticationProvider\beginPrimaryAuthentication(), ImageListPager\buildQueryConds(), MediaWiki\Auth\AuthManager\canCreateAccount(), EmailNotification\canSendUserTalkEmail(), ApiMain\checkAsserts(), SpecialBlock\checkUnblockSelf(), MediaWiki\Auth\AuthManager\continueAccountCreation(), MediaWiki\Auth\AuthManager\continueAccountLink(), MediaWiki\Auth\AuthManager\continueAuthentication(), SpecialReplaceText\createJobsForTextReplacements(), Installer\createMainpage(), Installer\createSysop(), Block\defaultRetroactiveAutoblock(), PopulateLogSearch\doDBUpdates(), MediaWiki\Storage\DerivedPageDataUpdater\doUpdates(), ApiValidatePassword\execute(), SpecialNuke\execute(), DisableOATHAuthForUser\execute(), SpecialRenameuser\execute(), ApiOATHValidate\execute(), ApiQueryOATH\execute(), Undelete\execute(), SpecialLog\execute(), ApiQueryDeletedrevs\execute(), SpecialContributions\execute(), MakeTestEdits\execute(), DeleteDefaultMessages\execute(), ImportSiteScripts\execute(), ResetUserEmail\execute(), ChangePassword\execute(), Protect\execute(), ApiQueryUserContribs\execute(), DeletedContributionsPage\execute(), ApiQueryLogEvents\execute(), RenameUserCleanup\execute(), InvalidateUserSesssions\execute(), TableCleanup\execute(), DeleteBatch\execute(), EditCLI\execute(), ImportTextFiles\execute(), MoveBatch\execute(), CreateAndPromote\execute(), ImportImages\execute(), PasswordReset\execute(), LoginSignupSpecialPage\execute(), UserrightsPage\fetchUser(), LogFormatter\formatParameterValue(), LogFormatter\formatParameterValueForApi(), CoreParserFunctions\gender(), WatchedItemStoreUnitTest\getAnonUser(), CaptchaPreAuthenticationProvider\getAuthenticationRequests(), TitleBlacklistPreAuthenticationProvider\getAuthenticationRequests(), CreditsAction\getAuthor(), MediaWiki\Auth\CheckBlocksSecondaryAuthenticationProviderTest\getBlockedUser(), WikiPage\getContributors(), WikiPage\getCreator(), WANCacheReapUpdate\getEventAffectedKeys(), BlockLogFormatter\getMessageParameters(), NewUsersLogFormatter\getMessageParameters(), SpecialNuke\getNewPages(), MediaWiki\Auth\AbstractPasswordPrimaryAuthenticationProvider\getNewPasswordExpiry(), DatabaseLogEntry\getPerformer(), RecentChange\getPerformer(), RCDatabaseLogEntry\getPerformer(), NewPagesPager\getQueryInfo(), NewFilesPager\getQueryInfo(), DeletedContribsPager\getQueryInfo(), ContribsPager\getQueryInfo(), Skin\getRelevantUser(), RollbackEdits\getRollbackTitles(), SpecialEmailUser\getTarget(), ReplaceAll\getUser(), CategoryMembershipChange\getUser(), DoubleRedirectJob\getUser(), ResourceLoaderContext\getUserObj(), WatchedItemQueryService\getUserRelatedConds(), ApiBase\getWatchlistUser(), ImportableOldRevisionImporter\import(), ImportableUploadRevisionImporter\import(), WikiRevision\importLogItem(), RequestContext\importScopedSession(), ReassignEdits\initialiseUser(), ManualLogEntry\insert(), LogPager\limitPerformer(), CentralIdLookup\localUserFromCentralId(), BotPassword\login(), RequestContext\newExtraneousContext(), MediaWiki\Session\UserInfo\newFromName(), WikiPage\onArticleDelete(), RenameuserHooks\onShowMissingArticle(), RawAction\onView(), InfoAction\pageInfo(), Block\parseTarget(), SpecialListFiles\prefixSearchSubpages(), SpecialUnblock\prefixSearchSubpages(), SpecialNuke\prefixSearchSubpages(), SpecialRenameuser\prefixSearchSubpages(), SpecialEmailUser\prefixSearchSubpages(), SpecialContributions\prefixSearchSubpages(), UserrightsPage\prefixSearchSubpages(), SpecialBlock\prefixSearchSubpages(), RevisionDbTestBase\provideInsertOn_exceptionOnIncomplete(), MediaWiki\Tests\Storage\DerivedPageDataUpdaterTest\provideIsReusableFor(), CaptchaPreAuthenticationProviderTest\providePingLimiter(), MediaWiki\Auth\TemporaryPasswordPrimaryAuthenticationProvider\providerAllowsAuthenticationDataChange(), MediaWiki\Auth\AuthPluginPrimaryAuthenticationProvider\providerChangeAuthenticationData(), MediaWiki\Auth\AuthPluginPrimaryAuthenticationProvider\providerRevokeAccessForUser(), CaptchaPreAuthenticationProviderTest\provideTestForAccountCreation(), EnotifNotifyJob\run(), ApiQueryDeletedRevisions\run(), ApiQueryAllRevisions\run(), ApiQueryAllDeletedRevisions\run(), ApiQueryAllImages\run(), ApiQueryRevisions\run(), ApiQueryRecentChanges\run(), RefreshLinksJob\runForTitle(), UserNamePrefixSearch\search(), MediaWiki\Auth\TemporaryPasswordPrimaryAuthenticationProvider\sendPasswordResetEmail(), Block\setBlocker(), RecentChangeTest\setUp(), TitlePermissionTest\setUp(), LogFormatterTest\setUp(), SpecialLog\show(), EditPage\showIntro(), Article\showMissingArticle(), WebInstallerName\submit(), MediaWiki\Auth\AbstractPreAuthenticationProviderTest\testAbstractPreAuthenticationProvider(), MediaWiki\Auth\AbstractPrimaryAuthenticationProviderTest\testAbstractPrimaryAuthenticationProvider(), MediaWiki\Auth\AbstractSecondaryAuthenticationProviderTest\testAbstractSecondaryAuthenticationProvider(), MediaWiki\Auth\LocalPasswordPrimaryAuthenticationProviderTest\testAccountCreation(), MediaWiki\Auth\AuthPluginPrimaryAuthenticationProviderTest\testAccountCreation(), MediaWiki\Auth\TemporaryPasswordPrimaryAuthenticationProviderTest\testAccountCreation(), MediaWiki\Auth\AuthManagerTest\testAccountCreation(), MediaWiki\Auth\TemporaryPasswordPrimaryAuthenticationProviderTest\testAccountCreationEmail(), MediaWiki\Auth\AuthManagerTest\testAccountCreationLogging(), MediaWiki\Auth\AuthManagerTest\testAccountLink(), UserTest\testActorId(), MediaWiki\Auth\AuthManagerTest\testAuthentication(), MediaWiki\Auth\AuthManagerTest\testAutoAccountCreation(), MediaWiki\Auth\AuthManagerTest\testAutoCreateFailOnLogin(), MediaWiki\Auth\AuthManagerTest\testAutoCreateOnLogin(), MediaWiki\Auth\CheckBlocksSecondaryAuthenticationProviderTest\testBasics(), MediaWiki\Auth\ResetPasswordSecondaryAuthenticationProviderTest\testBasics(), MediaWiki\Auth\AuthManagerTest\testBeginAccountCreation(), MediaWiki\Auth\AuthManagerTest\testBeginAccountLink(), MediaWiki\Auth\AuthManagerTest\testBeginAuthentication(), MediaWiki\Auth\ConfirmLinkSecondaryAuthenticationProviderTest\testBeginLinkAttempt(), MediaWiki\Auth\ConfirmLinkSecondaryAuthenticationProviderTest\testBeginSecondaryAccountCreation(), MediaWiki\Auth\ConfirmLinkSecondaryAuthenticationProviderTest\testBeginSecondaryAuthentication(), MediaWiki\Auth\EmailNotificationSecondaryAuthenticationProviderTest\testBeginSecondaryAuthentication(), MediaWiki\Auth\CheckBlocksSecondaryAuthenticationProviderTest\testBeginSecondaryAuthentication(), BlockTest\testBlockedUserCanNotCreateAccount(), CentralIdLookupTest\testCentralIdFromLocalUser(), MediaWiki\Auth\AuthManagerTest\testCheckAccountCreatePermissions(), ApiStashEditTest\testCheckCacheOldNoEditsAnon(), PasswordPolicyChecksTest\testCheckMaximalPasswordLength(), PasswordPolicyChecksTest\testCheckMinimalPasswordLength(), PasswordPolicyChecksTest\testCheckMinimumPasswordLengthToLogin(), PasswordPolicyChecksTest\testCheckPasswordCannotMatchBlacklist(), PasswordPolicyChecksTest\testCheckPasswordCannotMatchUsername(), UserTest\testCheckPasswordValidity(), PasswordPolicyChecksTest\testCheckPopularPasswordBlacklist(), UserPasswordPolicyTest\testCheckUserPassword(), MediaWiki\Auth\AuthManagerTest\testContinueAccountCreation(), MediaWiki\Auth\AuthManagerTest\testContinueAccountLink(), MediaWiki\Auth\ConfirmLinkSecondaryAuthenticationProviderTest\testContinueLinkAttempt(), MediaWiki\Auth\ConfirmLinkSecondaryAuthenticationProviderTest\testContinueSecondaryAccountCreation(), MediaWiki\Auth\ConfirmLinkSecondaryAuthenticationProviderTest\testContinueSecondaryAuthentication(), BlockTest\testCrappyCrossWikiBlocks(), MediaWiki\Auth\AuthManagerTest\testCreateFromLogin(), BlockTest\testDeprecatedConstructor(), MediaWiki\Auth\ThrottlePreAuthenticationProviderTest\testDisabled(), SpecialRedirectTest\testDispatch(), UserTest\testEquals(), UserTest\testExperienceLevelAnon(), MediaWiki\Auth\LegacyHookPreAuthenticationProvider\testForAuthentication(), MediaWiki\Auth\AuthManagerTest\testGetAuthenticationRequests(), UserTest\testGetEditCountForAnons(), UserPasswordPolicyTest\testGetPoliciesForUser(), RequestContextTest\testImportScopedSession(), MediaWiki\Session\SessionManagerTest\testInvalidateSessionsForUser(), LocalIdLookupTest\testIsAttached(), UserTest\testLoggedIn(), LocalIdLookupTest\testLookupCentralIds(), LocalIdLookupTest\testLookupUserNames(), MediaWiki\Tests\Storage\PageUpdaterTest\testMagicWords(), UserTest\testNewFromAnyId(), MediaWiki\Session\UserInfoTest\testNewFromId(), MediaWiki\Session\UserInfoTest\testNewFromName(), MediaWiki\Session\UserInfoTest\testNewFromUser(), MediaWiki\Auth\AuthPluginPrimaryAuthenticationProviderTest\testOnLocalUserCreated(), MediaWiki\Auth\AuthPluginPrimaryAuthenticationProviderTest\testOnUserGroupsChanged(), MediaWiki\Auth\AuthPluginPrimaryAuthenticationProviderTest\testOnUserLoggedIn(), MediaWiki\Auth\AuthPluginPrimaryAuthenticationProviderTest\testOnUserSaveSettings(), UserTest\testOptions(), ApiQueryWatchlistIntegrationTest\testOwnerAndTokenParams(), MediaWiki\Session\ImmutableSessionProviderWithCookieTest\testPersistSession(), CaptchaPreAuthenticationProviderTest\testPostAuthentication(), MediaWiki\Auth\ThrottlePreAuthenticationProviderTest\testPostAuthentication(), CaptchaPreAuthenticationProviderTest\testPostAuthentication_disabled(), MediaWiki\Auth\AbstractPrimaryAuthenticationProviderTest\testPrimaryAccountLink(), MediaWiki\Auth\CheckBlocksSecondaryAuthenticationProviderTest\testRangeBlock(), ApiBlockTest\testRangeBlock(), ChangesListSpecialPageTest\testRcHidebyothersFilter(), ChangesListSpecialPageTest\testRcHidemyselfFilter(), SpecialPageTest\testRequireLoginNotAnon(), MediaWiki\Session\SessionBackendTest\testResetId(), MediaWiki\Session\SessionBackendTest\testResetIdOfGlobalSession(), MediaWiki\Auth\AuthManagerTest\testSecuritySensitiveOperationStatus(), MediaWiki\Auth\AuthManagerTest\testSetDefaultUserOptions(), SpecialPageFatalTest\testSpecialPageDoesNotFatal(), MediaWiki\Session\SessionBackendTest\testTakeOverGlobalSession(), MediaWiki\Auth\ThrottlePreAuthenticationProviderTest\testTestForAccountCreation(), CaptchaPreAuthenticationProviderTest\testTestForAccountCreation(), MediaWiki\Auth\LegacyHookPreAuthenticationProviderTest\testTestForAccountCreation(), MediaWiki\Auth\LocalPasswordPrimaryAuthenticationProviderTest\testTestForAccountCreation(), MediaWiki\Auth\TemporaryPasswordPrimaryAuthenticationProviderTest\testTestForAccountCreation(), MediaWiki\Auth\AuthPluginPrimaryAuthenticationProviderTest\testTestForAccountCreation(), MediaWiki\Auth\ThrottlePreAuthenticationProviderTest\testTestForAuthentication(), MediaWiki\Auth\CheckBlocksSecondaryAuthenticationProviderTest\testTestUserForCreation(), MediaWiki\Auth\ResetPasswordSecondaryAuthenticationProviderTest\testTryReset(), MediaWiki\Session\SessionBackendTest\testUnpersistOfGlobalSession(), MediaWiki\Auth\AuthPluginPrimaryAuthenticationProvider\testUserCanAuthenticate(), RevisionDbTestBase\testUserWasLastToEdit(), ApiBlockTest\testVeryLargeRangeBlock(), ArticleViewTest\testViewUserPageOfNonexistingUser(), PageArchive\undeleteRevisions(), MediaWiki\Auth\AuthManagerTest\usernameForCreation(), HTMLUserTextField\validate(), and ApiBase\validateUser().

◆ newFromRow()

static User::newFromRow (   $row,
  $data = null 
)
static

Create a new user object from a user row.

The row should have the following fields from the user table in it:

  • either user_name or user_id to load further data if needed (or both)
  • user_real_name
  • all other fields (email, etc.) It is useless to provide the remaining fields if either user_id, user_name and user_real_name are not provided because the whole row will be loaded once more from the database when accessing them.
Parameters
stdClass$rowA row from the user table
array | null$dataFurther data to load into the object (see User::loadFromRow for valid keys)
Returns
User

Definition at line 778 of file User.php.

References $user, and User.

Referenced by ApiQueryUserContribs\execute(), ApiQueryUsers\execute(), DatabaseLogEntry\getPerformer(), PasswordReset\getUsersByEmail(), newSystemUser(), RebuildRecentchanges\rebuildRecentChangesTablePass4(), UserArrayFromResult\setCurrent(), UserTest\testActorId(), and UserTest\testExperienceLevel().

◆ newFromSession()

static User::newFromSession ( WebRequest  $request = null)
static

Create a new user object using data from session.

If the login credentials are invalid, the result is an anonymous user.

Parameters
WebRequest | null$requestObject to use; $wgRequest will be used if omitted.
Returns
User

Definition at line 756 of file User.php.

References $request, $user, and User.

Referenced by RequestContext\getUser(), ApiLogoutTest\setUp(), UserTest\testAutoblockCookieInauthentic(), UserTest\testAutoblockCookieInfiniteExpiry(), UserTest\testAutoblockCookieNoSecretKey(), UserTest\testAutoblockCookies(), UserTest\testAutoblockCookiesDisabled(), UserTest\testIpBlockCookieIgnoredWhenUserLoggedIn(), UserTest\testIpBlockCookieNotSet(), UserTest\testIpBlockCookieSet(), and UserTest\testIsPingLimitable().

◆ newSystemUser()

static User::newSystemUser (   $name,
  $options = [] 
)
static

Static factory method for creation of a "system" user from username.

A "system" user is an account that's used to attribute logged actions taken by MediaWiki itself, as opposed to a bot or human user. Examples might include the 'Maintenance script' or 'Conversion script' accounts used by various scripts in the maintenance/ directory or accounts such as 'MediaWiki message delivery' used by the MassMessage extension.

This can optionally create the user if it doesn't exist, and "steal" the account if it does exist.

"Stealing" an existing user is intended to make it impossible for normal authentication processes to use the account, effectively disabling the account for normal use:

  • Email is invalidated, to prevent account recovery by emailing a temporary password and to disassociate the account from the existing human.
  • The token is set to a magic invalid value, to kill existing sessions and to prevent $this->setToken() calls from resetting the token to a valid value.
  • SessionManager is instructed to prevent new sessions for the user, to do things like deauthorizing OAuth consumers.
  • AuthManager is instructed to revoke access, to invalidate or remove passwords and other credentials.
Parameters
string$nameUsername
array$optionsOptions are:
  • validate: As for User::getCanonicalName(), default 'valid'
  • create: Whether to create the user if it doesn't already exist, default true
  • steal: Whether to "disable" the account for normal use if it already exists, default false
Returns
User|null
Since
1.27

Definition at line 819 of file User.php.

References $dbr, $name, $options, $user, createNew(), DB_MASTER, DB_REPLICA, getCanonicalName(), getQueryInfo(), INVALID_TOKEN, newFromRow(), and wfGetDB().

Referenced by Cleanup\execute(), Undelete\execute(), ImportSiteScripts\execute(), AddChangeTag\execute(), Protect\execute(), CleanupSpam\execute(), RollbackEdits\execute(), TableCleanup\execute(), EditCLI\execute(), DeleteBatch\execute(), ImportTextFiles\execute(), CleanupCaps\execute(), MoveBatch\execute(), DeleteEqualMessages\execute(), ImportImages\execute(), and PopulateArchiveRevId\makeDummyRevisionRow().

◆ newTouchedTimestamp()

User::newTouchedTimestamp ( )
private

Generate a current or new-future timestamp to be stored in the user_touched field when we update things.

Returns
string Timestamp in TS_MW format

Definition at line 2757 of file User.php.

References $time, $wgClockSkewFudge, and wfTimestamp().

Referenced by addToDatabase(), checkAndSetTouched(), and saveSettings().

◆ pingLimiter()

User::pingLimiter (   $action = 'edit',
  $incrBy = 1 
)

Primitive rate limits: enforce maximum actions per time period to put a brake on flooding.

The method generates both a generic profiling point and a per action one (suffix being "-$action".

Note
When using a shared cache like memcached, IP-address last-hit counters will be shared across wikis.
Parameters
string$actionAction to enforce; 'edit' if unspecified
int$incrByPositive amount to increment counter by [defaults to 1]
Returns
bool True if a rate limiter was tripped

Definition at line 2138 of file User.php.

References $cache, $keys, $user, $wgRateLimits, as, getGroups(), getId(), ObjectCache\getLocalClusterInstance(), getRequest(), IP\getSubnet(), isNewbie(), isPingLimitable(), list, Hooks\run(), wfDebug(), and wfDebugLog().

Referenced by PasswordReset\execute().

◆ purge()

static User::purge (   $wikiId,
  $userId 
)
static
Since
1.27
Parameters
string$wikiId
int$userId

Definition at line 494 of file User.php.

References $cache.

Referenced by UserRightsProxy\invalidateCache(), and UserTest\testActorId().

◆ randomPassword()

static User::randomPassword ( )
static

Return a random password.

Deprecated:
since 1.27, use PasswordFactory::generateRandomPasswordString()
Returns
string New random password

Definition at line 1294 of file User.php.

References $wgMinimalPasswordLength, and PasswordFactory\generateRandomPasswordString().

◆ removeGroup()

User::removeGroup (   $group)

Remove the user from the given group.

This takes immediate effect.

Parameters
string$groupName of the group to remove
Returns
bool

Definition at line 3763 of file User.php.

References getEffectiveGroups(), UserGroupMembership\getMembership(), invalidateCache(), load(), loadGroups(), and Hooks\run().

◆ removeWatch()

User::removeWatch (   $title,
  $checkRights = self::CHECK_USER_RIGHTS 
)

Stop watching an article.

Since
1.22 $checkRights parameter added
Parameters
Title$titleTitle of the article to look at
bool$checkRightsWhether to check 'viewmywatchlist'/'editmywatchlist' rights. Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.

Definition at line 3951 of file User.php.

References $title, invalidateCache(), and isAllowed().

◆ requiresHTTPS()

User::requiresHTTPS ( )

Determine based on the wiki configuration and the user's options, whether this user must be over HTTPS no matter what.

Returns
bool

Definition at line 3514 of file User.php.

References $wgSecureLogin, getBoolOption(), getRequest(), Hooks\run(), and wfCanIPUseHTTPS().

◆ resetIdByNameCache()

static User::resetIdByNameCache ( )
static

Reset the cache used in idFromName().

For use in tests.

Definition at line 951 of file User.php.

Referenced by MediaWikiTestCase\addCoreDBData().

◆ resetOptions()

User::resetOptions (   $resetKinds = [ 'registered',
'registered-multiselect'  ,
'registered-checkmatrix'  ,
'unused']  ,
IContextSource  $context = null 
)

Reset certain (or all) options to the site defaults.

The optional parameter determines which kinds of preferences will be reset. Supported values are everything that can be reported by getOptionKinds() and 'all', which forces a reset of all preferences and overrides everything else.

Parameters
array | string$resetKindsWhich kinds of preferences to reset. Defaults to array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ) for backwards-compatibility.
IContextSource | null$contextContext source used when $resetKinds does not contain 'all', passed to getOptionKinds(). Defaults to RequestContext::getMain() when null.

Definition at line 3449 of file User.php.

References $context, $value, as, getDefaultOptions(), RequestContext\getMain(), getOptionKinds(), load(), and Hooks\run().

◆ resetTokenFromOption()

User::resetTokenFromOption (   $oname)

Reset a token stored in the preferences (like the watchlist one).

Does not save user's preferences (similarly to setOption()).

Parameters
string$onameThe option name to reset the token in
Returns
string|bool New token value, or false if this option is disabled.
See also
getTokenFromOption()
setOption()

Definition at line 3307 of file User.php.

References $wgHiddenPrefs, MWCryptRand\generateHex(), and setOption().

◆ saveOptions()

User::saveOptions ( )
protected

Saves the non-default options for this user, as previously set e.g.

via setOption(), in the database's "user_properties" (preferences) table. Usually used via saveSettings().

Definition at line 5562 of file User.php.

References $mOptions, $res, $value, as, captcha-old\count, DB_MASTER, getDefaultOption(), getId(), loadOptions(), Hooks\run(), and wfGetDB().

Referenced by addToDatabase(), and saveSettings().

◆ saveSettings()

◆ selectFields()

static User::selectFields ( )
static

Return the list of user fields that should be selected to create a new user object.

Deprecated:
since 1.31, use self::getQueryInfo() instead.
Returns
array

Definition at line 5628 of file User.php.

References wfDeprecated().

Referenced by UserTest\testActorId().

◆ sendConfirmationMail()

User::sendConfirmationMail (   $type = 'created')

Generate a new e-mail confirmation token and send a confirmation/invalidation mail to the user's given address.

Parameters
string$typeMessage to send, either "created", "changed" or "set"
Returns
Status

Definition at line 4686 of file User.php.

References $type, $wgLang, confirmationToken(), confirmationTokenUrl(), getName(), getRequest(), invalidationTokenUrl(), saveSettings(), sendMail(), text, and wfMessage().

Referenced by setEmailWithConfirmation().

◆ sendMail()

User::sendMail (   $subject,
  $body,
  $from = null,
  $replyto = null 
)

Send an e-mail to this user's account.

Does not check for confirmed status or validity.

Parameters
string$subjectMessage subject
string$bodyMessage body
User | null$fromOptional sending user; if unspecified, default $wgPasswordSender will be used.
string | null$replytoReply-To address
Returns
Status

Definition at line 4725 of file User.php.

References $wgPasswordSender, MailAddress\newFromUser(), UserMailer\send(), text, and wfMessage().

Referenced by sendConfirmationMail(), and setEmailWithConfirmation().

◆ setCookies()

User::setCookies (   $request = null,
  $secure = null,
  $rememberMe = false 
)

Persist this user's session (e.g.

set cookies)

Parameters
WebRequest | null$requestWebRequest object to use; $wgRequest will be used if null is passed.
bool | null$secureWhether to force secure/insecure cookies or use default
bool$rememberMeWhether to add a Token cookie for elongated sessions

Definition at line 4104 of file User.php.

References $request, MediaWiki\Logger\LoggerFactory\getInstance(), getRequest(), and load().

◆ setEmail()

User::setEmail (   $str)

Set the user's e-mail address.

Parameters
string$strNew e-mail address

Definition at line 3072 of file User.php.

References invalidateEmail(), load(), and Hooks\run().

Referenced by setEmailWithConfirmation().

◆ setEmailAuthenticationTimestamp()

User::setEmailAuthenticationTimestamp (   $timestamp)

Set the e-mail authentication timestamp.

Parameters
string$timestampTS_MW timestamp

Definition at line 4840 of file User.php.

References load(), and Hooks\run().

Referenced by confirmEmail(), and invalidateEmail().

◆ setEmailWithConfirmation()

User::setEmailWithConfirmation (   $str)

Set the user's e-mail address and a confirmation mail if needed.

Since
1.20
Parameters
string$strNew e-mail address
Returns
Status

Definition at line 3089 of file User.php.

References $type, $wgEmailAuthentication, $wgEnableEmail, getEmail(), getName(), getRequest(), StatusValue\newFatal(), StatusValue\newGood(), sendConfirmationMail(), sendMail(), setEmail(), text, and wfMessage().

◆ setId()

User::setId (   $v)

Set the user and reload all fields according to a given ID.

Parameters
int$vUser ID to reload

Definition at line 2453 of file User.php.

References clearInstanceCache().

◆ setInternalPassword()

User::setInternalPassword (   $str)

Set the password and reset the random token unconditionally.

Deprecated:
since 1.27, use AuthManager instead
Parameters
string | null$strNew password to set or null to set an invalid password hash meaning that the user will not be able to log in through the web interface.

Definition at line 2908 of file User.php.

References setPasswordInternal(), and wfDeprecated().

◆ setItemLoaded()

User::setItemLoaded (   $item)
protected

Set that an item has been loaded.

Parameters
string$item

Definition at line 1356 of file User.php.

Referenced by getActorId(), and loadFromRow().

◆ setName()

User::setName (   $str)

Set the user name.

This does not reload fields from the database according to the given name. Rather, it is used to create a temporary "nonexistent user" for later addition to the database. It can also be used to set the IP address for an anonymous user to something other than the current remote IP.

Note
User::newFromName() has roughly the same function, when the named user does not exist.
Parameters
string$strNew user name to set

Definition at line 2489 of file User.php.

References load().

Referenced by UserTest\testActorId().

◆ setNewpassword()

User::setNewpassword (   $str,
  $throttle = true 
)

Set the password for a password reminder or new account email.

Deprecated:
Removed in 1.27. Use PasswordReset instead.
Parameters
string$strNew password to set or null to set an invalid password hash meaning that the user will not be able to use it
bool$throttleIf true, reset the throttle timestamp to the present

Definition at line 3044 of file User.php.

◆ setNewtalk()

User::setNewtalk (   $val,
  $curRev = null 
)

Update the 'You have new messages!' status.

Parameters
bool$valWhether the user has new messages
Revision | null$curRevNew, as yet unseen revision of the user talk page. Ignored if null or !$val.

Definition at line 2725 of file User.php.

References deleteNewtalk(), getId(), getName(), invalidateCache(), isAnon(), load(), updateNewtalk(), and wfReadOnly().

Referenced by clearAllNotifications(), and clearNotification().

◆ setOption()

User::setOption (   $oname,
  $val 
)

Set the given option for a user.

You need to call saveSettings() to actually write to the database.

Parameters
string$onameThe option to set
mixed$valNew value to set

Definition at line 3258 of file User.php.

References getDefaultOption(), and loadOptions().

Referenced by resetTokenFromOption(), setPasswordInternal(), and UserTest\testOptions().

◆ setPassword()

User::setPassword (   $str)

Set the password and reset the random token.

Calls through to authentication plugin if necessary; will have no effect if the auth plugin refuses to pass the change through or if the legal password checks fail.

As a special case, setting the password to null wipes it, so the account cannot be logged in until a new password is set, for instance via e-mail.

Deprecated:
since 1.27, use AuthManager instead
Parameters
string$strNew password to set
Exceptions
PasswordErrorOn failure
Returns
bool

Definition at line 2895 of file User.php.

References setPasswordInternal(), and wfDeprecated().

◆ setPasswordInternal()

User::setPasswordInternal (   $str)
private

Actually set the password and such.

Since
1.27 cannot set a password for a user not in the database
Parameters
string | null$strNew password to set or null to set an invalid password hash meaning that the user will not be able to log in through the web interface.
Returns
bool Success

Definition at line 2921 of file User.php.

References changeAuthenticationData(), MediaWiki\Logger\LoggerFactory\getInstance(), getName(), and setOption().

Referenced by setInternalPassword(), and setPassword().

◆ setRealName()

User::setRealName (   $str)

Set the user's real name.

Parameters
string$strNew real name

Definition at line 3156 of file User.php.

References load().

◆ setToken()

User::setToken (   $token = false)

Set the random token (used for persistent authentication) Called from loadDefaults() among other places.

Parameters
string | bool$tokenIf specified, set the token to this value

Definition at line 3024 of file User.php.

References MWCryptRand\generateHex(), MediaWiki\Logger\LoggerFactory\getInstance(), and load().

Referenced by addToDatabase(), and getToken().

◆ spreadAnyEditBlock()

User::spreadAnyEditBlock ( )

If this user is logged-in and blocked, block any IP address they've successfully logged in from.

Returns
bool A block was spread

Definition at line 4467 of file User.php.

References isBlocked(), isLoggedIn(), and spreadBlock().

◆ spreadBlock()

User::spreadBlock ( )
protected

If this (non-anonymous) user is blocked, block the IP address they've successfully logged in from.

Returns
bool A block was spread

Definition at line 4480 of file User.php.

References getName(), getRequest(), load(), Block\newFromTarget(), and wfDebug().

Referenced by spreadAnyEditBlock().

◆ touch()

User::touch ( )

Update the "touched" timestamp for the user.

This is useful on various login/logout events when making sure that a browser or proxy that has multiple tenants does not suffer cache pollution where the new user sees the old users content. The value of getTouched() is checked when determining 304 vs 200 responses. Unlike invalidateCache(), this preserves the User object cache and avoids database writes.

Since
1.25

Definition at line 2824 of file User.php.

References $cache, and getId().

Referenced by invalidateCache().

◆ trackBlockWithCookie()

User::trackBlockWithCookie ( )

Set the 'BlockID' cookie depending on block type and user authentication status.

Definition at line 1402 of file User.php.

References getBlock(), RequestContext\getMain(), getRequest(), isAnon(), isLoggedIn(), Block\TYPE_IP, Block\TYPE_RANGE, and Block\TYPE_USER.

Referenced by loadFromSession(), UserTest\testIpBlockCookieNotSet(), and UserTest\testIpBlockCookieSet().

◆ updateActorId()

User::updateActorId ( IDatabase  $dbw)
private

Update the actor ID after an insert.

Parameters
IDatabase$dbwWritable database handle

Definition at line 4449 of file User.php.

References $wgActorTableSchemaMigrationStage, Wikimedia\Rdbms\IDatabase\insert(), Wikimedia\Rdbms\IDatabase\insertId(), and SCHEMA_COMPAT_WRITE_NEW.

Referenced by addToDatabase().

◆ updateNewtalk()

User::updateNewtalk (   $field,
  $id,
  $curRev = null 
)
protected

Add or update the new messages flag.

Parameters
string$field'user_ip' for anonymous users, 'user_id' otherwise
string | int$idUser's IP address for anonymous users, User ID otherwise
Revision | null$curRevNew, as yet unseen revision of the user talk page. Ignored if null.
Returns
bool True if successful, false otherwise

Definition at line 2680 of file User.php.

References DB_MASTER, wfDebug(), and wfGetDB().

Referenced by setNewtalk().

◆ useFilePatrol()

User::useFilePatrol ( )

Check whether to enable new files patrol features for this user.

Returns
bool True or false

Definition at line 3890 of file User.php.

References $wgUseFilePatrol, $wgUseRCPatrol, and isAllowedAny().

◆ useNPPatrol()

User::useNPPatrol ( )

Check whether to enable new pages patrol features for this user.

Returns
bool True or false

Definition at line 3878 of file User.php.

References $wgUseNPPatrol, $wgUseRCPatrol, and isAllowedAny().

◆ useRCPatrol()

User::useRCPatrol ( )

Check whether to enable recent changes patrol features for this user.

Returns
bool True or false

Definition at line 3869 of file User.php.

References $wgUseRCPatrol, and isAllowedAny().

◆ validateCache()

User::validateCache (   $timestamp)

Validate the cache for this account.

Parameters
string$timestampA timestamp in TS_MW format
Returns
bool

Definition at line 2839 of file User.php.

References getTouched().

◆ whoIs()

static User::whoIs (   $id)
static

Get the username corresponding to a given user ID.

Parameters
int$idUser ID
Returns
string|bool The corresponding username

Definition at line 891 of file User.php.

References UserCache\singleton().

Referenced by Title\checkActionPermissions(), ApiUnblock\execute(), ApiBlock\execute(), UserrightsPage\fetchUser(), ImageListPager\formatValue(), and ApiBlockTest\testBlockOfNonexistentUserId().

◆ whoIsReal()

static User::whoIsReal (   $id)
static

Get the real name of a user given their user ID.

Parameters
int$idUser ID
Returns
string|bool The corresponding user's real name

Definition at line 901 of file User.php.

References UserCache\singleton().

Member Data Documentation

◆ $idCacheByName

User::$idCacheByName = []
static

Definition at line 309 of file User.php.

◆ $mActorId

int null User::$mActorId
protected

Definition at line 213 of file User.php.

Referenced by getActorId().

◆ $mAllowUsertalk

bool User::$mAllowUsertalk
protected

Definition at line 301 of file User.php.

◆ $mAllRights

User::$mAllRights = false
staticprotected

String Cached results of getAllRights()

Definition at line 204 of file User.php.

Referenced by getAllRights().

◆ $mBlock

Block User::$mBlock

Definition at line 298 of file User.php.

Referenced by isBlockedFromCreateAccount().

◆ $mBlockedby

string User::$mBlockedby

Definition at line 272 of file User.php.

Referenced by blockedBy().

◆ $mBlockedFromCreateAccount

Block User::$mBlockedFromCreateAccount = false
private

Definition at line 304 of file User.php.

◆ $mBlockreason

string User::$mBlockreason
protected

Definition at line 278 of file User.php.

Referenced by blockedFor().

◆ $mCacheVars

User::$mCacheVars
staticprotected
Initial value:
= [
'mId',
'mName',
'mRealName',
'mEmail',
'mTouched',
'mToken',
'mEmailAuthenticated',
'mEmailToken',
'mEmailTokenExpires',
'mRegistration',
'mEditCount',
'mGroupMemberships',
'mOptionOverrides',
'mActorId',
]

Array of Strings List of member variables which are saved to the shared cache (memcached).

Any operation which changes the corresponding database fields must call a cache-clearing function.

Definition at line 92 of file User.php.

◆ $mCoreRights

User::$mCoreRights
staticprotected
Initial value:
= [
'apihighlimits',
'applychangetags',
'autoconfirmed',
'autocreateaccount',
'autopatrol',
'bigdelete',
'block',
'blockemail',
'bot',
'browsearchive',
'changetags',
'createaccount',
'createpage',
'createtalk',
'delete',
'deletechangetags',
'deletedhistory',
'deletedtext',
'deletelogentry',
'deleterevision',
'edit',
'editcontentmodel',
'editinterface',
'editprotected',
'editmyoptions',
'editmyprivateinfo',
'editmyusercss',
'editmyuserjson',
'editmyuserjs',
'editmywatchlist',
'editsemiprotected',
'editsitecss',
'editsitejson',
'editsitejs',
'editusercss',
'edituserjson',
'edituserjs',
'hideuser',
'import',
'importupload',
'ipblock-exempt',
'managechangetags',
'markbotedits',
'mergehistory',
'minoredit',
'move',
'movefile',
'move-categorypages',
'move-rootuserpages',
'move-subpages',
'nominornewtalk',
'noratelimit',
'override-export-depth',
'pagelang',
'patrol',
'patrolmarks',
'protect',
'purge',
'read',
'reupload',
'reupload-own',
'reupload-shared',
'rollback',
'sendemail',
'siteadmin',
'suppressionlog',
'suppressredirect',
'suppressrevision',
'unblockself',
'undelete',
'unwatchedpages',
'upload',
'upload_by_url',
'userrights',
'userrights-interwiki',
'viewmyprivateinfo',
'viewmywatchlist',
'viewsuppressed',
'writeapi',
]

Array of Strings Core rights.

Each of these should have a corresponding message of the form "right-$right".

Definition at line 119 of file User.php.

Referenced by getAllRights().

◆ $mDatePreference

string User::$mDatePreference
protected

Definition at line 270 of file User.php.

Referenced by getDatePreference().

◆ $mEditCount

int User::$mEditCount
protected

Definition at line 234 of file User.php.

Referenced by getEditCount().

◆ $mEffectiveGroups

array User::$mEffectiveGroups
protected

Definition at line 280 of file User.php.

Referenced by getEffectiveGroups().

◆ $mEmail

string User::$mEmail

Definition at line 218 of file User.php.

Referenced by getEmail().

◆ $mEmailAuthenticated

string User::$mEmailAuthenticated

Definition at line 226 of file User.php.

Referenced by getEmailAuthenticationTimestamp().

◆ $mEmailToken

string User::$mEmailToken
protected

Definition at line 228 of file User.php.

Referenced by saveSettings().

◆ $mEmailTokenExpires

string User::$mEmailTokenExpires
protected

Definition at line 230 of file User.php.

◆ $mFormerGroups

array User::$mFormerGroups
protected

Definition at line 284 of file User.php.

Referenced by getFormerGroups().

◆ $mFrom

User::$mFrom

String Initialization data source if mLoadedItems!==true.

May be one of:

  • 'defaults' anonymous user initialised from class defaults
  • 'name' initialise from mName
  • 'id' initialise from mId
  • 'actor' initialise from mActorId
  • 'session' log in from session if possible

Use the User::newFrom*() family of functions to set this.

Definition at line 263 of file User.php.

◆ $mGlobalBlock

Block User::$mGlobalBlock
protected

Definition at line 286 of file User.php.

◆ $mGroupMemberships

UserGroupMembership [] User::$mGroupMemberships
protected

Associative array of (group name => UserGroupMembership object)

Definition at line 236 of file User.php.

Referenced by getGroupMemberships().

◆ $mHash

string User::$mHash
protected

Definition at line 274 of file User.php.

◆ $mHideName

bool User::$mHideName

Definition at line 290 of file User.php.

Referenced by isHidden().

◆ $mId

int User::$mId

Cache variables.

Definition at line 209 of file User.php.

Referenced by addToDatabase(), getCacheKey(), and getId().

◆ $mImplicitGroups

array User::$mImplicitGroups
protected

Definition at line 282 of file User.php.

Referenced by getAutomaticGroups().

◆ $mLoadedItems

User::$mLoadedItems = []
protected

Array with already loaded items or true if all items have been loaded.

Definition at line 250 of file User.php.

Referenced by load().

◆ $mLocked

bool User::$mLocked
protected

Definition at line 288 of file User.php.

Referenced by isLocked().

◆ $mName

string User::$mName

Definition at line 211 of file User.php.

Referenced by addToDatabase(), and getName().

◆ $mNewtalk

User::$mNewtalk
protected

Lazy-initialized variables, invalidated with clearInstanceCache.

Definition at line 268 of file User.php.

Referenced by getNewtalk().

◆ $mOptionOverrides

array User::$mOptionOverrides
protected

Definition at line 238 of file User.php.

◆ $mOptions

array User::$mOptions

Definition at line 292 of file User.php.

Referenced by getOptionKinds(), getOptions(), and saveOptions().

◆ $mOptionsLoaded

User::$mOptionsLoaded

Bool Whether the cache variables have been loaded.

Definition at line 245 of file User.php.

◆ $mQuickTouched

string User::$mQuickTouched
protected

TS_MW timestamp from cache.

Definition at line 222 of file User.php.

◆ $mRealName

string User::$mRealName

Definition at line 215 of file User.php.

Referenced by addToDatabase(), and getRealName().

◆ $mRegistration

string User::$mRegistration
protected

Definition at line 232 of file User.php.

Referenced by getRegistration().

◆ $mRequest

WebRequest User::$mRequest
private

Definition at line 295 of file User.php.

Referenced by getRequest().

◆ $mRights

array User::$mRights

Definition at line 276 of file User.php.

Referenced by getRights().

◆ $mToken

string User::$mToken
protected

Definition at line 224 of file User.php.

Referenced by getToken().

◆ $mTouched

string User::$mTouched

TS_MW timestamp from the DB.

Definition at line 220 of file User.php.

Referenced by getDBTouched(), and getTouched().

◆ $queryFlagsUsed

int User::$queryFlagsUsed = self::READ_NORMAL
protected

User::READ_* constant bitfield used to load data.

Definition at line 307 of file User.php.

◆ CHECK_USER_RIGHTS

const User::CHECK_USER_RIGHTS = true
Since
1.27

Definition at line 79 of file User.php.

◆ EDIT_TOKEN_SUFFIX

const User::EDIT_TOKEN_SUFFIX = Token::SUFFIX

Global constant made accessible as class constants so that autoloader magic can be used.

Deprecated:
since 1.27, use \MediaWiki\Session\Token::SUFFIX

Definition at line 63 of file User.php.

◆ GETOPTIONS_EXCLUDE_DEFAULTS

const User::GETOPTIONS_EXCLUDE_DEFAULTS = 1

Exclude user options that are set to their default value.

Since
1.25

Definition at line 74 of file User.php.

Referenced by ResourceLoaderUserOptionsModule\getScript(), and ResourceLoaderUserOptionsModule\isKnownEmpty().

◆ IGNORE_USER_RIGHTS

◆ INVALID_TOKEN

const User::INVALID_TOKEN = '*** INVALID ***'

@const string An invalid value for user_token

Definition at line 56 of file User.php.

Referenced by newSystemUser().

◆ TOKEN_LENGTH

const User::TOKEN_LENGTH = 32

@const int Number of characters in user_token field.

Definition at line 51 of file User.php.

Referenced by BotPassword\save().

◆ VERSION

const User::VERSION = 12

@const int Serialized record version.

Definition at line 68 of file User.php.

Referenced by loadFromCache().


The documentation for this class was generated from the following file: