MediaWiki master
MediaWiki\User\User Class Reference

User class for the MediaWiki software. More...

Inherits Stringable, MediaWiki\Permissions\Authority, MediaWiki\User\UserIdentity, and MediaWiki\Mail\UserEmailContact.

Collaboration diagram for MediaWiki\User\User:

Public Member Functions

 __construct ()
 
__get ( $name)
 
 __set ( $name, $value)
 
 __sleep ()
 
 __toString ()
 
 addToDatabase ()
 Add this existing user object to the database.
 
 authorizeAction (string $action, ?PermissionStatus $status=null)
 Authorize an action.This should be used immediately before performing the action.Calling this method may have non-trivial side-effects, such as incrementing a rate limit counter.
Since
1.41
See also
isDefinitelyAllowed
authorizeRead
authorizeWrite
Parameters
string$action
PermissionStatus | null$statusaggregator for failures
Returns
bool

 
 authorizeRead (string $action, PageIdentity $target, ?PermissionStatus $status=null)
 
 authorizeWrite (string $action, PageIdentity $target, ?PermissionStatus $status=null)
 
 canReceiveEmail ()
 Is this user allowed to receive e-mails within limits of current site configuration?
 
 canSendEmail ()
 Is this user allowed to send e-mails within limits of current site configuration?
 
 changeAuthenticationData (array $data)
 Changes credentials of the user.
 
 checkAndSetTouched ()
 Bump user_touched if it didn't change since this object was loaded.
 
 checkPasswordValidity ( $password)
 Check if this is a valid password for this user.
 
 clearInstanceCache ( $reloadFrom=false)
 Clear various cached data stored in this object.
 
 clearSharedCache ( $mode='refresh')
 Clear user data from memcached.
 
 confirmEmail ()
 Mark the e-mail address confirmed.
 
 debouncedDBTouch ()
 Update the db touched timestamp for the user if it hasn't been updated recently.
 
 definitelyCan (string $action, PageIdentity $target, ?PermissionStatus $status=null)
 
 doLogout ()
 Clear the user's session, and reset the instance cache.
 
 equals (?UserIdentity $user)
 Checks if two user objects point to the same user.
 
 getActorId ( $dbwOrWikiId=self::LOCAL)
 Get the user's actor ID.
 
 getBlock ( $freshness=IDBAccessObject::READ_NORMAL, $disableIpBlockExemptChecking=false)
 Get the block affecting the user, or null if the user is not blocked.
 
 getConfirmationToken (?string &$expiration, ?int $tokenLifeTimeSeconds=null)
 Generate, store, and return a new e-mail confirmation code.
 
 getConfirmationTokenUrl (string $token)
 Return a URL the user can use to confirm their email address.
 
 getDatePreference ()
 Get the user's preferred date format.
 
 getDBTouched ()
 Get the user_touched timestamp field (time of last DB updates)
 
 getEditCount ()
 Get the user's edit count.
 
 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.
 
 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.
 
 getEmail ()
 Get the user's e-mail address.
 
 getEmailAuthenticationTimestamp ()
 Get the timestamp of the user's e-mail authentication.
 
 getExperienceLevel ()
 Compute experienced level based on edit count and registration date.
 
 getId ( $wikiId=self::LOCAL)
 Get the user's ID.
 
 getInstanceForUpdate ()
 Get a new instance of this user that was loaded from the primary DB via a locking read.
 
 getInstanceFromPrimary (int $loadFlags=IDBAccessObject::READ_LATEST)
 Get an instance of this user that was loaded from the primary DB.
 
 getInvalidationTokenUrl (string $token)
 Return a URL the user can use to invalidate their email address.
 
 getName ()
 Get the user name, or the IP of an anonymous user.
 
 getRealName ()
 Get the user's real name.
 
 getRegistration ()
 Get the timestamp of account creation.
 
 getRequest ()
 Get the WebRequest object to use with this object.
 
 getTalkPage ()
 Get this user's talk page title.
 
 getTitleKey ()
 Get the user's name escaped by underscores.
 
 getToken ( $forceCreation=true)
 Get the user's current token.
 
 getTokenFromOption ( $oname)
 Get a token stored in the preferences (like the watchlist one), resetting it if it's empty (and saving changes).
 
 getTokenUrl (string $page, string $token)
 Function to create a special page URL with a token path parameter.
 
 getTouched ()
 Get the user touched timestamp.
 
 getUser ()
 
 getUserPage ()
 Get this user's personal page title.
 
 getWikiId ()
 Returns self::LOCAL to indicate the user is associated with the local wiki.
 
 idForName ( $flags=IDBAccessObject::READ_NORMAL)
 If only this user's username is known, and it exists, return the user ID.
 
 invalidateCache ()
 Immediately touch the user data cache for this account.
 
 invalidateEmail ()
 Invalidate the user's e-mail confirmation, and unauthenticate the e-mail address if it was already confirmed.
 
 isAllowed (string $permission, ?PermissionStatus $status=null)
 Checks whether this authority has the given permission in general.
 
 isAllowedAll (... $permissions)
 Checks whether this authority has any of the given permissions in general.Implementations must ensure that this method returns false if isAllowed would return false for any of the given permissions. Calling isAllowedAll() with one parameter must be equivalent to calling isAllowed(). Calling isAllowedAny() with no parameter is not allowed.
See also
isAllowed
Parameters
string...$permissions Permissions to test. At least one must be given.
Returns
bool True if the user is allowed to perform all of the given actions

 
 isAllowedAny (... $permissions)
 Checks whether this authority has any of the given permissions in general.Implementations must ensure that this method returns true if isAllowed would return true for any of the given permissions. Calling isAllowedAny() with one parameter must be equivalent to calling isAllowed(). Calling isAllowedAny() with no parameter is not allowed.
See also
isAllowed
Parameters
string...$permissions Permissions to test. At least one must be given.
Returns
bool True if user is allowed to perform any of the given actions

 
 isAllowedToCreateAccount ()
 Get whether the user is allowed to create an account.
 
 isAnon ()
 Get whether the user is anonymous.
 
 isBlockedFromEmailuser ()
 Get whether the user is blocked from using Special:Emailuser.
 
 isBlockedFromUpload ()
 Get whether the user is blocked from using Special:Upload.
 
 isBot ()
 
 isDefinitelyAllowed (string $action, ?PermissionStatus $status=null)
 Checks whether this authority is allowed to perform the given action.This method performs a thorough check, but does not protect against race conditions. It is intended to be used when a user is intending to perform an action, but has not yet committed to it. For example, when a user visits their preferences page, this method may be used to determine whether the user should have the option to change their email address.This method may apply rate limit checks and evaluate user blocks.
Since
1.41
See also
isAllowed
definitelyCan
Parameters
string$action
PermissionStatus | null$statusaggregator for failures
Returns
bool

 
 isEmailConfirmationPending ()
 Check whether there is an outstanding request for e-mail confirmation.
 
 isEmailConfirmed ()
 Is this user's e-mail address valid-looking and confirmed within limits of the current site configuration?
 
 isHidden ()
 Check if user account is hidden.
 
 isItemLoaded ( $item, $all='all')
 Return whether an item has been loaded.
 
 isLocked ()
 Check if user account is locked.
 
 isNamed ()
 Is the user a normal non-temporary registered user?
 
 isNewbie ()
 Determine whether the user is a newbie.
 
 isPingLimitable ()
 Is this user subject to rate limiting?
 
 isRegistered ()
 Get whether the user is registered.
 
 isSafeToLoad ()
 Test if it's safe to load this User object.
 
 isSystemUser ()
 Get whether the user is a system user.
 
 isTemp ()
 Is the user an autocreated temporary user?
 
 isValidPassword ( $password)
 Is the input a valid password for this user?
 
 load ( $flags=IDBAccessObject::READ_NORMAL)
 Load the user table data for this object from the source given by mFrom.
 
 loadDefaults ( $name=false, $actorId=null)
 Set cached properties to default.
 
 loadFromDatabase ( $flags=IDBAccessObject::READ_LATEST)
 Load user data from the database.
 
 loadFromId ( $flags=IDBAccessObject::READ_NORMAL)
 Load user table data, given mId has already been set.
 
 logout ()
 Log this user out.
 
 matchEditToken ( $val, $salt='', $request=null, $maxage=null)
 Check given value against the token value stored in the session.
 
 pingLimiter ( $action='edit', $incrBy=1)
 Primitive rate limits: enforce maximum actions per time period to put a brake on flooding.
 
 probablyCan (string $action, PageIdentity $target, ?PermissionStatus $status=null)
 
 requiresHTTPS ()
 Determine based on the wiki configuration and the user's options, whether this user must be over HTTPS no matter what.
 
 resetTokenFromOption ( $oname)
 Reset a token stored in the preferences (like the watchlist one).
 
 saveSettings ()
 Save this user's settings into the database.
 
 scheduleSpreadBlock ()
 Schedule a deferred update which will block the IP address of the current user, if they are blocked with the autoblocking option.
 
 sendConfirmationMail ( $type='created')
 Generate a new e-mail confirmation token and send a confirmation/invalidation mail to the user's given address.
 
 sendMail ( $subject, $body, $from=null, $replyto=null)
 Send an e-mail to this user's account.
 
 setActorId (int $actorId)
 Sets the actor id.
 
 setCookies ( $request=null, $secure=null, $rememberMe=false)
 Persist this user's session (e.g.
 
 setEmail (string $str)
 Set the user's e-mail address.
 
 setEmailAuthenticationTimestamp ( $timestamp)
 Set the e-mail authentication timestamp.
 
 setEmailWithConfirmation (string $str)
 Set the user's e-mail address and send a confirmation mail if needed.
 
 setId ( $v)
 Set the user and reload all fields according to a given ID.
 
 setItemLoaded ( $item)
 Set that an item has been loaded.
 
 setName ( $str)
 Set the user name.
 
 setRealName (string $str)
 Set the user's real name.
 
 setToken ( $token=false)
 Set the random token (used for persistent authentication) Called from loadDefaults() among other places.
 
 spreadAnyEditBlock ()
 If this user is logged-in and blocked, block any IP address they've successfully logged in from.
 
 toRateLimitSubject ()
 
 touch ()
 Update the "touched" timestamp for the user.
 
 useFilePatrol ()
 Check whether to enable new files patrol features for this user.
 
 useNPPatrol ()
 Check whether to enable new pages patrol features for this user.
 
 useRCPatrol ()
 Check whether to enable recent changes patrol features for this user.
 
 validateCache ( $timestamp)
 Validate the cache for this account.
 
- Public Member Functions inherited from MediaWiki\Permissions\Authority
 getBlock (int $freshness=IDBAccessObject::READ_NORMAL)
 Returns any user block affecting the Authority.
 
- Public Member Functions inherited from MediaWiki\DAO\WikiAwareEntity
 assertWiki ( $wikiId)
 Throws if $wikiId is different from the return value of getWikiId().
 

Static Public Member Functions

static createNew ( $name, $params=[])
 Add a user to the database, return the user object.
 
static findUsersByGroup ( $groups, $limit=5000, $after=null)
 Return the users who are members of the given group(s).
 
static getQueryInfo ()
 Return the tables, fields, and join conditions to be selected to create a new user object.
 
static getRightDescription ( $right)
 Get the description of a given right as wikitext.
 
static getRightDescriptionHtml ( $right)
 Get the description of a given right as rendered HTML.
 
static isWellFormedConfirmationToken (string $token)
 Check if the given email confirmation token is well-formed (to detect mangling by email clients).
 
static newFatalPermissionDeniedStatus ( $permission)
 Factory function for fatal permission-denied errors.
 
static newQueryBuilder (IReadableDatabase $db)
 Get a SelectQueryBuilder with the tables, fields and join conditions needed to create a new User object.
 
static purge ( $dbDomain, $userId)
 
newFrom*() static factory methods
static newFromName ( $name, $validate='valid')
 
static newFromId ( $id)
 Static factory method for creation from a given user ID.
 
static newFromActorId ( $id)
 Static factory method for creation from a given actor ID.
 
static newFromIdentity (UserIdentity $identity)
 Returns a User object corresponding to the given UserIdentity.
 
static newFromAnyId ( $userId, $userName, $actorId, $dbDomain=false)
 Static factory method for creation from an ID, name, and/or actor ID.
 
static newFromConfirmationCode ( $code, $flags=IDBAccessObject::READ_NORMAL)
 Factory method to fetch whichever user has a given email confirmation code.
 
static newFromSession (?WebRequest $request=null)
 Create a new user object using data from session.
 
static newFromRow ( $row, $data=null)
 Create a new user object from a user row.
 
static newSystemUser ( $name, $options=[])
 Static factory method for creation of a "system" user from username.
 

Public Attributes

int null $mActorId
 Switched from protected to public for use in UserFactory.
 
string $mEmail
 
string null $mEmailAuthenticated
 
string $mFrom
 Initialization data source if mLoadedItems!==true.
 
int $mId
 Cache variables.
 
string $mName
 
string $mRealName
 
string $mTouched
 TS::MW timestamp from the DB.
 
const INVALID_TOKEN = '*** INVALID ***'
 An invalid string value for the user_token field.
 
const MAINTENANCE_SCRIPT_USER = 'Maintenance script'
 Username used for various maintenance scripts.
 
const READ_EXCLUSIVE = IDBAccessObject::READ_EXCLUSIVE
 
const READ_LOCKING = IDBAccessObject::READ_LOCKING
 
const TOKEN_LENGTH = 32
 Number of characters required for the user_token field.
 
- Public Attributes inherited from MediaWiki\DAO\WikiAwareEntity
const LOCAL = false
 Wiki ID value to use with instances that are defined relative to the local wiki.
 

Protected Member Functions

 confirmationToken (&$expiration)
 Deprecated alias for getConfirmationToken() for CentralAuth.
 
 getCacheKey (WANObjectCache $cache)
 
 invalidationTokenUrl ( $token)
 Deprecated alias for getInvalidationTokenUrl() for CentralAuth.
 
 loadFromCache ()
 Load user data from shared cache, given mId has already been set.
 
 loadFromRow ( $row, $data=null)
 Initialize this object from a row from the user table.
 
 loadFromUserObject ( $user)
 Load the data for this user object from another user object.
 
 makeUpdateConditions (IReadableDatabase $db)
 Build additional update conditions to protect against race conditions using a compare-and-set (CAS) mechanism based on comparing $this->mTouched with the user_touched field.
 
 spreadBlock (Block $block)
 If this (non-anonymous) user is blocked, block the IP address they've successfully logged in from.
 

Protected Attributes

string null $mDatePreference
 Lazy-initialized variables, invalidated with clearInstanceCache.
 
string null $mEmailToken
 
string null $mEmailTokenExpires
 
AbstractBlock false null $mGlobalBlock
 Null when uninitialized, false when there is no block.
 
array bool $mLoadedItems = []
 Array with already loaded items or true if all items have been loaded.
 
bool null $mLocked
 
string null $mQuickTouched
 TS::MW timestamp from cache.
 
string null $mToken
 
int $queryFlagsUsed = IDBAccessObject::READ_NORMAL
 IDBAccessObject::READ_* constant bitfield used to load data.
 

Static Protected Attributes

static string[] $mCacheVars
 List of member variables which are saved to the shared cache (memcached).
 

Detailed Description

User class for the MediaWiki software.

User objects manage reading and writing of user-specific storage, including:

  • user table (user_id, user_name, email, password, last login, etc.)
  • user_properties table (user options)
  • user_groups table (user rights and permissions)
  • user_newtalk table (last-seen for your own user talk page)
  • watchlist table (watched page titles by user, and their last-seen marker)
  • block table, formerly known as ipblocks (user blocks)

Callers use getter methods (getXXX) to read these fields. These getter functions manage all higher-level responsibilities such as expanding default user options, interpreting user groups into specific rights. Most user data needed when rendering page views are cached (or stored in the session) to minimize repeat database queries.

New code is encouraged to use the following narrower classes instead. If no replacement exist, and the User class method is not deprecated, feel free to use it in new code (instead of duplicating business logic).

  • UserIdentityValue, to represent a user name/id.
  • UserOptionsManager service, to read-write user options.
  • Authority via RequestContext::getAuthority, to represent the current user with a easy shortcuts to interpret user permissions (can user X do Y on page Z) without needing te call low-level PermissionManager and RateLimiter services. Authority replaces methods like User::isAllowed, User::definitelyCan, and User::pingLimiter.
  • PermissionManager service, to interpret rights and permissions of any user.
  • TalkPageNotificationManager service, replacing User::getNewtalk.
  • WatchlistManager service, replacing methods like User::isWatched, User::addWatch, and User::clearNotification.
  • BlockManager service, replacing User::getBlock.
Note
User implements Authority to ease transition. Always prefer using existing Authority or obtaining a proper Authority implementation.

Definition at line 110 of file User.php.

Constructor & Destructor Documentation

◆ __construct()

MediaWiki\User\User::__construct ( )
Access: internal
since 1.36, use the UserFactory service instead
See also
\MediaWiki\User management\UserFactory
newFromName()
newFromId()
newFromActorId()
newFromConfirmationCode()
newFromSession()
newFromRow()

Definition at line 258 of file User.php.

References MediaWiki\User\User\clearInstanceCache().

Member Function Documentation

◆ __get()

& MediaWiki\User\User::__get ( $name)

◆ __set()

MediaWiki\User\User::__set ( $name,
$value )

◆ __sleep()

MediaWiki\User\User::__sleep ( )

Definition at line 318 of file User.php.

◆ __toString()

MediaWiki\User\User::__toString ( )
Returns
string

Definition at line 276 of file User.php.

◆ addToDatabase()

MediaWiki\User\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->isRegistered() ) { $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 isRegistered(), and to commit the transaction after calling.

Returns
Status

Definition at line 2521 of file User.php.

References Wikimedia\Rdbms\IDatabase\affectedRows(), Wikimedia\Rdbms\IDatabase\insertId(), Wikimedia\Rdbms\IDatabase\newInsertQueryBuilder(), Wikimedia\Rdbms\IReadableDatabase\newSelectQueryBuilder(), Wikimedia\Rdbms\Platform\ISQLPlatform\timestamp(), and Wikimedia\Rdbms\Platform\ISQLPlatform\timestampOrNull().

Referenced by MediaWiki\Auth\AuthManager\autoCreateUser().

◆ authorizeAction()

MediaWiki\User\User::authorizeAction ( string $action,
?PermissionStatus $status = null )

Authorize an action.This should be used immediately before performing the action.Calling this method may have non-trivial side-effects, such as incrementing a rate limit counter.

Since
1.41
See also
isDefinitelyAllowed
authorizeRead
authorizeWrite
Parameters
string$action
PermissionStatus | null$statusaggregator for failures
Returns
bool

Since
1.41
Parameters
string$action
PermissionStatus | null$status
Returns
bool

Implements MediaWiki\Permissions\Authority.

Definition at line 3307 of file User.php.

◆ authorizeRead()

MediaWiki\User\User::authorizeRead ( string $action,
PageIdentity $target,
?PermissionStatus $status = null )
Since
1.36
Parameters
string$action
PageIdentity$target
PermissionStatus | null$status
Returns
bool

Implements MediaWiki\Permissions\Authority.

Definition at line 3318 of file User.php.

◆ authorizeWrite()

MediaWiki\User\User::authorizeWrite ( string $action,
PageIdentity $target,
?PermissionStatus $status = null )
Since
1.36
Parameters
string$action
PageIdentity$target
PermissionStatus | null$status
Returns
bool

Implements MediaWiki\Permissions\Authority.

Definition at line 3333 of file User.php.

◆ canReceiveEmail()

MediaWiki\User\User::canReceiveEmail ( )

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

Returns
bool

Definition at line 3015 of file User.php.

References MediaWiki\User\Options\UserOptionsLookup\getOption().

◆ canSendEmail()

MediaWiki\User\User::canSendEmail ( )

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

Deprecated
since 1.41, emits deprecation warnings since 1.43. Use EmailUser::canSend() instead.
Returns
bool

Definition at line 3002 of file User.php.

References wfDeprecated().

◆ changeAuthenticationData()

MediaWiki\User\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 1754 of file User.php.

◆ checkAndSetTouched()

MediaWiki\User\User::checkAndSetTouched ( )

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.

Access: internal
Returns
bool Whether user_touched was actually updated
Since
1.26

Definition at line 1269 of file User.php.

References $success.

◆ checkPasswordValidity()

MediaWiki\User\User::checkPasswordValidity ( $password)

Check if this is a valid password for this user.

Returns a Status object with a set of messages describing problems with the password. If the return status is fatal, the action should be refused and the password should not be checked at all (this is mainly meant for DoS mitigation). If the return value is OK but not good, the password can be checked, but the user should not be able to set their password to this. The value of the returned Status object will be an array which can have the following fields:

  • forceChange (bool): if set to true, the user should not be allowed to log with this password unless they change it during the login process (see ResetPasswordSecondaryAuthenticationProvider).
  • suggestChangeOnLogin (bool): if set to true, the user should be prompted for a password change on login.
Parameters
string$passwordDesired password
Returns
Status
Since
1.23

Definition at line 952 of file User.php.

◆ clearInstanceCache()

MediaWiki\User\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 1306 of file User.php.

References $wgFullyInitialised.

Referenced by MediaWiki\User\User\__construct().

◆ clearSharedCache()

MediaWiki\User\User::clearSharedCache ( $mode = 'refresh')

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 or 'changed' to clear before DB commit

Definition at line 1625 of file User.php.

◆ confirmationToken()

MediaWiki\User\User::confirmationToken ( & $expiration)
protected

Deprecated alias for getConfirmationToken() for CentralAuth.

Deprecated
Use getConfirmationToken() instead.
Parameters
string | null&$expiration
Returns
string

Definition at line 2882 of file User.php.

◆ confirmEmail()

MediaWiki\User\User::confirmEmail ( )

Mark the e-mail address confirmed.

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

Definition at line 2957 of file User.php.

References wfTimestampNow().

◆ createNew()

static MediaWiki\User\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.
  • 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 2426 of file User.php.

◆ debouncedDBTouch()

MediaWiki\User\User::debouncedDBTouch ( )

Update the db touched timestamp for the user if it hasn't been updated recently.

Since
1.45

Definition at line 1683 of file User.php.

◆ definitelyCan()

MediaWiki\User\User::definitelyCan ( string $action,
PageIdentity $target,
?PermissionStatus $status = null )
Since
1.36
Parameters
string$action
PageIdentity$target
PermissionStatus | null$status
Returns
bool

Implements MediaWiki\Permissions\Authority.

Definition at line 3279 of file User.php.

◆ doLogout()

MediaWiki\User\User::doLogout ( )

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

See also
logout()

Definition at line 2277 of file User.php.

◆ equals()

MediaWiki\User\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 | null$user
Returns
bool

Implements MediaWiki\User\UserIdentity.

Definition at line 3240 of file User.php.

Referenced by MediaWiki\Actions\RevertAction\checkCanExecute().

◆ findUsersByGroup()

static MediaWiki\User\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
UserArray|ArrayIterator

Definition at line 899 of file User.php.

◆ getActorId()

MediaWiki\User\User::getActorId ( $dbwOrWikiId = self::LOCAL)

Get the user's actor ID.

Since
1.31
Note
This method was removed from the UserIdentity interface in 1.36, but remains supported in the User class for now. New code should use ActorNormalization::findActorId() or ActorNormalization::acquireActorId() instead.
Parameters
IDatabase | string | false$dbwOrWikiIdDeprecated since 1.36. If a database connection is passed, a new actor ID is assigned if needed. ActorNormalization::acquireActorId() should be used for that purpose instead.
Returns
int The actor's ID, or 0 if no actor ID exists and $dbw was null
Exceptions
PreconditionExceptionif $dbwOrWikiId is a string and does not match the local wiki

Definition at line 1550 of file User.php.

References wfDeprecatedMsg().

◆ getBlock()

MediaWiki\User\User::getBlock ( $freshness = IDBAccessObject::READ_NORMAL,
$disableIpBlockExemptChecking = false )

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

Parameters
int | bool$freshnessOne of the IDBAccessObject::READ_XXX constants. For backwards compatibility, a boolean is also accepted, with true meaning READ_NORMAL and false meaning READ_LATEST.
bool$disableIpBlockExemptCheckingThis is used internally to prevent a infinite recursion with autopromote. See T270145.
Returns
?AbstractBlock

Definition at line 1405 of file User.php.

Referenced by MediaWiki\Actions\Action\checkCanExecute(), MediaWiki\SpecialPage\FormSpecialPage\checkExecutePermissions(), MediaWiki\SpecialPage\ContributionsSpecialPage\getUserLinks(), and MediaWiki\Block\BlockManager\trackBlockWithCookie().

◆ getCacheKey()

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

Definition at line 505 of file User.php.

References Wikimedia\ObjectCache\WANObjectCache\makeGlobalKey().

◆ getConfirmationToken()

MediaWiki\User\User::getConfirmationToken ( ?string & $expiration,
?int $tokenLifeTimeSeconds = null )

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

A hash (unsalted, since it's used as a key) is stored. Any preexisting e-mail confirmation token will be invalidated.

Note
Call saveSettings() after calling this function to commit this change to the database.
Since
1.45
Parameters
null | string&$expirationTimestamp at which the generated token expires
int | null$tokenLifeTimeSecondsOptional lifetime of the token in seconds. Defaults to the value of $wgUserEmailConfirmationTokenExpiry if not set.
Returns
string New token

Definition at line 2858 of file User.php.

◆ getConfirmationTokenUrl()

MediaWiki\User\User::getConfirmationTokenUrl ( string $token)

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

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

Definition at line 2903 of file User.php.

◆ getDatePreference()

MediaWiki\User\User::getDatePreference ( )

Get the user's preferred date format.

Returns
string User's preferred date format

Definition at line 2014 of file User.php.

References $wgLang, and MediaWiki\User\Options\UserOptionsLookup\getOption().

◆ getDBTouched()

MediaWiki\User\User::getDBTouched ( )

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

Returns
string TS::MW Timestamp
Since
1.26

Definition at line 1736 of file User.php.

◆ getEditCount()

MediaWiki\User\User::getEditCount ( )

Get the user's edit count.

Returns
int|null Null for anonymous users

Definition at line 2057 of file User.php.

Referenced by MediaWiki\Preferences\DefaultPreferencesFactory\profilePreferences().

◆ getEditToken()

MediaWiki\User\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
Deprecated
since 1.37. Use CsrfTokenSet::getToken instead
Parameters
string | string[]$saltOptional function-specific data for hashing
WebRequest | null$requestWebRequest object to use, or null to use the global request
Returns
string The new edit token

Definition at line 2753 of file User.php.

Referenced by MediaWiki\Specials\SpecialWatchlist\setTopText().

◆ getEditTokenObject()

MediaWiki\User\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
Deprecated
since 1.37. Use CsrfTokenSet::getToken instead
Parameters
string | string[]$saltOptional function-specific data for hashing
WebRequest | null$requestWebRequest object to use, or null to use the global request
Returns
Token The new edit token

Definition at line 2728 of file User.php.

Referenced by MediaWiki\Api\ApiQueryTokens\getToken().

◆ getEmail()

MediaWiki\User\User::getEmail ( )

Get the user's e-mail address.

Returns
string User's email address

Implements MediaWiki\Mail\UserEmailContact.

Definition at line 1841 of file User.php.

Referenced by MediaWiki\Preferences\DefaultPreferencesFactory\profilePreferences().

◆ getEmailAuthenticationTimestamp()

MediaWiki\User\User::getEmailAuthenticationTimestamp ( )

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

Returns
string TS::MW timestamp

Definition at line 1854 of file User.php.

Referenced by MediaWiki\Preferences\DefaultPreferencesFactory\profilePreferences().

◆ getExperienceLevel()

MediaWiki\User\User::getExperienceLevel ( )

Compute experienced level based on edit count and registration date.

Returns
string|false 'newcomer', 'learner', or 'experienced', false for anonymous users

Definition at line 2186 of file User.php.

References wfTimestamp().

◆ getId()

MediaWiki\User\User::getId ( $wikiId = self::LOCAL)

Get the user's ID.

Parameters
string | false$wikiIdThe wiki ID expected by the caller.
Returns
int The user's ID; 0 if the user is anonymous or nonexistent

Implements MediaWiki\User\UserIdentity.

Definition at line 1471 of file User.php.

Referenced by MediaWiki\Upload\UploadFromChunks\__construct(), MediaWiki\Auth\AuthManager\autoCreateUser(), MediaWiki\Auth\AuthManager\beginAccountLink(), MediaWiki\SpecialPage\ContributionsSpecialPage\getUserLinks(), and MediaWiki\Actions\CreditsAction\link().

◆ getInstanceForUpdate()

MediaWiki\User\User::getInstanceForUpdate ( )

Get a new instance of this user that was loaded from the primary DB 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 primary DB but without proper locks.

Returns
User|null Returns null if the user was not found in the DB
Since
1.27
Deprecated
since 1.45. Use User::getInstanceFromPrimary() instead. The exact equivalent of this method is getInstanceFromPrimary() with the READ_EXCLUSIVE flag, but most callers didn't actually need an exclusive lock, and overusing it is harmful, so consider whether you really need locking. Note that getInstanceFromPrimary() is not guaranteed to return a new instance if the original User object was already from the primary DB.

Definition at line 3196 of file User.php.

References wfDeprecated().

◆ getInstanceFromPrimary()

MediaWiki\User\User::getInstanceFromPrimary ( int $loadFlags = IDBAccessObject::READ_LATEST)

Get an instance of this user that was loaded from the primary DB.

If the user object was already from the primary DB (and more generally matches $loadFlags), it will be returned; otherwise a DB query will be performed and a new User instance returned.

Use this instead of the main context User when updating that user or updating something else based on the user's data, to avoid updating based on outdated information.

Optionally you can set a shared or exclusive lock on the user record with the $loadFlags option. Only use this (especially with an exclusive lock) when absolutely necessary, as overuse of locks can have significant performance impact.

Parameters
int$loadFlagsOptional IDBAccessObject flags for locking
Returns
User|null Returns null if the user was not found in the DB
Since
1.45

Definition at line 3218 of file User.php.

◆ getInvalidationTokenUrl()

MediaWiki\User\User::getInvalidationTokenUrl ( string $token)

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

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

Definition at line 2914 of file User.php.

◆ getName()

◆ getQueryInfo()

static MediaWiki\User\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() or SelectQueryBuilder::tables
  • fields: (string[]) to include in the $vars to IDatabase->select() or SelectQueryBuilder::fields
  • joins: (array) to include in the $join_conds to IDatabase->select() or SelectQueryBuilder::joinConds

Definition at line 3109 of file User.php.

◆ getRealName()

MediaWiki\User\User::getRealName ( )

◆ getRegistration()

MediaWiki\User\User::getRegistration ( )

Get the timestamp of account creation.

Deprecated
since 1.45 use UserRegistrationLookup instead.
Returns
string|false|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 3066 of file User.php.

Referenced by MediaWiki\Preferences\DefaultPreferencesFactory\profilePreferences().

◆ getRequest()

MediaWiki\User\User::getRequest ( )

Get the WebRequest object to use with this object.

Definition at line 2177 of file User.php.

Referenced by MediaWiki\User\PasswordReset\execute(), and MediaWiki\Block\BlockManager\trackBlockWithCookie().

◆ getRightDescription()

static MediaWiki\User\User::getRightDescription ( $right)
static

Get the description of a given right as wikitext.

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

Definition at line 3079 of file User.php.

References wfMessage().

◆ getRightDescriptionHtml()

static MediaWiki\User\User::getRightDescriptionHtml ( $right)
static

Get the description of a given right as rendered HTML.

Since
1.42
Parameters
string$rightRight to query
Returns
string HTML description of the right

Definition at line 3092 of file User.php.

References wfMessage().

◆ getTalkPage()

MediaWiki\User\User::getTalkPage ( )

Get this user's talk page title.

Returns
Title

Definition at line 2699 of file User.php.

Referenced by MediaWiki\SpecialPage\ContributionsSpecialPage\getUserLinks().

◆ getTitleKey()

MediaWiki\User\User::getTitleKey ( )

Get the user's name escaped by underscores.

Returns
string Username escaped by underscores.

Definition at line 1596 of file User.php.

Referenced by MediaWiki\Preferences\DefaultPreferencesFactory\profilePreferences().

◆ getToken()

MediaWiki\User\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 1781 of file User.php.

◆ getTokenFromOption()

MediaWiki\User\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|false 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 1965 of file User.php.

References MediaWiki\User\Options\UserOptionsLookup\getOption().

Referenced by MediaWiki\Specials\SpecialWatchlist\outputFeedLinks().

◆ getTokenUrl()

MediaWiki\User\User::getTokenUrl ( string $page,
string $token )

Function to create a special page URL with a token path parameter.

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 really long URL-encoded links, which also sometimes can get corrupted in some browsers/mailers (T8957 with Gmail and Internet Explorer).
Since
1.45
Parameters
string$pageSpecial page
string$token
Returns
string Formatted URL

Definition at line 2944 of file User.php.

◆ getTouched()

MediaWiki\User\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 1714 of file User.php.

References wfTimestamp().

◆ getUser()

MediaWiki\User\User::getUser ( )
Note
This is only here for compatibility with the Authority interface.
Since
1.36
Returns
UserIdentity $this

Implements MediaWiki\Permissions\Authority.

Definition at line 3253 of file User.php.

◆ getUserPage()

MediaWiki\User\User::getUserPage ( )

Get this user's personal page title.

Returns
Title User's personal page title

Definition at line 2690 of file User.php.

References NS_USER.

Referenced by MediaWiki\Auth\AuthManager\autoCreateUser(), and MediaWiki\SpecialPage\ContributionsSpecialPage\getUserLinks().

◆ getWikiId()

MediaWiki\User\User::getWikiId ( )

Returns self::LOCAL to indicate the user is associated with the local wiki.

Since
1.36

Implements MediaWiki\DAO\WikiAwareEntity.

Definition at line 269 of file User.php.

◆ idForName()

MediaWiki\User\User::idForName ( $flags = IDBAccessObject::READ_NORMAL)

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

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

Definition at line 2393 of file User.php.

◆ invalidateCache()

MediaWiki\User\User::invalidateCache ( )

Immediately touch the user data cache for this account.

Calls touch() and removes account data from memcached

Definition at line 1651 of file User.php.

◆ invalidateEmail()

MediaWiki\User\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 2974 of file User.php.

◆ invalidationTokenUrl()

MediaWiki\User\User::invalidationTokenUrl ( $token)
protected

Deprecated alias for getInvalidationTokenUrl() for CentralAuth.

Deprecated
Use getInvalidationTokenUrl() instead.
Parameters
string$tokenAccepts the email confirmation token
Returns
string New token URL

Definition at line 2925 of file User.php.

◆ isAllowed()

MediaWiki\User\User::isAllowed ( string $permission,
?PermissionStatus $status = null )

Checks whether this authority has the given permission in general.

For some permissions, exceptions may exist, both positive and negative, on a per-target basis. This method offers a fast, lightweight check, but may produce false positives. It is intended for determining which UI elements should be offered to the user.

This method will not apply rate limit checks or evaluate user blocks.

Parameters
string$permission
PermissionStatus | null$status
Returns
bool
See also
isDefinitelyAllowed
probablyCan

Implements MediaWiki\Permissions\Authority.

Definition at line 2130 of file User.php.

Referenced by MediaWiki\Actions\WatchAction\checkCanExecute(), MediaWiki\Preferences\DefaultPreferencesFactory\editingPreferences(), MediaWiki\Preferences\DefaultPreferencesFactory\getForm(), MediaWiki\Preferences\DefaultPreferencesFactory\profilePreferences(), MediaWiki\Preferences\DefaultPreferencesFactory\renderingPreferences(), and MediaWiki\Preferences\DefaultPreferencesFactory\watchlistPreferences().

◆ isAllowedAll()

MediaWiki\User\User::isAllowedAll ( $permissions)

Checks whether this authority has any of the given permissions in general.Implementations must ensure that this method returns false if isAllowed would return false for any of the given permissions. Calling isAllowedAll() with one parameter must be equivalent to calling isAllowed(). Calling isAllowedAny() with no parameter is not allowed.

See also
isAllowed
Parameters
string...$permissions Permissions to test. At least one must be given.
Returns
bool True if the user is allowed to perform all of the given actions

Implements MediaWiki\Permissions\Authority.

Definition at line 2126 of file User.php.

◆ isAllowedAny()

MediaWiki\User\User::isAllowedAny ( $permissions)

Checks whether this authority has any of the given permissions in general.Implementations must ensure that this method returns true if isAllowed would return true for any of the given permissions. Calling isAllowedAny() with one parameter must be equivalent to calling isAllowed(). Calling isAllowedAny() with no parameter is not allowed.

See also
isAllowed
Parameters
string...$permissions Permissions to test. At least one must be given.
Returns
bool True if user is allowed to perform any of the given actions

Implements MediaWiki\Permissions\Authority.

Definition at line 2121 of file User.php.

Referenced by MediaWiki\Actions\RevertAction\checkCanExecute(), and MediaWiki\Preferences\DefaultPreferencesFactory\watchlistPreferences().

◆ isAllowedToCreateAccount()

MediaWiki\User\User::isAllowedToCreateAccount ( )

Get whether the user is allowed to create an account.

Returns
bool

Definition at line 2681 of file User.php.

◆ isAnon()

MediaWiki\User\User::isAnon ( )

◆ isBlockedFromEmailuser()

MediaWiki\User\User::isBlockedFromEmailuser ( )

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

Returns
bool
Deprecated
since 1.41, emits deprecation warnings since 1.43. EmailUser::canSend checks blocks amongst other things. If you only need this check, use ::getBlock()->appliesToRight( 'sendemail' ).

Definition at line 2660 of file User.php.

References wfDeprecated().

◆ isBlockedFromUpload()

MediaWiki\User\User::isBlockedFromUpload ( )

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

Since
1.33
Returns
bool

Definition at line 2672 of file User.php.

◆ isBot()

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

Definition at line 2087 of file User.php.

Referenced by MediaWiki\Api\getWatchlistValue().

◆ isDefinitelyAllowed()

MediaWiki\User\User::isDefinitelyAllowed ( string $action,
?PermissionStatus $status = null )

Checks whether this authority is allowed to perform the given action.This method performs a thorough check, but does not protect against race conditions. It is intended to be used when a user is intending to perform an action, but has not yet committed to it. For example, when a user visits their preferences page, this method may be used to determine whether the user should have the option to change their email address.This method may apply rate limit checks and evaluate user blocks.

Since
1.41
See also
isAllowed
definitelyCan
Parameters
string$action
PermissionStatus | null$statusaggregator for failures
Returns
bool

Since
1.41
Parameters
string$action
PermissionStatus | null$status
Returns
bool

Implements MediaWiki\Permissions\Authority.

Definition at line 3295 of file User.php.

◆ isEmailConfirmationPending()

MediaWiki\User\User::isEmailConfirmationPending ( )

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

Returns
bool

Definition at line 3049 of file User.php.

References wfTimestamp().

◆ isEmailConfirmed()

MediaWiki\User\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

Implements MediaWiki\Mail\UserEmailContact.

Definition at line 3031 of file User.php.

◆ isHidden()

MediaWiki\User\User::isHidden ( )

Check if user account is hidden.

Returns
bool True if hidden, false otherwise

Definition at line 1461 of file User.php.

◆ isItemLoaded()

MediaWiki\User\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 1032 of file User.php.

◆ isLocked()

MediaWiki\User\User::isLocked ( )

Check if user account is locked.

Returns
bool True if locked, false otherwise

Definition at line 1446 of file User.php.

◆ isNamed()

MediaWiki\User\User::isNamed ( )

Is the user a normal non-temporary registered user?

Since
1.39
Returns
bool

Implements MediaWiki\Permissions\Authority.

Definition at line 3402 of file User.php.

◆ isNewbie()

MediaWiki\User\User::isNewbie ( )

Determine whether the user is a newbie.

Newbies are one of:

  • IP address editors
  • temporary accounts
  • most recently created full accounts.
    Returns
    bool

Definition at line 2711 of file User.php.

◆ isPingLimitable()

MediaWiki\User\User::isPingLimitable ( )

Is this user subject to rate limiting?

Returns
bool True if rate limited

Definition at line 1355 of file User.php.

◆ isRegistered()

MediaWiki\User\User::isRegistered ( )

Get whether the user is registered.

Returns
bool True if user is registered on this wiki, i.e., has a user ID. False if user is anonymous or has no local account (which can happen when importing). This is equivalent to getId() != 0 and is provided for code readability.
Since
1.34

Implements MediaWiki\Permissions\Authority.

Definition at line 2071 of file User.php.

Referenced by MediaWiki\Auth\AuthManager\beginAccountLink(), MediaWiki\Actions\WatchAction\checkCanExecute(), UppercaseTitlesForUnicodeTransition\execute(), and MediaWiki\Language\LanguageConverter\getUserVariant().

◆ isSafeToLoad()

MediaWiki\User\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 342 of file User.php.

References $wgFullyInitialised.

Referenced by MediaWiki\Language\LanguageConverter\getUserVariant(), and MediaWiki\Block\BlockManager\trackBlockWithCookie().

◆ isSystemUser()

MediaWiki\User\User::isSystemUser ( )

Get whether the user is a system user.

A user is considered to exist as a non-system user if it can authenticate, or has an email set, or has a non-invalid token.

Returns
bool Whether this user is a system user
Since
1.35

Definition at line 2110 of file User.php.

◆ isTemp()

MediaWiki\User\User::isTemp ( )

Is the user an autocreated temporary user?

Since
1.39
Returns
bool

Implements MediaWiki\Permissions\Authority.

Definition at line 3388 of file User.php.

Referenced by MediaWiki\Actions\WatchAction\checkCanExecute(), and MediaWiki\SpecialPage\ContributionsSpecialPage\getUserLinks().

◆ isValidPassword()

MediaWiki\User\User::isValidPassword ( $password)

Is the input a valid password for this user?

Parameters
string$passwordDesired password
Returns
bool

Definition at line 926 of file User.php.

◆ isWellFormedConfirmationToken()

static MediaWiki\User\User::isWellFormedConfirmationToken ( string $token)
static

Check if the given email confirmation token is well-formed (to detect mangling by email clients).

This does not check whether the token is valid.

Parameters
string$token
Returns
bool

Definition at line 2892 of file User.php.

◆ load()

MediaWiki\User\User::load ( $flags = IDBAccessObject::READ_NORMAL)

Load the user table data for this object from the source given by mFrom.

Parameters
int$flagsIDBAccessObject::READ_* constant bitfield

Definition at line 359 of file User.php.

References $wgFullyInitialised, MW_ENTRY_POINT, and MW_NO_SESSION.

Referenced by MediaWiki\Session\UserInfo\newFromId().

◆ loadDefaults()

MediaWiki\User\User::loadDefaults ( $name = false,
$actorId = null )

Set cached properties to default.

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

Definition at line 996 of file User.php.

References wfTimestamp().

◆ loadFromCache()

MediaWiki\User\User::loadFromCache ( )
protected

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

Returns
bool True
Since
1.25

Definition at line 518 of file User.php.

References $wgFullyInitialised, wfDebug(), and wfTimestamp().

◆ loadFromDatabase()

MediaWiki\User\User::loadFromDatabase ( $flags = IDBAccessObject::READ_LATEST)

Load user data from the database.

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

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

Definition at line 1081 of file User.php.

◆ loadFromId()

MediaWiki\User\User::loadFromId ( $flags = IDBAccessObject::READ_NORMAL)

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

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

Definition at line 464 of file User.php.

Referenced by MediaWiki\Auth\AuthManager\autoCreateUser().

◆ loadFromRow()

MediaWiki\User\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.

Definition at line 1127 of file User.php.

References wfTimestamp(), and wfTimestampOrNull().

Referenced by MediaWiki\User\User\newFromRow().

◆ loadFromUserObject()

MediaWiki\User\User::loadFromUserObject ( $user)
protected

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

Parameters
User$user

Definition at line 1237 of file User.php.

◆ logout()

MediaWiki\User\User::logout ( )

Log this user out.

Definition at line 2267 of file User.php.

◆ makeUpdateConditions()

MediaWiki\User\User::makeUpdateConditions ( IReadableDatabase $db)
protected

Build additional update conditions to protect against race conditions using a compare-and-set (CAS) mechanism based on comparing $this->mTouched with the user_touched field.

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

Definition at line 1251 of file User.php.

References Wikimedia\Rdbms\Platform\ISQLPlatform\timestamp().

◆ matchEditToken()

MediaWiki\User\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.

Deprecated
since 1.37. Use CsrfTokenSet::matchToken instead
Parameters
string | null$valInput value to compare
string | array$saltOptional function-specific data for hashing
WebRequest | null$requestObject to use, or null to use the global request
int | null$maxageFail tokens older than this, in seconds
Returns
bool Whether the token matches

Definition at line 2770 of file User.php.

◆ newFatalPermissionDeniedStatus()

static MediaWiki\User\User::newFatalPermissionDeniedStatus ( $permission)
static

Factory function for fatal permission-denied errors.

Since
1.22
Deprecated
since 1.41, use Authority::isAllowed instead. Core code can also use PermissionManager::newFatalPermissionDeniedStatus.
Parameters
string$permissionUser right required
Returns
Status

Definition at line 3173 of file User.php.

◆ newFromActorId()

static MediaWiki\User\User::newFromActorId ( $id)
static

Static factory method for creation from a given actor ID.

See also
UserFactory::newFromActorId
Deprecated
since 1.36, use a UserFactory instead
Since
1.31
Parameters
int$idValid actor ID
Returns
User

Definition at line 645 of file User.php.

◆ newFromAnyId()

static MediaWiki\User\User::newFromAnyId ( $userId,
$userName,
$actorId,
$dbDomain = false )
static

Static factory method for creation from an ID, name, and/or actor ID.

This does not check that the ID, name, and actor ID all correspond to the same user.

See also
UserFactory::newFromAnyId
Deprecated
since 1.36, use a UserFactory instead
Since
1.31
Parameters
int | null$userIdUser ID, if known
string | null$userNameUser name, if known
int | null$actorIdActor ID, if known
string | false$dbDomainremote wiki to which the User/Actor ID applies, or false if none
Returns
User

Definition at line 694 of file User.php.

◆ newFromConfirmationCode()

static MediaWiki\User\User::newFromConfirmationCode ( $code,
$flags = IDBAccessObject::READ_NORMAL )
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.

See also
UserFactory::newFromConfirmationCode
Deprecated
since 1.36, use a UserFactory instead
Parameters
string$codeConfirmation code
int$flagsIDBAccessObject::READ_* bitfield
Returns
User|null

Definition at line 715 of file User.php.

◆ newFromId()

static MediaWiki\User\User::newFromId ( $id)
static

Static factory method for creation from a given user ID.

See also
UserFactory::newFromId
Deprecated
since 1.36, use a UserFactory instead
Parameters
int$idValid user ID
Returns
User

Definition at line 628 of file User.php.

Referenced by MediaWiki\Session\UserInfo\newFromId(), and MediaWiki\User\Options\UserOptionsUpdateJob\run().

◆ newFromIdentity()

static MediaWiki\User\User::newFromIdentity ( UserIdentity $identity)
static

Returns a User object corresponding to the given UserIdentity.

See also
UserFactory::newFromUserIdentity
Deprecated
since 1.36, use a UserFactory instead
Since
1.32
Parameters
UserIdentity$identity
Returns
User

Definition at line 664 of file User.php.

◆ newFromName()

static MediaWiki\User\User::newFromName ( $name,
$validate = 'valid' )
static
See also
UserFactory::newFromName
Deprecated
since 1.36, use a UserFactory instead

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.Type 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, except that true is accepted as an alias for 'valid', for BC.
Returns
User|false 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 602 of file User.php.

Referenced by RenameUsersMatchingPattern\execute(), MediaWiki\Session\UserInfo\newFromName(), and MediaWiki\Specials\SpecialEmailUser\userForm().

◆ newFromRow()

static MediaWiki\User\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 750 of file User.php.

References MediaWiki\User\User\loadFromRow().

Referenced by MediaWiki\User\UserArrayFromResult\setCurrent().

◆ newFromSession()

static MediaWiki\User\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; the global request will be used if omitted.
Returns
User

Definition at line 728 of file User.php.

◆ newQueryBuilder()

static MediaWiki\User\User::newQueryBuilder ( IReadableDatabase $db)
static

Get a SelectQueryBuilder with the tables, fields and join conditions needed to create a new User object.

The return value is a plain SelectQueryBuilder, not a UserSelectQueryBuilder. That way, there is no need for an ActorStore.

Returns
SelectQueryBuilder

Definition at line 3143 of file User.php.

References Wikimedia\Rdbms\IReadableDatabase\newSelectQueryBuilder().

◆ newSystemUser()

static MediaWiki\User\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.

System users should usually be listed in $wgReservedUsernames.

Parameters
string$nameUsername
array$optionsOptions are:
  • validate: Type 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, default 'valid'. Deprecated since 1.36.
  • 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
See also
self::isSystemUser()
MainConfigSchema::ReservedUsernames

Definition at line 800 of file User.php.

References wfDeprecatedMsg().

◆ pingLimiter()

MediaWiki\User\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 1376 of file User.php.

Referenced by MediaWiki\User\PasswordReset\execute().

◆ probablyCan()

MediaWiki\User\User::probablyCan ( string $action,
PageIdentity $target,
?PermissionStatus $status = null )
Since
1.36
Parameters
string$action
PageIdentity$target
PermissionStatus | null$status
Returns
bool

Implements MediaWiki\Permissions\Authority.

Definition at line 3264 of file User.php.

◆ purge()

static MediaWiki\User\User::purge ( $dbDomain,
$userId )
static
Since
1.27
Parameters
string$dbDomain
int$userId

Definition at line 494 of file User.php.

◆ requiresHTTPS()

MediaWiki\User\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 2036 of file User.php.

◆ resetTokenFromOption()

MediaWiki\User\User::resetTokenFromOption ( $oname)

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

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

Parameters
string$onameThe option name to reset the token in
Returns
string|false New token value, or false if this option is disabled.
See also
getTokenFromOption()
\MediaWiki\User management\Options\UserOptionsManager::setOption

Definition at line 1996 of file User.php.

◆ saveSettings()

◆ scheduleSpreadBlock()

MediaWiki\User\User::scheduleSpreadBlock ( )

Schedule a deferred update which will block the IP address of the current user, if they are blocked with the autoblocking option.

Since
1.45

Definition at line 2600 of file User.php.

References Profiler\instance().

◆ sendConfirmationMail()

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

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

Any preexisting e-mail confirmation token will be invalidated.

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

Definition at line 2782 of file User.php.

◆ sendMail()

MediaWiki\User\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 | string[]$bodyMessage body or array containing keys text and html
User | null$fromOptional sending user; if unspecified, default $wgPasswordSender will be used.
MailAddress | null$replytoReply-To address
Returns
Status

Definition at line 2812 of file User.php.

References wfMessage().

◆ setActorId()

MediaWiki\User\User::setActorId ( int $actorId)

Sets the actor id.

For use by ActorStore only. Should be removed once callers of getActorId() have been migrated to using ActorNormalization.

Access: internal
Deprecated
since 1.36
Parameters
int$actorId

Definition at line 1587 of file User.php.

◆ setCookies()

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

Persist this user's session (e.g.

set cookies)

Parameters
WebRequest | null$requestWebRequest object to use; the global request 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 2230 of file User.php.

◆ setEmail()

MediaWiki\User\User::setEmail ( string $str)

Set the user's e-mail address.

Parameters
string$strNew e-mail address

Definition at line 1865 of file User.php.

◆ setEmailAuthenticationTimestamp()

MediaWiki\User\User::setEmailAuthenticationTimestamp ( $timestamp)

Set the e-mail authentication timestamp.

Parameters
string | null$timestampTS::MW timestamp

Definition at line 2988 of file User.php.

◆ setEmailWithConfirmation()

MediaWiki\User\User::setEmailWithConfirmation ( string $str)

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

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

Definition at line 1882 of file User.php.

References wfMessage().

◆ setId()

MediaWiki\User\User::setId ( $v)

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

Parameters
int$vUser ID to reload

Definition at line 1495 of file User.php.

Referenced by MediaWiki\Auth\AuthManager\autoCreateUser().

◆ setItemLoaded()

MediaWiki\User\User::setItemLoaded ( $item)

Set that an item has been loaded.

Access: internal
Only public for use in UserFactory
Parameters
string$item

Definition at line 1044 of file User.php.

◆ setName()

MediaWiki\User\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 1532 of file User.php.

◆ setRealName()

MediaWiki\User\User::setRealName ( string $str)

Set the user's real name.

Parameters
string$strNew real name

Definition at line 1950 of file User.php.

◆ setToken()

MediaWiki\User\User::setToken ( $token = false)

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

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

Definition at line 1825 of file User.php.

Referenced by MediaWiki\Session\SessionManager\invalidateSessionsForUser().

◆ spreadAnyEditBlock()

MediaWiki\User\User::spreadAnyEditBlock ( )

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

Calls the "SpreadAnyEditBlock" hook, so this may block the IP address using a non-core blocking mechanism.

Returns
bool A block was spread

Definition at line 2615 of file User.php.

◆ spreadBlock()

MediaWiki\User\User::spreadBlock ( Block $block)
protected

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

Parameters
Block$blockThe active block on the user
Returns
bool A block was spread

Definition at line 2637 of file User.php.

◆ toRateLimitSubject()

MediaWiki\User\User::toRateLimitSubject ( )
Access: internal
for use by UserAuthority only!
Returns
RateLimitSubject

Definition at line 1384 of file User.php.

◆ touch()

MediaWiki\User\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 1668 of file User.php.

◆ useFilePatrol()

MediaWiki\User\User::useFilePatrol ( )

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

Returns
bool True or false

Definition at line 2163 of file User.php.

Referenced by MediaWiki\RecentChanges\ChangesList\isUnpatrolled().

◆ useNPPatrol()

MediaWiki\User\User::useNPPatrol ( )

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

Returns
bool True or false

Definition at line 2148 of file User.php.

Referenced by MediaWiki\RecentChanges\ChangesList\isUnpatrolled(), and MediaWiki\Preferences\DefaultPreferencesFactory\rcPreferences().

◆ useRCPatrol()

MediaWiki\User\User::useRCPatrol ( )

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

Returns
bool True or false

Definition at line 2138 of file User.php.

Referenced by MediaWiki\RecentChanges\ChangesList\isUnpatrolled(), MediaWiki\Preferences\DefaultPreferencesFactory\rcPreferences(), and MediaWiki\Preferences\DefaultPreferencesFactory\watchlistPreferences().

◆ validateCache()

MediaWiki\User\User::validateCache ( $timestamp)

Validate the cache for this account.

Parameters
string$timestampA timestamp in TS::MW format
Returns
bool

Definition at line 1702 of file User.php.

Member Data Documentation

◆ $mActorId

int null MediaWiki\User\User::$mActorId

Switched from protected to public for use in UserFactory.

Definition at line 182 of file User.php.

◆ $mCacheVars

string [] MediaWiki\User\User::$mCacheVars
staticprotected
Initial value:
= [
'mId',
'mName',
'mRealName',
'mEmail',
'mTouched',
'mToken',
'mEmailAuthenticated',
'mEmailToken',
'mEmailTokenExpires',
'mActorId',
]

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 154 of file User.php.

◆ $mDatePreference

string null MediaWiki\User\User::$mDatePreference
protected

Lazy-initialized variables, invalidated with clearInstanceCache.

Definition at line 225 of file User.php.

◆ $mEmail

string MediaWiki\User\User::$mEmail

Definition at line 187 of file User.php.

◆ $mEmailAuthenticated

string null MediaWiki\User\User::$mEmailAuthenticated

Definition at line 195 of file User.php.

◆ $mEmailToken

string null MediaWiki\User\User::$mEmailToken
protected

Definition at line 197 of file User.php.

◆ $mEmailTokenExpires

string null MediaWiki\User\User::$mEmailTokenExpires
protected

Definition at line 199 of file User.php.

◆ $mFrom

string MediaWiki\User\User::$mFrom

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 219 of file User.php.

◆ $mGlobalBlock

AbstractBlock false null MediaWiki\User\User::$mGlobalBlock
protected

Null when uninitialized, false when there is no block.

Definition at line 227 of file User.php.

◆ $mId

int MediaWiki\User\User::$mId

Cache variables.

Definition at line 174 of file User.php.

◆ $mLoadedItems

array bool MediaWiki\User\User::$mLoadedItems = []
protected

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

Definition at line 206 of file User.php.

◆ $mLocked

bool null MediaWiki\User\User::$mLocked
protected

Definition at line 229 of file User.php.

◆ $mName

string MediaWiki\User\User::$mName

Definition at line 176 of file User.php.

◆ $mQuickTouched

string null MediaWiki\User\User::$mQuickTouched
protected

TS::MW timestamp from cache.

Definition at line 191 of file User.php.

◆ $mRealName

string MediaWiki\User\User::$mRealName

Definition at line 184 of file User.php.

◆ $mToken

string null MediaWiki\User\User::$mToken
protected

Definition at line 193 of file User.php.

◆ $mTouched

string MediaWiki\User\User::$mTouched

TS::MW timestamp from the DB.

Definition at line 189 of file User.php.

◆ $queryFlagsUsed

int MediaWiki\User\User::$queryFlagsUsed = IDBAccessObject::READ_NORMAL
protected

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

Definition at line 235 of file User.php.

◆ INVALID_TOKEN

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

An invalid string value for the user_token field.

Definition at line 133 of file User.php.

◆ MAINTENANCE_SCRIPT_USER

const MediaWiki\User\User::MAINTENANCE_SCRIPT_USER = 'Maintenance script'

Username used for various maintenance scripts.

Since
1.37

Definition at line 145 of file User.php.

◆ READ_EXCLUSIVE

const MediaWiki\User\User::READ_EXCLUSIVE = IDBAccessObject::READ_EXCLUSIVE
See also
IDBAccessObject::READ_EXCLUSIVE

Definition at line 118 of file User.php.

◆ READ_LOCKING

const MediaWiki\User\User::READ_LOCKING = IDBAccessObject::READ_LOCKING
See also
IDBAccessObject::READ_LOCKING

Definition at line 123 of file User.php.

◆ TOKEN_LENGTH

const MediaWiki\User\User::TOKEN_LENGTH = 32

Number of characters required for the user_token field.

Definition at line 128 of file User.php.


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