3 * Implements the User class for the %MediaWiki software.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use MediaWiki\Session\SessionManager
;
26 * String Some punctuation to prevent editing from broken text-mangling proxies.
27 * @deprecated since 1.27, use \\MediaWiki\\Session\\Token::SUFFIX
30 define( 'EDIT_TOKEN_SUFFIX', MediaWiki\Session\Token
::SUFFIX
);
33 * The User object encapsulates all of the user-specific settings (user_id,
34 * name, rights, email address, options, last login time). Client
35 * classes use the getXXX() functions to access these fields. These functions
36 * do all the work of determining whether the user is logged in,
37 * whether the requested option can be satisfied from cookies or
38 * whether a database query is needed. Most of the settings needed
39 * for rendering normal pages are set in the cookie to minimize use
42 class User
implements IDBAccessObject
{
44 * @const int Number of characters in user_token field.
46 const TOKEN_LENGTH
= 32;
49 * Global constant made accessible as class constants so that autoloader
51 * @deprecated since 1.27, use \\MediaWiki\\Session\\Token::SUFFIX
53 const EDIT_TOKEN_SUFFIX
= EDIT_TOKEN_SUFFIX
;
56 * @const int Serialized record version.
61 * Maximum items in $mWatchedItems
63 const MAX_WATCHED_ITEMS_CACHE
= 100;
66 * Exclude user options that are set to their default value.
69 const GETOPTIONS_EXCLUDE_DEFAULTS
= 1;
72 * Array of Strings List of member variables which are saved to the
73 * shared cache (memcached). Any operation which changes the
74 * corresponding database fields must call a cache-clearing function.
77 protected static $mCacheVars = array(
85 'mEmailAuthenticated',
92 // user_properties table
97 * Array of Strings Core rights.
98 * Each of these should have a corresponding message of the form
102 protected static $mCoreRights = array(
132 'editusercssjs', # deprecated
145 'move-categorypages',
146 'move-rootuserpages',
150 'override-export-depth',
173 'userrights-interwiki',
181 * String Cached results of getAllRights()
183 protected static $mAllRights = false;
185 /** Cache variables */
195 /** @var string TS_MW timestamp from the DB */
197 /** @var string TS_MW timestamp from cache */
198 protected $mQuickTouched;
202 public $mEmailAuthenticated;
204 protected $mEmailToken;
206 protected $mEmailTokenExpires;
208 protected $mRegistration;
210 protected $mEditCount;
214 protected $mOptionOverrides;
218 * Bool Whether the cache variables have been loaded.
221 public $mOptionsLoaded;
224 * Array with already loaded items or true if all items have been loaded.
226 protected $mLoadedItems = array();
230 * String Initialization data source if mLoadedItems!==true. May be one of:
231 * - 'defaults' anonymous user initialised from class defaults
232 * - 'name' initialise from mName
233 * - 'id' initialise from mId
234 * - 'session' log in from session if possible
236 * Use the User::newFrom*() family of functions to set this.
241 * Lazy-initialized variables, invalidated with clearInstanceCache
245 protected $mDatePreference;
253 protected $mBlockreason;
255 protected $mEffectiveGroups;
257 protected $mImplicitGroups;
259 protected $mFormerGroups;
261 protected $mBlockedGlobally;
278 protected $mAllowUsertalk;
281 private $mBlockedFromCreateAccount = false;
284 private $mWatchedItems = array();
286 /** @var integer User::READ_* constant bitfield used to load data */
287 protected $queryFlagsUsed = self
::READ_NORMAL
;
289 public static $idCacheByName = array();
292 * Lightweight constructor for an anonymous user.
293 * Use the User::newFrom* factory functions for other kinds of users.
297 * @see newFromConfirmationCode()
298 * @see newFromSession()
301 public function __construct() {
302 $this->clearInstanceCache( 'defaults' );
308 public function __toString() {
309 return $this->getName();
313 * Load the user table data for this object from the source given by mFrom.
315 * @param integer $flags User::READ_* constant bitfield
317 public function load( $flags = self
::READ_NORMAL
) {
318 global $wgFullyInitialised;
320 if ( $this->mLoadedItems
=== true ) {
324 // Set it now to avoid infinite recursion in accessors
325 $oldLoadedItems = $this->mLoadedItems
;
326 $this->mLoadedItems
= true;
327 $this->queryFlagsUsed
= $flags;
329 // If this is called too early, things are likely to break.
330 if ( $this->mFrom
=== 'session' && empty( $wgFullyInitialised ) ) {
331 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
332 ->warning( 'User::loadFromSession called before the end of Setup.php', array(
333 'exception' => new Exception( 'User::loadFromSession called before the end of Setup.php' ),
335 $this->loadDefaults();
336 $this->mLoadedItems
= $oldLoadedItems;
340 switch ( $this->mFrom
) {
342 $this->loadDefaults();
345 // Make sure this thread sees its own changes
346 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
347 $flags |
= self
::READ_LATEST
;
348 $this->queryFlagsUsed
= $flags;
351 $this->mId
= self
::idFromName( $this->mName
, $flags );
353 // Nonexistent user placeholder object
354 $this->loadDefaults( $this->mName
);
356 $this->loadFromId( $flags );
360 $this->loadFromId( $flags );
363 if ( !$this->loadFromSession() ) {
364 // Loading from session failed. Load defaults.
365 $this->loadDefaults();
367 Hooks
::run( 'UserLoadAfterLoadFromSession', array( $this ) );
370 throw new UnexpectedValueException(
371 "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
376 * Load user table data, given mId has already been set.
377 * @param integer $flags User::READ_* constant bitfield
378 * @return bool False if the ID does not exist, true otherwise
380 public function loadFromId( $flags = self
::READ_NORMAL
) {
381 if ( $this->mId
== 0 ) {
382 $this->loadDefaults();
386 // Try cache (unless this needs data from the master DB).
387 // NOTE: if this thread called saveSettings(), the cache was cleared.
388 $latest = DBAccessObjectUtils
::hasFlags( $flags, self
::READ_LATEST
);
389 if ( $latest ||
!$this->loadFromCache() ) {
390 wfDebug( "User: cache miss for user {$this->mId}\n" );
391 // Load from DB (make sure this thread sees its own changes)
392 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
393 $flags |
= self
::READ_LATEST
;
395 if ( !$this->loadFromDatabase( $flags ) ) {
396 // Can't load from ID, user is anonymous
399 $this->saveToCache();
402 $this->mLoadedItems
= true;
403 $this->queryFlagsUsed
= $flags;
410 * @param string $wikiId
411 * @param integer $userId
413 public static function purge( $wikiId, $userId ) {
414 $cache = ObjectCache
::getMainWANInstance();
415 $cache->delete( $cache->makeGlobalKey( 'user', 'id', $wikiId, $userId ) );
420 * @param WANObjectCache $cache
423 protected function getCacheKey( WANObjectCache
$cache ) {
424 return $cache->makeGlobalKey( 'user', 'id', wfWikiID(), $this->mId
);
428 * Load user data from shared cache, given mId has already been set.
430 * @return bool false if the ID does not exist or data is invalid, true otherwise
433 protected function loadFromCache() {
434 if ( $this->mId
== 0 ) {
435 $this->loadDefaults();
439 $cache = ObjectCache
::getMainWANInstance();
440 $data = $cache->get( $this->getCacheKey( $cache ) );
441 if ( !is_array( $data ) ||
$data['mVersion'] < self
::VERSION
) {
446 wfDebug( "User: got user {$this->mId} from cache\n" );
448 // Restore from cache
449 foreach ( self
::$mCacheVars as $name ) {
450 $this->$name = $data[$name];
457 * Save user data to the shared cache
459 * This method should not be called outside the User class
461 public function saveToCache() {
464 $this->loadOptions();
466 if ( $this->isAnon() ) {
467 // Anonymous users are uncached
472 foreach ( self
::$mCacheVars as $name ) {
473 $data[$name] = $this->$name;
475 $data['mVersion'] = self
::VERSION
;
476 $opts = Database
::getCacheSetOptions( wfGetDB( DB_SLAVE
) );
478 $cache = ObjectCache
::getMainWANInstance();
479 $key = $this->getCacheKey( $cache );
480 $cache->set( $key, $data, $cache::TTL_HOUR
, $opts );
483 /** @name newFrom*() static factory methods */
487 * Static factory method for creation from username.
489 * This is slightly less efficient than newFromId(), so use newFromId() if
490 * you have both an ID and a name handy.
492 * @param string $name Username, validated by Title::newFromText()
493 * @param string|bool $validate Validate username. Takes the same parameters as
494 * User::getCanonicalName(), except that true is accepted as an alias
495 * for 'valid', for BC.
497 * @return User|bool User object, or false if the username is invalid
498 * (e.g. if it contains illegal characters or is an IP address). If the
499 * username is not present in the database, the result will be a user object
500 * with a name, zero user ID and default settings.
502 public static function newFromName( $name, $validate = 'valid' ) {
503 if ( $validate === true ) {
506 $name = self
::getCanonicalName( $name, $validate );
507 if ( $name === false ) {
510 // Create unloaded user object
514 $u->setItemLoaded( 'name' );
520 * Static factory method for creation from a given user ID.
522 * @param int $id Valid user ID
523 * @return User The corresponding User object
525 public static function newFromId( $id ) {
529 $u->setItemLoaded( 'id' );
534 * Factory method to fetch whichever user has a given email confirmation code.
535 * This code is generated when an account is created or its e-mail address
538 * If the code is invalid or has expired, returns NULL.
540 * @param string $code Confirmation code
541 * @param int $flags User::READ_* bitfield
544 public static function newFromConfirmationCode( $code, $flags = 0 ) {
545 $db = ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
546 ?
wfGetDB( DB_MASTER
)
547 : wfGetDB( DB_SLAVE
);
549 $id = $db->selectField(
553 'user_email_token' => md5( $code ),
554 'user_email_token_expires > ' . $db->addQuotes( $db->timestamp() ),
558 return $id ? User
::newFromId( $id ) : null;
562 * Create a new user object using data from session. If the login
563 * credentials are invalid, the result is an anonymous user.
565 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
568 public static function newFromSession( WebRequest
$request = null ) {
570 $user->mFrom
= 'session';
571 $user->mRequest
= $request;
576 * Create a new user object from a user row.
577 * The row should have the following fields from the user table in it:
578 * - either user_name or user_id to load further data if needed (or both)
580 * - all other fields (email, etc.)
581 * It is useless to provide the remaining fields if either user_id,
582 * user_name and user_real_name are not provided because the whole row
583 * will be loaded once more from the database when accessing them.
585 * @param stdClass $row A row from the user table
586 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
589 public static function newFromRow( $row, $data = null ) {
591 $user->loadFromRow( $row, $data );
596 * Static factory method for creation of a "system" user from username.
598 * A "system" user is an account that's used to attribute logged actions
599 * taken by MediaWiki itself, as opposed to a bot or human user. Examples
600 * might include the 'Maintenance script' or 'Conversion script' accounts
601 * used by various scripts in the maintenance/ directory or accounts such
602 * as 'MediaWiki message delivery' used by the MassMessage extension.
604 * This can optionally create the user if it doesn't exist, and "steal" the
605 * account if it does exist.
607 * @param string $name Username
608 * @param array $options Options are:
609 * - validate: As for User::getCanonicalName(), default 'valid'
610 * - create: Whether to create the user if it doesn't already exist, default true
611 * - steal: Whether to reset the account's password and email if it
612 * already exists, default false
615 public static function newSystemUser( $name, $options = array() ) {
617 'validate' => 'valid',
622 $name = self
::getCanonicalName( $name, $options['validate'] );
623 if ( $name === false ) {
627 $dbw = wfGetDB( DB_MASTER
);
628 $row = $dbw->selectRow(
631 self
::selectFields(),
632 array( 'user_password', 'user_newpassword' )
634 array( 'user_name' => $name ),
638 // No user. Create it?
639 return $options['create'] ? self
::createNew( $name ) : null;
641 $user = self
::newFromRow( $row );
643 // A user is considered to exist as a non-system user if it has a
644 // password set, or a temporary password set, or an email set.
645 $passwordFactory = new PasswordFactory();
646 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
648 $password = $passwordFactory->newFromCiphertext( $row->user_password
);
649 } catch ( PasswordError
$e ) {
650 wfDebug( 'Invalid password hash found in database.' );
651 $password = PasswordFactory
::newInvalidPassword();
654 $newpassword = $passwordFactory->newFromCiphertext( $row->user_newpassword
);
655 } catch ( PasswordError
$e ) {
656 wfDebug( 'Invalid password hash found in database.' );
657 $newpassword = PasswordFactory
::newInvalidPassword();
659 if ( !$password instanceof InvalidPassword ||
!$newpassword instanceof InvalidPassword
662 // User exists. Steal it?
663 if ( !$options['steal'] ) {
667 $nopass = PasswordFactory
::newInvalidPassword()->toString();
672 'user_password' => $nopass,
673 'user_newpassword' => $nopass,
674 'user_newpass_time' => null,
676 array( 'user_id' => $user->getId() ),
679 $user->invalidateEmail();
680 $user->saveSettings();
683 SessionManager
::singleton()->preventSessionsForUser( $user->getName() );
691 * Get the username corresponding to a given user ID
692 * @param int $id User ID
693 * @return string|bool The corresponding username
695 public static function whoIs( $id ) {
696 return UserCache
::singleton()->getProp( $id, 'name' );
700 * Get the real name of a user given their user ID
702 * @param int $id User ID
703 * @return string|bool The corresponding user's real name
705 public static function whoIsReal( $id ) {
706 return UserCache
::singleton()->getProp( $id, 'real_name' );
710 * Get database id given a user name
711 * @param string $name Username
712 * @param integer $flags User::READ_* constant bitfield
713 * @return int|null The corresponding user's ID, or null if user is nonexistent
715 public static function idFromName( $name, $flags = self
::READ_NORMAL
) {
716 $nt = Title
::makeTitleSafe( NS_USER
, $name );
717 if ( is_null( $nt ) ) {
722 if ( !( $flags & self
::READ_LATEST
) && isset( self
::$idCacheByName[$name] ) ) {
723 return self
::$idCacheByName[$name];
726 $db = ( $flags & self
::READ_LATEST
)
727 ?
wfGetDB( DB_MASTER
)
728 : wfGetDB( DB_SLAVE
);
733 array( 'user_name' => $nt->getText() ),
737 if ( $s === false ) {
740 $result = $s->user_id
;
743 self
::$idCacheByName[$name] = $result;
745 if ( count( self
::$idCacheByName ) > 1000 ) {
746 self
::$idCacheByName = array();
753 * Reset the cache used in idFromName(). For use in tests.
755 public static function resetIdByNameCache() {
756 self
::$idCacheByName = array();
760 * Does the string match an anonymous IPv4 address?
762 * This function exists for username validation, in order to reject
763 * usernames which are similar in form to IP addresses. Strings such
764 * as 300.300.300.300 will return true because it looks like an IP
765 * address, despite not being strictly valid.
767 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
768 * address because the usemod software would "cloak" anonymous IP
769 * addresses like this, if we allowed accounts like this to be created
770 * new users could get the old edits of these anonymous users.
772 * @param string $name Name to match
775 public static function isIP( $name ) {
776 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
777 || IP
::isIPv6( $name );
781 * Is the input a valid username?
783 * Checks if the input is a valid username, we don't want an empty string,
784 * an IP address, anything that contains slashes (would mess up subpages),
785 * is longer than the maximum allowed username size or doesn't begin with
788 * @param string $name Name to match
791 public static function isValidUserName( $name ) {
792 global $wgContLang, $wgMaxNameChars;
795 || User
::isIP( $name )
796 ||
strpos( $name, '/' ) !== false
797 ||
strlen( $name ) > $wgMaxNameChars
798 ||
$name != $wgContLang->ucfirst( $name )
800 wfDebugLog( 'username', __METHOD__
.
801 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
805 // Ensure that the name can't be misresolved as a different title,
806 // such as with extra namespace keys at the start.
807 $parsed = Title
::newFromText( $name );
808 if ( is_null( $parsed )
809 ||
$parsed->getNamespace()
810 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
811 wfDebugLog( 'username', __METHOD__
.
812 ": '$name' invalid due to ambiguous prefixes" );
816 // Check an additional blacklist of troublemaker characters.
817 // Should these be merged into the title char list?
818 $unicodeBlacklist = '/[' .
819 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
820 '\x{00a0}' . # non-breaking space
821 '\x{2000}-\x{200f}' . # various whitespace
822 '\x{2028}-\x{202f}' . # breaks and control chars
823 '\x{3000}' . # ideographic space
824 '\x{e000}-\x{f8ff}' . # private use
826 if ( preg_match( $unicodeBlacklist, $name ) ) {
827 wfDebugLog( 'username', __METHOD__
.
828 ": '$name' invalid due to blacklisted characters" );
836 * Usernames which fail to pass this function will be blocked
837 * from user login and new account registrations, but may be used
838 * internally by batch processes.
840 * If an account already exists in this form, login will be blocked
841 * by a failure to pass this function.
843 * @param string $name Name to match
846 public static function isUsableName( $name ) {
847 global $wgReservedUsernames;
848 // Must be a valid username, obviously ;)
849 if ( !self
::isValidUserName( $name ) ) {
853 static $reservedUsernames = false;
854 if ( !$reservedUsernames ) {
855 $reservedUsernames = $wgReservedUsernames;
856 Hooks
::run( 'UserGetReservedNames', array( &$reservedUsernames ) );
859 // Certain names may be reserved for batch processes.
860 foreach ( $reservedUsernames as $reserved ) {
861 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
862 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
864 if ( $reserved == $name ) {
872 * Usernames which fail to pass this function will be blocked
873 * from new account registrations, but may be used internally
874 * either by batch processes or by user accounts which have
875 * already been created.
877 * Additional blacklisting may be added here rather than in
878 * isValidUserName() to avoid disrupting existing accounts.
880 * @param string $name String to match
883 public static function isCreatableName( $name ) {
884 global $wgInvalidUsernameCharacters;
886 // Ensure that the username isn't longer than 235 bytes, so that
887 // (at least for the builtin skins) user javascript and css files
888 // will work. (bug 23080)
889 if ( strlen( $name ) > 235 ) {
890 wfDebugLog( 'username', __METHOD__
.
891 ": '$name' invalid due to length" );
895 // Preg yells if you try to give it an empty string
896 if ( $wgInvalidUsernameCharacters !== '' ) {
897 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
898 wfDebugLog( 'username', __METHOD__
.
899 ": '$name' invalid due to wgInvalidUsernameCharacters" );
904 return self
::isUsableName( $name );
908 * Is the input a valid password for this user?
910 * @param string $password Desired password
913 public function isValidPassword( $password ) {
914 // simple boolean wrapper for getPasswordValidity
915 return $this->getPasswordValidity( $password ) === true;
919 * Given unvalidated password input, return error message on failure.
921 * @param string $password Desired password
922 * @return bool|string|array True on success, string or array of error message on failure
924 public function getPasswordValidity( $password ) {
925 $result = $this->checkPasswordValidity( $password );
926 if ( $result->isGood() ) {
930 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
931 $messages[] = $error['message'];
933 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
934 $messages[] = $warning['message'];
936 if ( count( $messages ) === 1 ) {
944 * Check if this is a valid password for this user
946 * Create a Status object based on the password's validity.
947 * The Status should be set to fatal if the user should not
948 * be allowed to log in, and should have any errors that
949 * would block changing the password.
951 * If the return value of this is not OK, the password
952 * should not be checked. If the return value is not Good,
953 * the password can be checked, but the user should not be
954 * able to set their password to this.
956 * @param string $password Desired password
957 * @param string $purpose one of 'login', 'create', 'reset'
961 public function checkPasswordValidity( $password, $purpose = 'login' ) {
962 global $wgPasswordPolicy;
964 $upp = new UserPasswordPolicy(
965 $wgPasswordPolicy['policies'],
966 $wgPasswordPolicy['checks']
969 $status = Status
::newGood();
970 $result = false; // init $result to false for the internal checks
972 if ( !Hooks
::run( 'isValidPassword', array( $password, &$result, $this ) ) ) {
973 $status->error( $result );
977 if ( $result === false ) {
978 $status->merge( $upp->checkUserPassword( $this, $password, $purpose ) );
980 } elseif ( $result === true ) {
983 $status->error( $result );
984 return $status; // the isValidPassword hook set a string $result and returned true
989 * Given unvalidated user input, return a canonical username, or false if
990 * the username is invalid.
991 * @param string $name User input
992 * @param string|bool $validate Type of validation to use:
993 * - false No validation
994 * - 'valid' Valid for batch processes
995 * - 'usable' Valid for batch processes and login
996 * - 'creatable' Valid for batch processes, login and account creation
998 * @throws InvalidArgumentException
999 * @return bool|string
1001 public static function getCanonicalName( $name, $validate = 'valid' ) {
1002 // Force usernames to capital
1004 $name = $wgContLang->ucfirst( $name );
1006 # Reject names containing '#'; these will be cleaned up
1007 # with title normalisation, but then it's too late to
1009 if ( strpos( $name, '#' ) !== false ) {
1013 // Clean up name according to title rules,
1014 // but only when validation is requested (bug 12654)
1015 $t = ( $validate !== false ) ?
1016 Title
::newFromText( $name ) : Title
::makeTitle( NS_USER
, $name );
1017 // Check for invalid titles
1018 if ( is_null( $t ) ) {
1022 // Reject various classes of invalid names
1024 $name = $wgAuth->getCanonicalName( $t->getText() );
1026 switch ( $validate ) {
1030 if ( !User
::isValidUserName( $name ) ) {
1035 if ( !User
::isUsableName( $name ) ) {
1040 if ( !User
::isCreatableName( $name ) ) {
1045 throw new InvalidArgumentException(
1046 'Invalid parameter value for $validate in ' . __METHOD__
);
1052 * Count the number of edits of a user
1054 * @param int $uid User ID to check
1055 * @return int The user's edit count
1057 * @deprecated since 1.21 in favour of User::getEditCount
1059 public static function edits( $uid ) {
1060 wfDeprecated( __METHOD__
, '1.21' );
1061 $user = self
::newFromId( $uid );
1062 return $user->getEditCount();
1066 * Return a random password.
1068 * @deprecated since 1.27, use PasswordFactory::generateRandomPasswordString()
1069 * @return string New random password
1071 public static function randomPassword() {
1072 global $wgMinimalPasswordLength;
1073 return PasswordFactory
::generateRandomPasswordString( $wgMinimalPasswordLength );
1077 * Set cached properties to default.
1079 * @note This no longer clears uncached lazy-initialised properties;
1080 * the constructor does that instead.
1082 * @param string|bool $name
1084 public function loadDefaults( $name = false ) {
1086 $this->mName
= $name;
1087 $this->mRealName
= '';
1089 $this->mOptionOverrides
= null;
1090 $this->mOptionsLoaded
= false;
1092 $loggedOut = $this->mRequest ?
$this->mRequest
->getSession()->getLoggedOutTimestamp() : 0;
1093 if ( $loggedOut !== 0 ) {
1094 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1096 $this->mTouched
= '1'; # Allow any pages to be cached
1099 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1100 $this->mEmailAuthenticated
= null;
1101 $this->mEmailToken
= '';
1102 $this->mEmailTokenExpires
= null;
1103 $this->mRegistration
= wfTimestamp( TS_MW
);
1104 $this->mGroups
= array();
1106 Hooks
::run( 'UserLoadDefaults', array( $this, $name ) );
1110 * Return whether an item has been loaded.
1112 * @param string $item Item to check. Current possibilities:
1116 * @param string $all 'all' to check if the whole object has been loaded
1117 * or any other string to check if only the item is available (e.g.
1121 public function isItemLoaded( $item, $all = 'all' ) {
1122 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1123 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1127 * Set that an item has been loaded
1129 * @param string $item
1131 protected function setItemLoaded( $item ) {
1132 if ( is_array( $this->mLoadedItems
) ) {
1133 $this->mLoadedItems
[$item] = true;
1138 * Load user data from the session.
1140 * @return bool True if the user is logged in, false otherwise.
1142 private function loadFromSession() {
1145 Hooks
::run( 'UserLoadFromSession', array( $this, &$result ), '1.27' );
1146 if ( $result !== null ) {
1150 // MediaWiki\Session\Session already did the necessary authentication of the user
1151 // returned here, so just use it if applicable.
1152 $session = $this->getRequest()->getSession();
1153 $user = $session->getUser();
1154 if ( $user->isLoggedIn() ) {
1155 $this->loadFromUserObject( $user );
1156 // Other code expects these to be set in the session, so set them.
1157 $session->set( 'wsUserID', $this->getId() );
1158 $session->set( 'wsUserName', $this->getName() );
1159 $session->set( 'wsToken', $this->mToken
);
1167 * Load user and user_group data from the database.
1168 * $this->mId must be set, this is how the user is identified.
1170 * @param integer $flags User::READ_* constant bitfield
1171 * @return bool True if the user exists, false if the user is anonymous
1173 public function loadFromDatabase( $flags = self
::READ_LATEST
) {
1175 $this->mId
= intval( $this->mId
);
1178 if ( !$this->mId
) {
1179 $this->loadDefaults();
1183 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
1184 $db = wfGetDB( $index );
1186 $s = $db->selectRow(
1188 self
::selectFields(),
1189 array( 'user_id' => $this->mId
),
1194 $this->queryFlagsUsed
= $flags;
1195 Hooks
::run( 'UserLoadFromDatabase', array( $this, &$s ) );
1197 if ( $s !== false ) {
1198 // Initialise user table data
1199 $this->loadFromRow( $s );
1200 $this->mGroups
= null; // deferred
1201 $this->getEditCount(); // revalidation for nulls
1206 $this->loadDefaults();
1212 * Initialize this object from a row from the user table.
1214 * @param stdClass $row Row from the user table to load.
1215 * @param array $data Further user data to load into the object
1217 * user_groups Array with groups out of the user_groups table
1218 * user_properties Array with properties out of the user_properties table
1220 protected function loadFromRow( $row, $data = null ) {
1223 $this->mGroups
= null; // deferred
1225 if ( isset( $row->user_name
) ) {
1226 $this->mName
= $row->user_name
;
1227 $this->mFrom
= 'name';
1228 $this->setItemLoaded( 'name' );
1233 if ( isset( $row->user_real_name
) ) {
1234 $this->mRealName
= $row->user_real_name
;
1235 $this->setItemLoaded( 'realname' );
1240 if ( isset( $row->user_id
) ) {
1241 $this->mId
= intval( $row->user_id
);
1242 $this->mFrom
= 'id';
1243 $this->setItemLoaded( 'id' );
1248 if ( isset( $row->user_id
) && isset( $row->user_name
) ) {
1249 self
::$idCacheByName[$row->user_name
] = $row->user_id
;
1252 if ( isset( $row->user_editcount
) ) {
1253 $this->mEditCount
= $row->user_editcount
;
1258 if ( isset( $row->user_touched
) ) {
1259 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1264 if ( isset( $row->user_email
) ) {
1265 $this->mEmail
= $row->user_email
;
1266 $this->mToken
= $row->user_token
;
1267 if ( $this->mToken
== '' ) {
1268 $this->mToken
= null;
1270 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1271 $this->mEmailToken
= $row->user_email_token
;
1272 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1273 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1279 $this->mLoadedItems
= true;
1282 if ( is_array( $data ) ) {
1283 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1284 $this->mGroups
= $data['user_groups'];
1286 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1287 $this->loadOptions( $data['user_properties'] );
1293 * Load the data for this user object from another user object.
1297 protected function loadFromUserObject( $user ) {
1299 $user->loadGroups();
1300 $user->loadOptions();
1301 foreach ( self
::$mCacheVars as $var ) {
1302 $this->$var = $user->$var;
1307 * Load the groups from the database if they aren't already loaded.
1309 private function loadGroups() {
1310 if ( is_null( $this->mGroups
) ) {
1311 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
1312 ?
wfGetDB( DB_MASTER
)
1313 : wfGetDB( DB_SLAVE
);
1314 $res = $db->select( 'user_groups',
1315 array( 'ug_group' ),
1316 array( 'ug_user' => $this->mId
),
1318 $this->mGroups
= array();
1319 foreach ( $res as $row ) {
1320 $this->mGroups
[] = $row->ug_group
;
1326 * Add the user to the group if he/she meets given criteria.
1328 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1329 * possible to remove manually via Special:UserRights. In such case it
1330 * will not be re-added automatically. The user will also not lose the
1331 * group if they no longer meet the criteria.
1333 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1335 * @return array Array of groups the user has been promoted to.
1337 * @see $wgAutopromoteOnce
1339 public function addAutopromoteOnceGroups( $event ) {
1340 global $wgAutopromoteOnceLogInRC, $wgAuth;
1342 if ( wfReadOnly() ||
!$this->getId() ) {
1346 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1347 if ( !count( $toPromote ) ) {
1351 if ( !$this->checkAndSetTouched() ) {
1352 return array(); // raced out (bug T48834)
1355 $oldGroups = $this->getGroups(); // previous groups
1356 foreach ( $toPromote as $group ) {
1357 $this->addGroup( $group );
1359 // update groups in external authentication database
1360 Hooks
::run( 'UserGroupsChanged', array( $this, $toPromote, array(), false ) );
1361 $wgAuth->updateExternalDBGroups( $this, $toPromote );
1363 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1365 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1366 $logEntry->setPerformer( $this );
1367 $logEntry->setTarget( $this->getUserPage() );
1368 $logEntry->setParameters( array(
1369 '4::oldgroups' => $oldGroups,
1370 '5::newgroups' => $newGroups,
1372 $logid = $logEntry->insert();
1373 if ( $wgAutopromoteOnceLogInRC ) {
1374 $logEntry->publish( $logid );
1381 * Bump user_touched if it didn't change since this object was loaded
1383 * On success, the mTouched field is updated.
1384 * The user serialization cache is always cleared.
1386 * @return bool Whether user_touched was actually updated
1389 protected function checkAndSetTouched() {
1392 if ( !$this->mId
) {
1393 return false; // anon
1396 // Get a new user_touched that is higher than the old one
1397 $oldTouched = $this->mTouched
;
1398 $newTouched = $this->newTouchedTimestamp();
1400 $dbw = wfGetDB( DB_MASTER
);
1401 $dbw->update( 'user',
1402 array( 'user_touched' => $dbw->timestamp( $newTouched ) ),
1404 'user_id' => $this->mId
,
1405 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
1409 $success = ( $dbw->affectedRows() > 0 );
1412 $this->mTouched
= $newTouched;
1413 $this->clearSharedCache();
1415 // Clears on failure too since that is desired if the cache is stale
1416 $this->clearSharedCache( 'refresh' );
1423 * Clear various cached data stored in this object. The cache of the user table
1424 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1426 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1427 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1429 public function clearInstanceCache( $reloadFrom = false ) {
1430 $this->mNewtalk
= -1;
1431 $this->mDatePreference
= null;
1432 $this->mBlockedby
= -1; # Unset
1433 $this->mHash
= false;
1434 $this->mRights
= null;
1435 $this->mEffectiveGroups
= null;
1436 $this->mImplicitGroups
= null;
1437 $this->mGroups
= null;
1438 $this->mOptions
= null;
1439 $this->mOptionsLoaded
= false;
1440 $this->mEditCount
= null;
1442 if ( $reloadFrom ) {
1443 $this->mLoadedItems
= array();
1444 $this->mFrom
= $reloadFrom;
1449 * Combine the language default options with any site-specific options
1450 * and add the default language variants.
1452 * @return array Array of String options
1454 public static function getDefaultOptions() {
1455 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1457 static $defOpt = null;
1458 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1459 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1460 // mid-request and see that change reflected in the return value of this function.
1461 // Which is insane and would never happen during normal MW operation
1465 $defOpt = $wgDefaultUserOptions;
1466 // Default language setting
1467 $defOpt['language'] = $wgContLang->getCode();
1468 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1469 $defOpt[$langCode == $wgContLang->getCode() ?
'variant' : "variant-$langCode"] = $langCode;
1471 foreach ( SearchEngine
::searchableNamespaces() as $nsnum => $nsname ) {
1472 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1474 $defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1476 Hooks
::run( 'UserGetDefaultOptions', array( &$defOpt ) );
1482 * Get a given default option value.
1484 * @param string $opt Name of option to retrieve
1485 * @return string Default option value
1487 public static function getDefaultOption( $opt ) {
1488 $defOpts = self
::getDefaultOptions();
1489 if ( isset( $defOpts[$opt] ) ) {
1490 return $defOpts[$opt];
1497 * Get blocking information
1498 * @param bool $bFromSlave Whether to check the slave database first.
1499 * To improve performance, non-critical checks are done against slaves.
1500 * Check when actually saving should be done against master.
1502 private function getBlockedStatus( $bFromSlave = true ) {
1503 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1505 if ( -1 != $this->mBlockedby
) {
1509 wfDebug( __METHOD__
. ": checking...\n" );
1511 // Initialize data...
1512 // Otherwise something ends up stomping on $this->mBlockedby when
1513 // things get lazy-loaded later, causing false positive block hits
1514 // due to -1 !== 0. Probably session-related... Nothing should be
1515 // overwriting mBlockedby, surely?
1518 # We only need to worry about passing the IP address to the Block generator if the
1519 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1520 # know which IP address they're actually coming from
1521 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->equals( $wgUser ) ) {
1522 $ip = $this->getRequest()->getIP();
1528 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1531 if ( !$block instanceof Block
&& $ip !== null && !in_array( $ip, $wgProxyWhitelist ) ) {
1533 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1535 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1536 $block->mReason
= wfMessage( 'proxyblockreason' )->text();
1537 $block->setTarget( $ip );
1538 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1540 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1541 $block->mReason
= wfMessage( 'sorbsreason' )->text();
1542 $block->setTarget( $ip );
1546 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1547 if ( !$block instanceof Block
1548 && $wgApplyIpBlocksToXff
1550 && !in_array( $ip, $wgProxyWhitelist )
1552 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1553 $xff = array_map( 'trim', explode( ',', $xff ) );
1554 $xff = array_diff( $xff, array( $ip ) );
1555 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1556 $block = Block
::chooseBlock( $xffblocks, $xff );
1557 if ( $block instanceof Block
) {
1558 # Mangle the reason to alert the user that the block
1559 # originated from matching the X-Forwarded-For header.
1560 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->text();
1564 if ( $block instanceof Block
) {
1565 wfDebug( __METHOD__
. ": Found block.\n" );
1566 $this->mBlock
= $block;
1567 $this->mBlockedby
= $block->getByName();
1568 $this->mBlockreason
= $block->mReason
;
1569 $this->mHideName
= $block->mHideName
;
1570 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1572 $this->mBlockedby
= '';
1573 $this->mHideName
= 0;
1574 $this->mAllowUsertalk
= false;
1578 Hooks
::run( 'GetBlockedStatus', array( &$this ) );
1583 * Whether the given IP is in a DNS blacklist.
1585 * @param string $ip IP to check
1586 * @param bool $checkWhitelist Whether to check the whitelist first
1587 * @return bool True if blacklisted.
1589 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1590 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1592 if ( !$wgEnableDnsBlacklist ) {
1596 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1600 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1604 * Whether the given IP is in a given DNS blacklist.
1606 * @param string $ip IP to check
1607 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1608 * @return bool True if blacklisted.
1610 public function inDnsBlacklist( $ip, $bases ) {
1613 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1614 if ( IP
::isIPv4( $ip ) ) {
1615 // Reverse IP, bug 21255
1616 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1618 foreach ( (array)$bases as $base ) {
1620 // If we have an access key, use that too (ProjectHoneypot, etc.)
1622 if ( is_array( $base ) ) {
1623 if ( count( $base ) >= 2 ) {
1624 // Access key is 1, base URL is 0
1625 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1627 $host = "$ipReversed.{$base[0]}";
1629 $basename = $base[0];
1631 $host = "$ipReversed.$base";
1635 $ipList = gethostbynamel( $host );
1638 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
1642 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
1651 * Check if an IP address is in the local proxy list
1657 public static function isLocallyBlockedProxy( $ip ) {
1658 global $wgProxyList;
1660 if ( !$wgProxyList ) {
1664 if ( !is_array( $wgProxyList ) ) {
1665 // Load from the specified file
1666 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1669 if ( !is_array( $wgProxyList ) ) {
1671 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1673 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1674 // Old-style flipped proxy list
1683 * Is this user subject to rate limiting?
1685 * @return bool True if rate limited
1687 public function isPingLimitable() {
1688 global $wgRateLimitsExcludedIPs;
1689 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1690 // No other good way currently to disable rate limits
1691 // for specific IPs. :P
1692 // But this is a crappy hack and should die.
1695 return !$this->isAllowed( 'noratelimit' );
1699 * Primitive rate limits: enforce maximum actions per time period
1700 * to put a brake on flooding.
1702 * The method generates both a generic profiling point and a per action one
1703 * (suffix being "-$action".
1705 * @note When using a shared cache like memcached, IP-address
1706 * last-hit counters will be shared across wikis.
1708 * @param string $action Action to enforce; 'edit' if unspecified
1709 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1710 * @return bool True if a rate limiter was tripped
1712 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1713 // Call the 'PingLimiter' hook
1715 if ( !Hooks
::run( 'PingLimiter', array( &$this, $action, &$result, $incrBy ) ) ) {
1719 global $wgRateLimits;
1720 if ( !isset( $wgRateLimits[$action] ) ) {
1724 // Some groups shouldn't trigger the ping limiter, ever
1725 if ( !$this->isPingLimitable() ) {
1729 $limits = $wgRateLimits[$action];
1731 $id = $this->getId();
1734 if ( isset( $limits['anon'] ) && $id == 0 ) {
1735 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1738 if ( isset( $limits['user'] ) && $id != 0 ) {
1739 $userLimit = $limits['user'];
1741 if ( $this->isNewbie() ) {
1742 if ( isset( $limits['newbie'] ) && $id != 0 ) {
1743 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1745 if ( isset( $limits['ip'] ) ) {
1746 $ip = $this->getRequest()->getIP();
1747 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1749 if ( isset( $limits['subnet'] ) ) {
1750 $ip = $this->getRequest()->getIP();
1753 if ( IP
::isIPv6( $ip ) ) {
1754 $parts = IP
::parseRange( "$ip/64" );
1755 $subnet = $parts[0];
1756 } elseif ( preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1758 $subnet = $matches[1];
1760 if ( $subnet !== false ) {
1761 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1765 // Check for group-specific permissions
1766 // If more than one group applies, use the group with the highest limit
1767 foreach ( $this->getGroups() as $group ) {
1768 if ( isset( $limits[$group] ) ) {
1769 if ( $userLimit === false
1770 ||
$limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1772 $userLimit = $limits[$group];
1776 // Set the user limit key
1777 if ( $userLimit !== false ) {
1778 list( $max, $period ) = $userLimit;
1779 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
1780 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1783 $cache = ObjectCache
::getLocalClusterInstance();
1786 foreach ( $keys as $key => $limit ) {
1787 list( $max, $period ) = $limit;
1788 $summary = "(limit $max in {$period}s)";
1789 $count = $cache->get( $key );
1792 if ( $count >= $max ) {
1793 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1794 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1797 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1800 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1801 if ( $incrBy > 0 ) {
1802 $cache->add( $key, 0, intval( $period ) ); // first ping
1805 if ( $incrBy > 0 ) {
1806 $cache->incr( $key, $incrBy );
1814 * Check if user is blocked
1816 * @param bool $bFromSlave Whether to check the slave database instead of
1817 * the master. Hacked from false due to horrible probs on site.
1818 * @return bool True if blocked, false otherwise
1820 public function isBlocked( $bFromSlave = true ) {
1821 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
1825 * Get the block affecting the user, or null if the user is not blocked
1827 * @param bool $bFromSlave Whether to check the slave database instead of the master
1828 * @return Block|null
1830 public function getBlock( $bFromSlave = true ) {
1831 $this->getBlockedStatus( $bFromSlave );
1832 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
1836 * Check if user is blocked from editing a particular article
1838 * @param Title $title Title to check
1839 * @param bool $bFromSlave Whether to check the slave database instead of the master
1842 public function isBlockedFrom( $title, $bFromSlave = false ) {
1843 global $wgBlockAllowsUTEdit;
1845 $blocked = $this->isBlocked( $bFromSlave );
1846 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
1847 // If a user's name is suppressed, they cannot make edits anywhere
1848 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName()
1849 && $title->getNamespace() == NS_USER_TALK
) {
1851 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
1854 Hooks
::run( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1860 * If user is blocked, return the name of the user who placed the block
1861 * @return string Name of blocker
1863 public function blockedBy() {
1864 $this->getBlockedStatus();
1865 return $this->mBlockedby
;
1869 * If user is blocked, return the specified reason for the block
1870 * @return string Blocking reason
1872 public function blockedFor() {
1873 $this->getBlockedStatus();
1874 return $this->mBlockreason
;
1878 * If user is blocked, return the ID for the block
1879 * @return int Block ID
1881 public function getBlockId() {
1882 $this->getBlockedStatus();
1883 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
1887 * Check if user is blocked on all wikis.
1888 * Do not use for actual edit permission checks!
1889 * This is intended for quick UI checks.
1891 * @param string $ip IP address, uses current client if none given
1892 * @return bool True if blocked, false otherwise
1894 public function isBlockedGlobally( $ip = '' ) {
1895 if ( $this->mBlockedGlobally
!== null ) {
1896 return $this->mBlockedGlobally
;
1898 // User is already an IP?
1899 if ( IP
::isIPAddress( $this->getName() ) ) {
1900 $ip = $this->getName();
1902 $ip = $this->getRequest()->getIP();
1905 Hooks
::run( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1906 $this->mBlockedGlobally
= (bool)$blocked;
1907 return $this->mBlockedGlobally
;
1911 * Check if user account is locked
1913 * @return bool True if locked, false otherwise
1915 public function isLocked() {
1916 if ( $this->mLocked
!== null ) {
1917 return $this->mLocked
;
1920 $authUser = $wgAuth->getUserInstance( $this );
1921 $this->mLocked
= (bool)$authUser->isLocked();
1922 Hooks
::run( 'UserIsLocked', array( $this, &$this->mLocked
) );
1923 return $this->mLocked
;
1927 * Check if user account is hidden
1929 * @return bool True if hidden, false otherwise
1931 public function isHidden() {
1932 if ( $this->mHideName
!== null ) {
1933 return $this->mHideName
;
1935 $this->getBlockedStatus();
1936 if ( !$this->mHideName
) {
1938 $authUser = $wgAuth->getUserInstance( $this );
1939 $this->mHideName
= (bool)$authUser->isHidden();
1940 Hooks
::run( 'UserIsHidden', array( $this, &$this->mHideName
) );
1942 return $this->mHideName
;
1946 * Get the user's ID.
1947 * @return int The user's ID; 0 if the user is anonymous or nonexistent
1949 public function getId() {
1950 if ( $this->mId
=== null && $this->mName
!== null && User
::isIP( $this->mName
) ) {
1951 // Special case, we know the user is anonymous
1953 } elseif ( !$this->isItemLoaded( 'id' ) ) {
1954 // Don't load if this was initialized from an ID
1961 * Set the user and reload all fields according to a given ID
1962 * @param int $v User ID to reload
1964 public function setId( $v ) {
1966 $this->clearInstanceCache( 'id' );
1970 * Get the user name, or the IP of an anonymous user
1971 * @return string User's name or IP address
1973 public function getName() {
1974 if ( $this->isItemLoaded( 'name', 'only' ) ) {
1975 // Special case optimisation
1976 return $this->mName
;
1979 if ( $this->mName
=== false ) {
1981 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
1983 return $this->mName
;
1988 * Set the user name.
1990 * This does not reload fields from the database according to the given
1991 * name. Rather, it is used to create a temporary "nonexistent user" for
1992 * later addition to the database. It can also be used to set the IP
1993 * address for an anonymous user to something other than the current
1996 * @note User::newFromName() has roughly the same function, when the named user
1998 * @param string $str New user name to set
2000 public function setName( $str ) {
2002 $this->mName
= $str;
2006 * Get the user's name escaped by underscores.
2007 * @return string Username escaped by underscores.
2009 public function getTitleKey() {
2010 return str_replace( ' ', '_', $this->getName() );
2014 * Check if the user has new messages.
2015 * @return bool True if the user has new messages
2017 public function getNewtalk() {
2020 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2021 if ( $this->mNewtalk
=== -1 ) {
2022 $this->mNewtalk
= false; # reset talk page status
2024 // Check memcached separately for anons, who have no
2025 // entire User object stored in there.
2026 if ( !$this->mId
) {
2027 global $wgDisableAnonTalk;
2028 if ( $wgDisableAnonTalk ) {
2029 // Anon newtalk disabled by configuration.
2030 $this->mNewtalk
= false;
2032 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
2035 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2039 return (bool)$this->mNewtalk
;
2043 * Return the data needed to construct links for new talk page message
2044 * alerts. If there are new messages, this will return an associative array
2045 * with the following data:
2046 * wiki: The database name of the wiki
2047 * link: Root-relative link to the user's talk page
2048 * rev: The last talk page revision that the user has seen or null. This
2049 * is useful for building diff links.
2050 * If there are no new messages, it returns an empty array.
2051 * @note This function was designed to accomodate multiple talk pages, but
2052 * currently only returns a single link and revision.
2055 public function getNewMessageLinks() {
2057 if ( !Hooks
::run( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) ) {
2059 } elseif ( !$this->getNewtalk() ) {
2062 $utp = $this->getTalkPage();
2063 $dbr = wfGetDB( DB_SLAVE
);
2064 // Get the "last viewed rev" timestamp from the oldest message notification
2065 $timestamp = $dbr->selectField( 'user_newtalk',
2066 'MIN(user_last_timestamp)',
2067 $this->isAnon() ?
array( 'user_ip' => $this->getName() ) : array( 'user_id' => $this->getID() ),
2069 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2070 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ) );
2074 * Get the revision ID for the last talk page revision viewed by the talk
2076 * @return int|null Revision ID or null
2078 public function getNewMessageRevisionId() {
2079 $newMessageRevisionId = null;
2080 $newMessageLinks = $this->getNewMessageLinks();
2081 if ( $newMessageLinks ) {
2082 // Note: getNewMessageLinks() never returns more than a single link
2083 // and it is always for the same wiki, but we double-check here in
2084 // case that changes some time in the future.
2085 if ( count( $newMessageLinks ) === 1
2086 && $newMessageLinks[0]['wiki'] === wfWikiID()
2087 && $newMessageLinks[0]['rev']
2089 /** @var Revision $newMessageRevision */
2090 $newMessageRevision = $newMessageLinks[0]['rev'];
2091 $newMessageRevisionId = $newMessageRevision->getId();
2094 return $newMessageRevisionId;
2098 * Internal uncached check for new messages
2101 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2102 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2103 * @return bool True if the user has new messages
2105 protected function checkNewtalk( $field, $id ) {
2106 $dbr = wfGetDB( DB_SLAVE
);
2108 $ok = $dbr->selectField( 'user_newtalk', $field, array( $field => $id ), __METHOD__
);
2110 return $ok !== false;
2114 * Add or update the new messages flag
2115 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2116 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2117 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2118 * @return bool True if successful, false otherwise
2120 protected function updateNewtalk( $field, $id, $curRev = null ) {
2121 // Get timestamp of the talk page revision prior to the current one
2122 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2123 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2124 // Mark the user as having new messages since this revision
2125 $dbw = wfGetDB( DB_MASTER
);
2126 $dbw->insert( 'user_newtalk',
2127 array( $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ),
2130 if ( $dbw->affectedRows() ) {
2131 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2134 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2140 * Clear the new messages flag for the given user
2141 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2142 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2143 * @return bool True if successful, false otherwise
2145 protected function deleteNewtalk( $field, $id ) {
2146 $dbw = wfGetDB( DB_MASTER
);
2147 $dbw->delete( 'user_newtalk',
2148 array( $field => $id ),
2150 if ( $dbw->affectedRows() ) {
2151 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2154 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2160 * Update the 'You have new messages!' status.
2161 * @param bool $val Whether the user has new messages
2162 * @param Revision $curRev New, as yet unseen revision of the user talk
2163 * page. Ignored if null or !$val.
2165 public function setNewtalk( $val, $curRev = null ) {
2166 if ( wfReadOnly() ) {
2171 $this->mNewtalk
= $val;
2173 if ( $this->isAnon() ) {
2175 $id = $this->getName();
2178 $id = $this->getId();
2182 $changed = $this->updateNewtalk( $field, $id, $curRev );
2184 $changed = $this->deleteNewtalk( $field, $id );
2188 $this->invalidateCache();
2193 * Generate a current or new-future timestamp to be stored in the
2194 * user_touched field when we update things.
2195 * @return string Timestamp in TS_MW format
2197 private function newTouchedTimestamp() {
2198 global $wgClockSkewFudge;
2200 $time = wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2201 if ( $this->mTouched
&& $time <= $this->mTouched
) {
2202 $time = wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $this->mTouched
) +
1 );
2209 * Clear user data from memcached
2211 * Use after applying updates to the database; caller's
2212 * responsibility to update user_touched if appropriate.
2214 * Called implicitly from invalidateCache() and saveSettings().
2216 * @param string $mode Use 'refresh' to clear now; otherwise before DB commit
2218 public function clearSharedCache( $mode = 'changed' ) {
2219 if ( !$this->getId() ) {
2223 $cache = ObjectCache
::getMainWANInstance();
2224 $key = $this->getCacheKey( $cache );
2225 if ( $mode === 'refresh' ) {
2226 $cache->delete( $key, 1 );
2228 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle( function() use ( $cache, $key ) {
2229 $cache->delete( $key );
2235 * Immediately touch the user data cache for this account
2237 * Calls touch() and removes account data from memcached
2239 public function invalidateCache() {
2241 $this->clearSharedCache();
2245 * Update the "touched" timestamp for the user
2247 * This is useful on various login/logout events when making sure that
2248 * a browser or proxy that has multiple tenants does not suffer cache
2249 * pollution where the new user sees the old users content. The value
2250 * of getTouched() is checked when determining 304 vs 200 responses.
2251 * Unlike invalidateCache(), this preserves the User object cache and
2252 * avoids database writes.
2256 public function touch() {
2257 $id = $this->getId();
2259 $key = wfMemcKey( 'user-quicktouched', 'id', $id );
2260 ObjectCache
::getMainWANInstance()->touchCheckKey( $key );
2261 $this->mQuickTouched
= null;
2266 * Validate the cache for this account.
2267 * @param string $timestamp A timestamp in TS_MW format
2270 public function validateCache( $timestamp ) {
2271 return ( $timestamp >= $this->getTouched() );
2275 * Get the user touched timestamp
2277 * Use this value only to validate caches via inequalities
2278 * such as in the case of HTTP If-Modified-Since response logic
2280 * @return string TS_MW Timestamp
2282 public function getTouched() {
2286 if ( $this->mQuickTouched
=== null ) {
2287 $key = wfMemcKey( 'user-quicktouched', 'id', $this->mId
);
2288 $cache = ObjectCache
::getMainWANInstance();
2290 $this->mQuickTouched
= wfTimestamp( TS_MW
, $cache->getCheckKeyTime( $key ) );
2293 return max( $this->mTouched
, $this->mQuickTouched
);
2296 return $this->mTouched
;
2300 * Get the user_touched timestamp field (time of last DB updates)
2301 * @return string TS_MW Timestamp
2304 public function getDBTouched() {
2307 return $this->mTouched
;
2311 * @deprecated Removed in 1.27.
2315 public function getPassword() {
2316 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2320 * @deprecated Removed in 1.27.
2324 public function getTemporaryPassword() {
2325 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2329 * Set the password and reset the random token.
2330 * Calls through to authentication plugin if necessary;
2331 * will have no effect if the auth plugin refuses to
2332 * pass the change through or if the legal password
2335 * As a special case, setting the password to null
2336 * wipes it, so the account cannot be logged in until
2337 * a new password is set, for instance via e-mail.
2339 * @deprecated since 1.27. AuthManager is coming.
2340 * @param string $str New password to set
2341 * @throws PasswordError On failure
2344 public function setPassword( $str ) {
2347 if ( $str !== null ) {
2348 if ( !$wgAuth->allowPasswordChange() ) {
2349 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2352 $status = $this->checkPasswordValidity( $str );
2353 if ( !$status->isGood() ) {
2354 throw new PasswordError( $status->getMessage()->text() );
2358 if ( !$wgAuth->setPassword( $this, $str ) ) {
2359 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2363 $this->setOption( 'watchlisttoken', false );
2364 $this->setPasswordInternal( $str );
2370 * Set the password and reset the random token unconditionally.
2372 * @deprecated since 1.27. AuthManager is coming.
2373 * @param string|null $str New password to set or null to set an invalid
2374 * password hash meaning that the user will not be able to log in
2375 * through the web interface.
2377 public function setInternalPassword( $str ) {
2380 if ( $wgAuth->allowSetLocalPassword() ) {
2382 $this->setOption( 'watchlisttoken', false );
2383 $this->setPasswordInternal( $str );
2388 * Actually set the password and such
2389 * @since 1.27 cannot set a password for a user not in the database
2390 * @param string|null $str New password to set or null to set an invalid
2391 * password hash meaning that the user will not be able to log in
2392 * through the web interface.
2394 private function setPasswordInternal( $str ) {
2395 $id = self
::idFromName( $this->getName(), self
::READ_LATEST
);
2397 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2400 $passwordFactory = new PasswordFactory();
2401 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
2402 $dbw = wfGetDB( DB_MASTER
);
2406 'user_password' => $passwordFactory->newFromPlaintext( $str )->toString(),
2407 'user_newpassword' => PasswordFactory
::newInvalidPassword()->toString(),
2408 'user_newpass_time' => $dbw->timestampOrNull( null ),
2416 // When the main password is changed, invalidate all bot passwords too
2417 BotPassword
::invalidateAllPasswordsForUser( $this->getName() );
2421 * Get the user's current token.
2422 * @param bool $forceCreation Force the generation of a new token if the
2423 * user doesn't have one (default=true for backwards compatibility).
2424 * @return string Token
2426 public function getToken( $forceCreation = true ) {
2428 if ( !$this->mToken
&& $forceCreation ) {
2431 return $this->mToken
;
2435 * Set the random token (used for persistent authentication)
2436 * Called from loadDefaults() among other places.
2438 * @param string|bool $token If specified, set the token to this value
2440 public function setToken( $token = false ) {
2443 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2445 $this->mToken
= $token;
2450 * Set the password for a password reminder or new account email
2452 * @deprecated since 1.27, AuthManager is coming
2453 * @param string $str New password to set or null to set an invalid
2454 * password hash meaning that the user will not be able to use it
2455 * @param bool $throttle If true, reset the throttle timestamp to the present
2457 public function setNewpassword( $str, $throttle = true ) {
2458 $id = $this->getId();
2460 throw new LogicException( 'Cannot set new password for a user that is not in the database.' );
2463 $dbw = wfGetDB( DB_MASTER
);
2465 $passwordFactory = new PasswordFactory();
2466 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
2468 'user_newpassword' => $passwordFactory->newFromPlaintext( $str )->toString(),
2471 if ( $str === null ) {
2472 $update['user_newpass_time'] = null;
2473 } elseif ( $throttle ) {
2474 $update['user_newpass_time'] = $dbw->timestamp();
2477 $dbw->update( 'user', $update, array( 'user_id' => $id ), __METHOD__
);
2481 * Has password reminder email been sent within the last
2482 * $wgPasswordReminderResendTime hours?
2485 public function isPasswordReminderThrottled() {
2486 global $wgPasswordReminderResendTime;
2488 if ( !$wgPasswordReminderResendTime ) {
2494 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
2495 ?
wfGetDB( DB_MASTER
)
2496 : wfGetDB( DB_SLAVE
);
2497 $newpassTime = $db->selectField(
2499 'user_newpass_time',
2500 array( 'user_id' => $this->getId() ),
2504 if ( $newpassTime === null ) {
2507 $expiry = wfTimestamp( TS_UNIX
, $newpassTime ) +
$wgPasswordReminderResendTime * 3600;
2508 return time() < $expiry;
2512 * Get the user's e-mail address
2513 * @return string User's email address
2515 public function getEmail() {
2517 Hooks
::run( 'UserGetEmail', array( $this, &$this->mEmail
) );
2518 return $this->mEmail
;
2522 * Get the timestamp of the user's e-mail authentication
2523 * @return string TS_MW timestamp
2525 public function getEmailAuthenticationTimestamp() {
2527 Hooks
::run( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
2528 return $this->mEmailAuthenticated
;
2532 * Set the user's e-mail address
2533 * @param string $str New e-mail address
2535 public function setEmail( $str ) {
2537 if ( $str == $this->mEmail
) {
2540 $this->invalidateEmail();
2541 $this->mEmail
= $str;
2542 Hooks
::run( 'UserSetEmail', array( $this, &$this->mEmail
) );
2546 * Set the user's e-mail address and a confirmation mail if needed.
2549 * @param string $str New e-mail address
2552 public function setEmailWithConfirmation( $str ) {
2553 global $wgEnableEmail, $wgEmailAuthentication;
2555 if ( !$wgEnableEmail ) {
2556 return Status
::newFatal( 'emaildisabled' );
2559 $oldaddr = $this->getEmail();
2560 if ( $str === $oldaddr ) {
2561 return Status
::newGood( true );
2564 $this->setEmail( $str );
2566 if ( $str !== '' && $wgEmailAuthentication ) {
2567 // Send a confirmation request to the new address if needed
2568 $type = $oldaddr != '' ?
'changed' : 'set';
2569 $result = $this->sendConfirmationMail( $type );
2570 if ( $result->isGood() ) {
2571 // Say to the caller that a confirmation mail has been sent
2572 $result->value
= 'eauth';
2575 $result = Status
::newGood( true );
2582 * Get the user's real name
2583 * @return string User's real name
2585 public function getRealName() {
2586 if ( !$this->isItemLoaded( 'realname' ) ) {
2590 return $this->mRealName
;
2594 * Set the user's real name
2595 * @param string $str New real name
2597 public function setRealName( $str ) {
2599 $this->mRealName
= $str;
2603 * Get the user's current setting for a given option.
2605 * @param string $oname The option to check
2606 * @param string $defaultOverride A default value returned if the option does not exist
2607 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2608 * @return string User's current value for the option
2609 * @see getBoolOption()
2610 * @see getIntOption()
2612 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2613 global $wgHiddenPrefs;
2614 $this->loadOptions();
2616 # We want 'disabled' preferences to always behave as the default value for
2617 # users, even if they have set the option explicitly in their settings (ie they
2618 # set it, and then it was disabled removing their ability to change it). But
2619 # we don't want to erase the preferences in the database in case the preference
2620 # is re-enabled again. So don't touch $mOptions, just override the returned value
2621 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2622 return self
::getDefaultOption( $oname );
2625 if ( array_key_exists( $oname, $this->mOptions
) ) {
2626 return $this->mOptions
[$oname];
2628 return $defaultOverride;
2633 * Get all user's options
2635 * @param int $flags Bitwise combination of:
2636 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2637 * to the default value. (Since 1.25)
2640 public function getOptions( $flags = 0 ) {
2641 global $wgHiddenPrefs;
2642 $this->loadOptions();
2643 $options = $this->mOptions
;
2645 # We want 'disabled' preferences to always behave as the default value for
2646 # users, even if they have set the option explicitly in their settings (ie they
2647 # set it, and then it was disabled removing their ability to change it). But
2648 # we don't want to erase the preferences in the database in case the preference
2649 # is re-enabled again. So don't touch $mOptions, just override the returned value
2650 foreach ( $wgHiddenPrefs as $pref ) {
2651 $default = self
::getDefaultOption( $pref );
2652 if ( $default !== null ) {
2653 $options[$pref] = $default;
2657 if ( $flags & self
::GETOPTIONS_EXCLUDE_DEFAULTS
) {
2658 $options = array_diff_assoc( $options, self
::getDefaultOptions() );
2665 * Get the user's current setting for a given option, as a boolean value.
2667 * @param string $oname The option to check
2668 * @return bool User's current value for the option
2671 public function getBoolOption( $oname ) {
2672 return (bool)$this->getOption( $oname );
2676 * Get the user's current setting for a given option, as an integer value.
2678 * @param string $oname The option to check
2679 * @param int $defaultOverride A default value returned if the option does not exist
2680 * @return int User's current value for the option
2683 public function getIntOption( $oname, $defaultOverride = 0 ) {
2684 $val = $this->getOption( $oname );
2686 $val = $defaultOverride;
2688 return intval( $val );
2692 * Set the given option for a user.
2694 * You need to call saveSettings() to actually write to the database.
2696 * @param string $oname The option to set
2697 * @param mixed $val New value to set
2699 public function setOption( $oname, $val ) {
2700 $this->loadOptions();
2702 // Explicitly NULL values should refer to defaults
2703 if ( is_null( $val ) ) {
2704 $val = self
::getDefaultOption( $oname );
2707 $this->mOptions
[$oname] = $val;
2711 * Get a token stored in the preferences (like the watchlist one),
2712 * resetting it if it's empty (and saving changes).
2714 * @param string $oname The option name to retrieve the token from
2715 * @return string|bool User's current value for the option, or false if this option is disabled.
2716 * @see resetTokenFromOption()
2718 * @deprecated 1.26 Applications should use the OAuth extension
2720 public function getTokenFromOption( $oname ) {
2721 global $wgHiddenPrefs;
2723 $id = $this->getId();
2724 if ( !$id ||
in_array( $oname, $wgHiddenPrefs ) ) {
2728 $token = $this->getOption( $oname );
2730 // Default to a value based on the user token to avoid space
2731 // wasted on storing tokens for all users. When this option
2732 // is set manually by the user, only then is it stored.
2733 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
2740 * Reset a token stored in the preferences (like the watchlist one).
2741 * *Does not* save user's preferences (similarly to setOption()).
2743 * @param string $oname The option name to reset the token in
2744 * @return string|bool New token value, or false if this option is disabled.
2745 * @see getTokenFromOption()
2748 public function resetTokenFromOption( $oname ) {
2749 global $wgHiddenPrefs;
2750 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2754 $token = MWCryptRand
::generateHex( 40 );
2755 $this->setOption( $oname, $token );
2760 * Return a list of the types of user options currently returned by
2761 * User::getOptionKinds().
2763 * Currently, the option kinds are:
2764 * - 'registered' - preferences which are registered in core MediaWiki or
2765 * by extensions using the UserGetDefaultOptions hook.
2766 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2767 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2768 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2769 * be used by user scripts.
2770 * - 'special' - "preferences" that are not accessible via User::getOptions
2771 * or User::setOptions.
2772 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2773 * These are usually legacy options, removed in newer versions.
2775 * The API (and possibly others) use this function to determine the possible
2776 * option types for validation purposes, so make sure to update this when a
2777 * new option kind is added.
2779 * @see User::getOptionKinds
2780 * @return array Option kinds
2782 public static function listOptionKinds() {
2785 'registered-multiselect',
2786 'registered-checkmatrix',
2794 * Return an associative array mapping preferences keys to the kind of a preference they're
2795 * used for. Different kinds are handled differently when setting or reading preferences.
2797 * See User::listOptionKinds for the list of valid option types that can be provided.
2799 * @see User::listOptionKinds
2800 * @param IContextSource $context
2801 * @param array $options Assoc. array with options keys to check as keys.
2802 * Defaults to $this->mOptions.
2803 * @return array The key => kind mapping data
2805 public function getOptionKinds( IContextSource
$context, $options = null ) {
2806 $this->loadOptions();
2807 if ( $options === null ) {
2808 $options = $this->mOptions
;
2811 $prefs = Preferences
::getPreferences( $this, $context );
2814 // Pull out the "special" options, so they don't get converted as
2815 // multiselect or checkmatrix.
2816 $specialOptions = array_fill_keys( Preferences
::getSaveBlacklist(), true );
2817 foreach ( $specialOptions as $name => $value ) {
2818 unset( $prefs[$name] );
2821 // Multiselect and checkmatrix options are stored in the database with
2822 // one key per option, each having a boolean value. Extract those keys.
2823 $multiselectOptions = array();
2824 foreach ( $prefs as $name => $info ) {
2825 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2826 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2827 $opts = HTMLFormField
::flattenOptions( $info['options'] );
2828 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2830 foreach ( $opts as $value ) {
2831 $multiselectOptions["$prefix$value"] = true;
2834 unset( $prefs[$name] );
2837 $checkmatrixOptions = array();
2838 foreach ( $prefs as $name => $info ) {
2839 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2840 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2841 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
2842 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
2843 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2845 foreach ( $columns as $column ) {
2846 foreach ( $rows as $row ) {
2847 $checkmatrixOptions["$prefix$column-$row"] = true;
2851 unset( $prefs[$name] );
2855 // $value is ignored
2856 foreach ( $options as $key => $value ) {
2857 if ( isset( $prefs[$key] ) ) {
2858 $mapping[$key] = 'registered';
2859 } elseif ( isset( $multiselectOptions[$key] ) ) {
2860 $mapping[$key] = 'registered-multiselect';
2861 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2862 $mapping[$key] = 'registered-checkmatrix';
2863 } elseif ( isset( $specialOptions[$key] ) ) {
2864 $mapping[$key] = 'special';
2865 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2866 $mapping[$key] = 'userjs';
2868 $mapping[$key] = 'unused';
2876 * Reset certain (or all) options to the site defaults
2878 * The optional parameter determines which kinds of preferences will be reset.
2879 * Supported values are everything that can be reported by getOptionKinds()
2880 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2882 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
2883 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2884 * for backwards-compatibility.
2885 * @param IContextSource|null $context Context source used when $resetKinds
2886 * does not contain 'all', passed to getOptionKinds().
2887 * Defaults to RequestContext::getMain() when null.
2889 public function resetOptions(
2890 $resetKinds = array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ),
2891 IContextSource
$context = null
2894 $defaultOptions = self
::getDefaultOptions();
2896 if ( !is_array( $resetKinds ) ) {
2897 $resetKinds = array( $resetKinds );
2900 if ( in_array( 'all', $resetKinds ) ) {
2901 $newOptions = $defaultOptions;
2903 if ( $context === null ) {
2904 $context = RequestContext
::getMain();
2907 $optionKinds = $this->getOptionKinds( $context );
2908 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
2909 $newOptions = array();
2911 // Use default values for the options that should be deleted, and
2912 // copy old values for the ones that shouldn't.
2913 foreach ( $this->mOptions
as $key => $value ) {
2914 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
2915 if ( array_key_exists( $key, $defaultOptions ) ) {
2916 $newOptions[$key] = $defaultOptions[$key];
2919 $newOptions[$key] = $value;
2924 Hooks
::run( 'UserResetAllOptions', array( $this, &$newOptions, $this->mOptions
, $resetKinds ) );
2926 $this->mOptions
= $newOptions;
2927 $this->mOptionsLoaded
= true;
2931 * Get the user's preferred date format.
2932 * @return string User's preferred date format
2934 public function getDatePreference() {
2935 // Important migration for old data rows
2936 if ( is_null( $this->mDatePreference
) ) {
2938 $value = $this->getOption( 'date' );
2939 $map = $wgLang->getDatePreferenceMigrationMap();
2940 if ( isset( $map[$value] ) ) {
2941 $value = $map[$value];
2943 $this->mDatePreference
= $value;
2945 return $this->mDatePreference
;
2949 * Determine based on the wiki configuration and the user's options,
2950 * whether this user must be over HTTPS no matter what.
2954 public function requiresHTTPS() {
2955 global $wgSecureLogin;
2956 if ( !$wgSecureLogin ) {
2959 $https = $this->getBoolOption( 'prefershttps' );
2960 Hooks
::run( 'UserRequiresHTTPS', array( $this, &$https ) );
2962 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
2969 * Get the user preferred stub threshold
2973 public function getStubThreshold() {
2974 global $wgMaxArticleSize; # Maximum article size, in Kb
2975 $threshold = $this->getIntOption( 'stubthreshold' );
2976 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2977 // If they have set an impossible value, disable the preference
2978 // so we can use the parser cache again.
2985 * Get the permissions this user has.
2986 * @return array Array of String permission names
2988 public function getRights() {
2989 if ( is_null( $this->mRights
) ) {
2990 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
2992 $allowedRights = $this->getRequest()->getSession()->getAllowedUserRights();
2993 if ( $allowedRights !== null ) {
2994 $this->mRights
= array_intersect( $this->mRights
, $allowedRights );
2997 Hooks
::run( 'UserGetRights', array( $this, &$this->mRights
) );
2998 // Force reindexation of rights when a hook has unset one of them
2999 $this->mRights
= array_values( array_unique( $this->mRights
) );
3001 return $this->mRights
;
3005 * Get the list of explicit group memberships this user has.
3006 * The implicit * and user groups are not included.
3007 * @return array Array of String internal group names
3009 public function getGroups() {
3011 $this->loadGroups();
3012 return $this->mGroups
;
3016 * Get the list of implicit group memberships this user has.
3017 * This includes all explicit groups, plus 'user' if logged in,
3018 * '*' for all accounts, and autopromoted groups
3019 * @param bool $recache Whether to avoid the cache
3020 * @return array Array of String internal group names
3022 public function getEffectiveGroups( $recache = false ) {
3023 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
3024 $this->mEffectiveGroups
= array_unique( array_merge(
3025 $this->getGroups(), // explicit groups
3026 $this->getAutomaticGroups( $recache ) // implicit groups
3028 // Hook for additional groups
3029 Hooks
::run( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
3030 // Force reindexation of groups when a hook has unset one of them
3031 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
3033 return $this->mEffectiveGroups
;
3037 * Get the list of implicit group memberships this user has.
3038 * This includes 'user' if logged in, '*' for all accounts,
3039 * and autopromoted groups
3040 * @param bool $recache Whether to avoid the cache
3041 * @return array Array of String internal group names
3043 public function getAutomaticGroups( $recache = false ) {
3044 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
3045 $this->mImplicitGroups
= array( '*' );
3046 if ( $this->getId() ) {
3047 $this->mImplicitGroups
[] = 'user';
3049 $this->mImplicitGroups
= array_unique( array_merge(
3050 $this->mImplicitGroups
,
3051 Autopromote
::getAutopromoteGroups( $this )
3055 // Assure data consistency with rights/groups,
3056 // as getEffectiveGroups() depends on this function
3057 $this->mEffectiveGroups
= null;
3060 return $this->mImplicitGroups
;
3064 * Returns the groups the user has belonged to.
3066 * The user may still belong to the returned groups. Compare with getGroups().
3068 * The function will not return groups the user had belonged to before MW 1.17
3070 * @return array Names of the groups the user has belonged to.
3072 public function getFormerGroups() {
3075 if ( is_null( $this->mFormerGroups
) ) {
3076 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3077 ?
wfGetDB( DB_MASTER
)
3078 : wfGetDB( DB_SLAVE
);
3079 $res = $db->select( 'user_former_groups',
3080 array( 'ufg_group' ),
3081 array( 'ufg_user' => $this->mId
),
3083 $this->mFormerGroups
= array();
3084 foreach ( $res as $row ) {
3085 $this->mFormerGroups
[] = $row->ufg_group
;
3089 return $this->mFormerGroups
;
3093 * Get the user's edit count.
3094 * @return int|null Null for anonymous users
3096 public function getEditCount() {
3097 if ( !$this->getId() ) {
3101 if ( $this->mEditCount
=== null ) {
3102 /* Populate the count, if it has not been populated yet */
3103 $dbr = wfGetDB( DB_SLAVE
);
3104 // check if the user_editcount field has been initialized
3105 $count = $dbr->selectField(
3106 'user', 'user_editcount',
3107 array( 'user_id' => $this->mId
),
3111 if ( $count === null ) {
3112 // it has not been initialized. do so.
3113 $count = $this->initEditCount();
3115 $this->mEditCount
= $count;
3117 return (int)$this->mEditCount
;
3121 * Add the user to the given group.
3122 * This takes immediate effect.
3123 * @param string $group Name of the group to add
3126 public function addGroup( $group ) {
3129 if ( !Hooks
::run( 'UserAddGroup', array( $this, &$group ) ) ) {
3133 $dbw = wfGetDB( DB_MASTER
);
3134 if ( $this->getId() ) {
3135 $dbw->insert( 'user_groups',
3137 'ug_user' => $this->getID(),
3138 'ug_group' => $group,
3141 array( 'IGNORE' ) );
3144 $this->loadGroups();
3145 $this->mGroups
[] = $group;
3146 // In case loadGroups was not called before, we now have the right twice.
3147 // Get rid of the duplicate.
3148 $this->mGroups
= array_unique( $this->mGroups
);
3150 // Refresh the groups caches, and clear the rights cache so it will be
3151 // refreshed on the next call to $this->getRights().
3152 $this->getEffectiveGroups( true );
3153 $this->mRights
= null;
3155 $this->invalidateCache();
3161 * Remove the user from the given group.
3162 * This takes immediate effect.
3163 * @param string $group Name of the group to remove
3166 public function removeGroup( $group ) {
3168 if ( !Hooks
::run( 'UserRemoveGroup', array( $this, &$group ) ) ) {
3172 $dbw = wfGetDB( DB_MASTER
);
3173 $dbw->delete( 'user_groups',
3175 'ug_user' => $this->getID(),
3176 'ug_group' => $group,
3179 // Remember that the user was in this group
3180 $dbw->insert( 'user_former_groups',
3182 'ufg_user' => $this->getID(),
3183 'ufg_group' => $group,
3189 $this->loadGroups();
3190 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
3192 // Refresh the groups caches, and clear the rights cache so it will be
3193 // refreshed on the next call to $this->getRights().
3194 $this->getEffectiveGroups( true );
3195 $this->mRights
= null;
3197 $this->invalidateCache();
3203 * Get whether the user is logged in
3206 public function isLoggedIn() {
3207 return $this->getID() != 0;
3211 * Get whether the user is anonymous
3214 public function isAnon() {
3215 return !$this->isLoggedIn();
3219 * Check if user is allowed to access a feature / make an action
3221 * @param string ... Permissions to test
3222 * @return bool True if user is allowed to perform *any* of the given actions
3224 public function isAllowedAny() {
3225 $permissions = func_get_args();
3226 foreach ( $permissions as $permission ) {
3227 if ( $this->isAllowed( $permission ) ) {
3236 * @param string ... Permissions to test
3237 * @return bool True if the user is allowed to perform *all* of the given actions
3239 public function isAllowedAll() {
3240 $permissions = func_get_args();
3241 foreach ( $permissions as $permission ) {
3242 if ( !$this->isAllowed( $permission ) ) {
3250 * Internal mechanics of testing a permission
3251 * @param string $action
3254 public function isAllowed( $action = '' ) {
3255 if ( $action === '' ) {
3256 return true; // In the spirit of DWIM
3258 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3259 // by misconfiguration: 0 == 'foo'
3260 return in_array( $action, $this->getRights(), true );
3264 * Check whether to enable recent changes patrol features for this user
3265 * @return bool True or false
3267 public function useRCPatrol() {
3268 global $wgUseRCPatrol;
3269 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3273 * Check whether to enable new pages patrol features for this user
3274 * @return bool True or false
3276 public function useNPPatrol() {
3277 global $wgUseRCPatrol, $wgUseNPPatrol;
3279 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3280 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3285 * Check whether to enable new files patrol features for this user
3286 * @return bool True or false
3288 public function useFilePatrol() {
3289 global $wgUseRCPatrol, $wgUseFilePatrol;
3291 ( $wgUseRCPatrol ||
$wgUseFilePatrol )
3292 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3297 * Get the WebRequest object to use with this object
3299 * @return WebRequest
3301 public function getRequest() {
3302 if ( $this->mRequest
) {
3303 return $this->mRequest
;
3311 * Get a WatchedItem for this user and $title.
3313 * @since 1.22 $checkRights parameter added
3314 * @param Title $title
3315 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3316 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3317 * @return WatchedItem
3319 public function getWatchedItem( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3320 $key = $checkRights . ':' . $title->getNamespace() . ':' . $title->getDBkey();
3322 if ( isset( $this->mWatchedItems
[$key] ) ) {
3323 return $this->mWatchedItems
[$key];
3326 if ( count( $this->mWatchedItems
) >= self
::MAX_WATCHED_ITEMS_CACHE
) {
3327 $this->mWatchedItems
= array();
3330 $this->mWatchedItems
[$key] = WatchedItem
::fromUserTitle( $this, $title, $checkRights );
3331 return $this->mWatchedItems
[$key];
3335 * Check the watched status of an article.
3336 * @since 1.22 $checkRights parameter added
3337 * @param Title $title Title of the article to look at
3338 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3339 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3342 public function isWatched( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3343 return $this->getWatchedItem( $title, $checkRights )->isWatched();
3348 * @since 1.22 $checkRights parameter added
3349 * @param Title $title Title of the article to look at
3350 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3351 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3353 public function addWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3354 $this->getWatchedItem( $title, $checkRights )->addWatch();
3355 $this->invalidateCache();
3359 * Stop watching an article.
3360 * @since 1.22 $checkRights parameter added
3361 * @param Title $title Title of the article to look at
3362 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3363 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3365 public function removeWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3366 $this->getWatchedItem( $title, $checkRights )->removeWatch();
3367 $this->invalidateCache();
3371 * Clear the user's notification timestamp for the given title.
3372 * If e-notif e-mails are on, they will receive notification mails on
3373 * the next change of the page if it's watched etc.
3374 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3375 * @param Title $title Title of the article to look at
3376 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3378 public function clearNotification( &$title, $oldid = 0 ) {
3379 global $wgUseEnotif, $wgShowUpdatedMarker;
3381 // Do nothing if the database is locked to writes
3382 if ( wfReadOnly() ) {
3386 // Do nothing if not allowed to edit the watchlist
3387 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3391 // If we're working on user's talk page, we should update the talk page message indicator
3392 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3393 if ( !Hooks
::run( 'UserClearNewTalkNotification', array( &$this, $oldid ) ) ) {
3398 // Try to update the DB post-send and only if needed...
3399 DeferredUpdates
::addCallableUpdate( function() use ( $that, $title, $oldid ) {
3400 if ( !$that->getNewtalk() ) {
3401 return; // no notifications to clear
3404 // Delete the last notifications (they stack up)
3405 $that->setNewtalk( false );
3407 // If there is a new, unseen, revision, use its timestamp
3409 ?
$title->getNextRevisionID( $oldid, Title
::GAID_FOR_UPDATE
)
3412 $that->setNewtalk( true, Revision
::newFromId( $nextid ) );
3417 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3421 if ( $this->isAnon() ) {
3422 // Nothing else to do...
3426 // Only update the timestamp if the page is being watched.
3427 // The query to find out if it is watched is cached both in memcached and per-invocation,
3428 // and when it does have to be executed, it can be on a slave
3429 // If this is the user's newtalk page, we always update the timestamp
3431 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3435 $this->getWatchedItem( $title )->resetNotificationTimestamp(
3436 $force, $oldid, WatchedItem
::DEFERRED
3441 * Resets all of the given user's page-change notification timestamps.
3442 * If e-notif e-mails are on, they will receive notification mails on
3443 * the next change of any watched page.
3444 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3446 public function clearAllNotifications() {
3447 if ( wfReadOnly() ) {
3451 // Do nothing if not allowed to edit the watchlist
3452 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3456 global $wgUseEnotif, $wgShowUpdatedMarker;
3457 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3458 $this->setNewtalk( false );
3461 $id = $this->getId();
3463 $dbw = wfGetDB( DB_MASTER
);
3464 $dbw->update( 'watchlist',
3465 array( /* SET */ 'wl_notificationtimestamp' => null ),
3466 array( /* WHERE */ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ),
3469 // We also need to clear here the "you have new message" notification for the own user_talk page;
3470 // it's cleared one page view later in WikiPage::doViewUpdates().
3475 * Set a cookie on the user's client. Wrapper for
3476 * WebResponse::setCookie
3477 * @deprecated since 1.27
3478 * @param string $name Name of the cookie to set
3479 * @param string $value Value to set
3480 * @param int $exp Expiration time, as a UNIX time value;
3481 * if 0 or not specified, use the default $wgCookieExpiration
3482 * @param bool $secure
3483 * true: Force setting the secure attribute when setting the cookie
3484 * false: Force NOT setting the secure attribute when setting the cookie
3485 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3486 * @param array $params Array of options sent passed to WebResponse::setcookie()
3487 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3490 protected function setCookie(
3491 $name, $value, $exp = 0, $secure = null, $params = array(), $request = null
3493 wfDeprecated( __METHOD__
, '1.27' );
3494 if ( $request === null ) {
3495 $request = $this->getRequest();
3497 $params['secure'] = $secure;
3498 $request->response()->setCookie( $name, $value, $exp, $params );
3502 * Clear a cookie on the user's client
3503 * @deprecated since 1.27
3504 * @param string $name Name of the cookie to clear
3505 * @param bool $secure
3506 * true: Force setting the secure attribute when setting the cookie
3507 * false: Force NOT setting the secure attribute when setting the cookie
3508 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3509 * @param array $params Array of options sent passed to WebResponse::setcookie()
3511 protected function clearCookie( $name, $secure = null, $params = array() ) {
3512 wfDeprecated( __METHOD__
, '1.27' );
3513 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3517 * Set an extended login cookie on the user's client. The expiry of the cookie
3518 * is controlled by the $wgExtendedLoginCookieExpiration configuration
3521 * @see User::setCookie
3523 * @deprecated since 1.27
3524 * @param string $name Name of the cookie to set
3525 * @param string $value Value to set
3526 * @param bool $secure
3527 * true: Force setting the secure attribute when setting the cookie
3528 * false: Force NOT setting the secure attribute when setting the cookie
3529 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3531 protected function setExtendedLoginCookie( $name, $value, $secure ) {
3532 global $wgExtendedLoginCookieExpiration, $wgCookieExpiration;
3534 wfDeprecated( __METHOD__
, '1.27' );
3537 $exp +
= $wgExtendedLoginCookieExpiration !== null
3538 ?
$wgExtendedLoginCookieExpiration
3539 : $wgCookieExpiration;
3541 $this->setCookie( $name, $value, $exp, $secure );
3545 * Persist this user's session (e.g. set cookies)
3547 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3549 * @param bool $secure Whether to force secure/insecure cookies or use default
3550 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3552 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3554 if ( 0 == $this->mId
) {
3558 $session = $this->getRequest()->getSession();
3559 if ( $request && $session->getRequest() !== $request ) {
3560 $session = $session->sessionWithRequest( $request );
3562 $delay = $session->delaySave();
3564 if ( !$session->getUser()->equals( $this ) ) {
3565 if ( !$session->canSetUser() ) {
3566 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3567 ->warning( __METHOD__
.
3568 ": Cannot save user \"$this\" to a user \"{$session->getUser()}\"'s immutable session"
3572 $session->setUser( $this );
3575 $session->setRememberUser( $rememberMe );
3576 if ( $secure !== null ) {
3577 $session->setForceHTTPS( $secure );
3580 $session->persist();
3582 ScopedCallback
::consume( $delay );
3586 * Log this user out.
3588 public function logout() {
3589 if ( Hooks
::run( 'UserLogout', array( &$this ) ) ) {
3595 * Clear the user's session, and reset the instance cache.
3598 public function doLogout() {
3599 $session = $this->getRequest()->getSession();
3600 if ( !$session->canSetUser() ) {
3601 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3602 ->warning( __METHOD__
. ": Cannot log out of an immutable session" );
3603 } elseif ( !$session->getUser()->equals( $this ) ) {
3604 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3605 ->warning( __METHOD__
.
3606 ": Cannot log user \"$this\" out of a user \"{$session->getUser()}\"'s session"
3608 // But we still may as well make this user object anon
3609 $this->clearInstanceCache( 'defaults' );
3611 $this->clearInstanceCache( 'defaults' );
3612 $delay = $session->delaySave();
3613 $session->setLoggedOutTimestamp( time() );
3614 $session->setUser( new User
);
3615 $session->set( 'wsUserID', 0 ); // Other code expects this
3616 ScopedCallback
::consume( $delay );
3621 * Save this user's settings into the database.
3622 * @todo Only rarely do all these fields need to be set!
3624 public function saveSettings() {
3625 if ( wfReadOnly() ) {
3626 // @TODO: caller should deal with this instead!
3627 // This should really just be an exception.
3628 MWExceptionHandler
::logException( new DBExpectedError(
3630 "Could not update user with ID '{$this->mId}'; DB is read-only."
3636 if ( 0 == $this->mId
) {
3640 // Get a new user_touched that is higher than the old one.
3641 // This will be used for a CAS check as a last-resort safety
3642 // check against race conditions and slave lag.
3643 $oldTouched = $this->mTouched
;
3644 $newTouched = $this->newTouchedTimestamp();
3646 $dbw = wfGetDB( DB_MASTER
);
3647 $dbw->update( 'user',
3649 'user_name' => $this->mName
,
3650 'user_real_name' => $this->mRealName
,
3651 'user_email' => $this->mEmail
,
3652 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3653 'user_touched' => $dbw->timestamp( $newTouched ),
3654 'user_token' => strval( $this->mToken
),
3655 'user_email_token' => $this->mEmailToken
,
3656 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
3657 ), array( /* WHERE */
3658 'user_id' => $this->mId
,
3659 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
3663 if ( !$dbw->affectedRows() ) {
3664 // Maybe the problem was a missed cache update; clear it to be safe
3665 $this->clearSharedCache( 'refresh' );
3666 // User was changed in the meantime or loaded with stale data
3667 $from = ( $this->queryFlagsUsed
& self
::READ_LATEST
) ?
'master' : 'slave';
3668 throw new MWException(
3669 "CAS update failed on user_touched for user ID '{$this->mId}' (read from $from);" .
3670 " the version of the user to be saved is older than the current version."
3674 $this->mTouched
= $newTouched;
3675 $this->saveOptions();
3677 Hooks
::run( 'UserSaveSettings', array( $this ) );
3678 $this->clearSharedCache();
3679 $this->getUserPage()->invalidateCache();
3683 * If only this user's username is known, and it exists, return the user ID.
3685 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
3688 public function idForName( $flags = 0 ) {
3689 $s = trim( $this->getName() );
3694 $db = ( ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
)
3695 ?
wfGetDB( DB_MASTER
)
3696 : wfGetDB( DB_SLAVE
);
3698 $options = ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
)
3699 ?
array( 'LOCK IN SHARE MODE' )
3702 $id = $db->selectField( 'user',
3703 'user_id', array( 'user_name' => $s ), __METHOD__
, $options );
3709 * Add a user to the database, return the user object
3711 * @param string $name Username to add
3712 * @param array $params Array of Strings Non-default parameters to save to
3713 * the database as user_* fields:
3714 * - email: The user's email address.
3715 * - email_authenticated: The email authentication timestamp.
3716 * - real_name: The user's real name.
3717 * - options: An associative array of non-default options.
3718 * - token: Random authentication token. Do not set.
3719 * - registration: Registration timestamp. Do not set.
3721 * @return User|null User object, or null if the username already exists.
3723 public static function createNew( $name, $params = array() ) {
3724 foreach ( array( 'password', 'newpassword', 'newpass_time', 'password_expires' ) as $field ) {
3725 if ( isset( $params[$field] ) ) {
3726 wfDeprecated( __METHOD__
. " with param '$field'", '1.27' );
3727 unset( $params[$field] );
3733 $user->setToken(); // init token
3734 if ( isset( $params['options'] ) ) {
3735 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
3736 unset( $params['options'] );
3738 $dbw = wfGetDB( DB_MASTER
);
3739 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3741 $noPass = PasswordFactory
::newInvalidPassword()->toString();
3744 'user_id' => $seqVal,
3745 'user_name' => $name,
3746 'user_password' => $noPass,
3747 'user_newpassword' => $noPass,
3748 'user_email' => $user->mEmail
,
3749 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
3750 'user_real_name' => $user->mRealName
,
3751 'user_token' => strval( $user->mToken
),
3752 'user_registration' => $dbw->timestamp( $user->mRegistration
),
3753 'user_editcount' => 0,
3754 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
3756 foreach ( $params as $name => $value ) {
3757 $fields["user_$name"] = $value;
3759 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
3760 if ( $dbw->affectedRows() ) {
3761 $newUser = User
::newFromId( $dbw->insertId() );
3769 * Add this existing user object to the database. If the user already
3770 * exists, a fatal status object is returned, and the user object is
3771 * initialised with the data from the database.
3773 * Previously, this function generated a DB error due to a key conflict
3774 * if the user already existed. Many extension callers use this function
3775 * in code along the lines of:
3777 * $user = User::newFromName( $name );
3778 * if ( !$user->isLoggedIn() ) {
3779 * $user->addToDatabase();
3781 * // do something with $user...
3783 * However, this was vulnerable to a race condition (bug 16020). By
3784 * initialising the user object if the user exists, we aim to support this
3785 * calling sequence as far as possible.
3787 * Note that if the user exists, this function will acquire a write lock,
3788 * so it is still advisable to make the call conditional on isLoggedIn(),
3789 * and to commit the transaction after calling.
3791 * @throws MWException
3794 public function addToDatabase() {
3796 if ( !$this->mToken
) {
3797 $this->setToken(); // init token
3800 $this->mTouched
= $this->newTouchedTimestamp();
3802 $noPass = PasswordFactory
::newInvalidPassword()->toString();
3804 $dbw = wfGetDB( DB_MASTER
);
3805 $inWrite = $dbw->writesOrCallbacksPending();
3806 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3807 $dbw->insert( 'user',
3809 'user_id' => $seqVal,
3810 'user_name' => $this->mName
,
3811 'user_password' => $noPass,
3812 'user_newpassword' => $noPass,
3813 'user_email' => $this->mEmail
,
3814 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3815 'user_real_name' => $this->mRealName
,
3816 'user_token' => strval( $this->mToken
),
3817 'user_registration' => $dbw->timestamp( $this->mRegistration
),
3818 'user_editcount' => 0,
3819 'user_touched' => $dbw->timestamp( $this->mTouched
),
3823 if ( !$dbw->affectedRows() ) {
3824 // The queries below cannot happen in the same REPEATABLE-READ snapshot.
3825 // Handle this by COMMIT, if possible, or by LOCK IN SHARE MODE otherwise.
3827 // Can't commit due to pending writes that may need atomicity.
3828 // This may cause some lock contention unlike the case below.
3829 $options = array( 'LOCK IN SHARE MODE' );
3830 $flags = self
::READ_LOCKING
;
3832 // Often, this case happens early in views before any writes when
3833 // using CentralAuth. It's should be OK to commit and break the snapshot.
3834 $dbw->commit( __METHOD__
, 'flush' );
3836 $flags = self
::READ_LATEST
;
3838 $this->mId
= $dbw->selectField( 'user', 'user_id',
3839 array( 'user_name' => $this->mName
), __METHOD__
, $options );
3842 if ( $this->loadFromDatabase( $flags ) ) {
3847 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
3848 "to insert user '{$this->mName}' row, but it was not present in select!" );
3850 return Status
::newFatal( 'userexists' );
3852 $this->mId
= $dbw->insertId();
3853 self
::$idCacheByName[$this->mName
] = $this->mId
;
3855 // Clear instance cache other than user table data, which is already accurate
3856 $this->clearInstanceCache();
3858 $this->saveOptions();
3859 return Status
::newGood();
3863 * If this user is logged-in and blocked,
3864 * block any IP address they've successfully logged in from.
3865 * @return bool A block was spread
3867 public function spreadAnyEditBlock() {
3868 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3869 return $this->spreadBlock();
3875 * If this (non-anonymous) user is blocked,
3876 * block the IP address they've successfully logged in from.
3877 * @return bool A block was spread
3879 protected function spreadBlock() {
3880 wfDebug( __METHOD__
. "()\n" );
3882 if ( $this->mId
== 0 ) {
3886 $userblock = Block
::newFromTarget( $this->getName() );
3887 if ( !$userblock ) {
3891 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3895 * Get whether the user is explicitly blocked from account creation.
3896 * @return bool|Block
3898 public function isBlockedFromCreateAccount() {
3899 $this->getBlockedStatus();
3900 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
3901 return $this->mBlock
;
3904 # bug 13611: if the IP address the user is trying to create an account from is
3905 # blocked with createaccount disabled, prevent new account creation there even
3906 # when the user is logged in
3907 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3908 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
3910 return $this->mBlockedFromCreateAccount
instanceof Block
3911 && $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
3912 ?
$this->mBlockedFromCreateAccount
3917 * Get whether the user is blocked from using Special:Emailuser.
3920 public function isBlockedFromEmailuser() {
3921 $this->getBlockedStatus();
3922 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
3926 * Get whether the user is allowed to create an account.
3929 public function isAllowedToCreateAccount() {
3930 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
3934 * Get this user's personal page title.
3936 * @return Title User's personal page title
3938 public function getUserPage() {
3939 return Title
::makeTitle( NS_USER
, $this->getName() );
3943 * Get this user's talk page title.
3945 * @return Title User's talk page title
3947 public function getTalkPage() {
3948 $title = $this->getUserPage();
3949 return $title->getTalkPage();
3953 * Determine whether the user is a newbie. Newbies are either
3954 * anonymous IPs, or the most recently created accounts.
3957 public function isNewbie() {
3958 return !$this->isAllowed( 'autoconfirmed' );
3962 * Check to see if the given clear-text password is one of the accepted passwords
3963 * @deprecated since 1.27. AuthManager is coming.
3964 * @param string $password User password
3965 * @return bool True if the given password is correct, otherwise False
3967 public function checkPassword( $password ) {
3968 global $wgAuth, $wgLegacyEncoding;
3972 // Some passwords will give a fatal Status, which means there is
3973 // some sort of technical or security reason for this password to
3974 // be completely invalid and should never be checked (e.g., T64685)
3975 if ( !$this->checkPasswordValidity( $password )->isOK() ) {
3979 // Certain authentication plugins do NOT want to save
3980 // domain passwords in a mysql database, so we should
3981 // check this (in case $wgAuth->strict() is false).
3982 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
3984 } elseif ( $wgAuth->strict() ) {
3985 // Auth plugin doesn't allow local authentication
3987 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
3988 // Auth plugin doesn't allow local authentication for this user name
3992 $passwordFactory = new PasswordFactory();
3993 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
3994 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3995 ?
wfGetDB( DB_MASTER
)
3996 : wfGetDB( DB_SLAVE
);
3999 $mPassword = $passwordFactory->newFromCiphertext( $db->selectField(
4000 'user', 'user_password', array( 'user_id' => $this->getId() ), __METHOD__
4002 } catch ( PasswordError
$e ) {
4003 wfDebug( 'Invalid password hash found in database.' );
4004 $mPassword = PasswordFactory
::newInvalidPassword();
4007 if ( !$mPassword->equals( $password ) ) {
4008 if ( $wgLegacyEncoding ) {
4009 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
4010 // Check for this with iconv
4011 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
4012 if ( $cp1252Password === $password ||
!$mPassword->equals( $cp1252Password ) ) {
4020 if ( $passwordFactory->needsUpdate( $mPassword ) && !wfReadOnly() ) {
4021 $this->setPasswordInternal( $password );
4028 * Check if the given clear-text password matches the temporary password
4029 * sent by e-mail for password reset operations.
4031 * @deprecated since 1.27. AuthManager is coming.
4032 * @param string $plaintext
4033 * @return bool True if matches, false otherwise
4035 public function checkTemporaryPassword( $plaintext ) {
4036 global $wgNewPasswordExpiry;
4040 $passwordFactory = new PasswordFactory();
4041 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4042 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
4043 ?
wfGetDB( DB_MASTER
)
4044 : wfGetDB( DB_SLAVE
);
4046 $row = $db->selectRow(
4048 array( 'user_newpassword', 'user_newpass_time' ),
4049 array( 'user_id' => $this->getId() ),
4053 $newPassword = $passwordFactory->newFromCiphertext( $row->user_newpassword
);
4054 } catch ( PasswordError
$e ) {
4055 wfDebug( 'Invalid password hash found in database.' );
4056 $newPassword = PasswordFactory
::newInvalidPassword();
4059 if ( $newPassword->equals( $plaintext ) ) {
4060 if ( is_null( $row->user_newpass_time
) ) {
4063 $expiry = wfTimestamp( TS_UNIX
, $row->user_newpass_time
) +
$wgNewPasswordExpiry;
4064 return ( time() < $expiry );
4071 * Initialize (if necessary) and return a session token value
4072 * which can be used in edit forms to show that the user's
4073 * login credentials aren't being hijacked with a foreign form
4077 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4078 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4079 * @return MediaWiki\\Session\\Token The new edit token
4081 public function getEditTokenObject( $salt = '', $request = null ) {
4082 if ( $this->isAnon() ) {
4083 return new LoggedOutEditToken();
4087 $request = $this->getRequest();
4089 return $request->getSession()->getToken( $salt );
4093 * Initialize (if necessary) and return a session token value
4094 * which can be used in edit forms to show that the user's
4095 * login credentials aren't being hijacked with a foreign form
4099 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4100 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4101 * @return string The new edit token
4103 public function getEditToken( $salt = '', $request = null ) {
4104 return $this->getEditTokenObject( $salt, $request )->toString();
4108 * Get the embedded timestamp from a token.
4109 * @deprecated since 1.27, use \\MediaWiki\\Session\\Token::getTimestamp instead.
4110 * @param string $val Input token
4113 public static function getEditTokenTimestamp( $val ) {
4114 wfDeprecated( __METHOD__
, '1.27' );
4115 return MediaWiki\Session\Token
::getTimestamp( $val );
4119 * Check given value against the token value stored in the session.
4120 * A match should confirm that the form was submitted from the
4121 * user's own login session, not a form submission from a third-party
4124 * @param string $val Input value to compare
4125 * @param string $salt Optional function-specific data for hashing
4126 * @param WebRequest|null $request Object to use or null to use $wgRequest
4127 * @param int $maxage Fail tokens older than this, in seconds
4128 * @return bool Whether the token matches
4130 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4131 return $this->getEditTokenObject( $salt, $request )->match( $val, $maxage );
4135 * Check given value against the token value stored in the session,
4136 * ignoring the suffix.
4138 * @param string $val Input value to compare
4139 * @param string $salt Optional function-specific data for hashing
4140 * @param WebRequest|null $request Object to use or null to use $wgRequest
4141 * @param int $maxage Fail tokens older than this, in seconds
4142 * @return bool Whether the token matches
4144 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4145 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . self
::EDIT_TOKEN_SUFFIX
;
4146 return $this->matchEditToken( $val, $salt, $request, $maxage );
4150 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4151 * mail to the user's given address.
4153 * @param string $type Message to send, either "created", "changed" or "set"
4156 public function sendConfirmationMail( $type = 'created' ) {
4158 $expiration = null; // gets passed-by-ref and defined in next line.
4159 $token = $this->confirmationToken( $expiration );
4160 $url = $this->confirmationTokenUrl( $token );
4161 $invalidateURL = $this->invalidationTokenUrl( $token );
4162 $this->saveSettings();
4164 if ( $type == 'created' ||
$type === false ) {
4165 $message = 'confirmemail_body';
4166 } elseif ( $type === true ) {
4167 $message = 'confirmemail_body_changed';
4169 // Messages: confirmemail_body_changed, confirmemail_body_set
4170 $message = 'confirmemail_body_' . $type;
4173 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4174 wfMessage( $message,
4175 $this->getRequest()->getIP(),
4178 $wgLang->userTimeAndDate( $expiration, $this ),
4180 $wgLang->userDate( $expiration, $this ),
4181 $wgLang->userTime( $expiration, $this ) )->text() );
4185 * Send an e-mail to this user's account. Does not check for
4186 * confirmed status or validity.
4188 * @param string $subject Message subject
4189 * @param string $body Message body
4190 * @param User|null $from Optional sending user; if unspecified, default
4191 * $wgPasswordSender will be used.
4192 * @param string $replyto Reply-To address
4195 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4196 global $wgPasswordSender;
4198 if ( $from instanceof User
) {
4199 $sender = MailAddress
::newFromUser( $from );
4201 $sender = new MailAddress( $wgPasswordSender,
4202 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4204 $to = MailAddress
::newFromUser( $this );
4206 return UserMailer
::send( $to, $sender, $subject, $body, array(
4207 'replyTo' => $replyto,
4212 * Generate, store, and return a new e-mail confirmation code.
4213 * A hash (unsalted, since it's used as a key) is stored.
4215 * @note Call saveSettings() after calling this function to commit
4216 * this change to the database.
4218 * @param string &$expiration Accepts the expiration time
4219 * @return string New token
4221 protected function confirmationToken( &$expiration ) {
4222 global $wgUserEmailConfirmationTokenExpiry;
4224 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4225 $expiration = wfTimestamp( TS_MW
, $expires );
4227 $token = MWCryptRand
::generateHex( 32 );
4228 $hash = md5( $token );
4229 $this->mEmailToken
= $hash;
4230 $this->mEmailTokenExpires
= $expiration;
4235 * Return a URL the user can use to confirm their email address.
4236 * @param string $token Accepts the email confirmation token
4237 * @return string New token URL
4239 protected function confirmationTokenUrl( $token ) {
4240 return $this->getTokenUrl( 'ConfirmEmail', $token );
4244 * Return a URL the user can use to invalidate their email address.
4245 * @param string $token Accepts the email confirmation token
4246 * @return string New token URL
4248 protected function invalidationTokenUrl( $token ) {
4249 return $this->getTokenUrl( 'InvalidateEmail', $token );
4253 * Internal function to format the e-mail validation/invalidation URLs.
4254 * This uses a quickie hack to use the
4255 * hardcoded English names of the Special: pages, for ASCII safety.
4257 * @note Since these URLs get dropped directly into emails, using the
4258 * short English names avoids insanely long URL-encoded links, which
4259 * also sometimes can get corrupted in some browsers/mailers
4260 * (bug 6957 with Gmail and Internet Explorer).
4262 * @param string $page Special page
4263 * @param string $token Token
4264 * @return string Formatted URL
4266 protected function getTokenUrl( $page, $token ) {
4267 // Hack to bypass localization of 'Special:'
4268 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4269 return $title->getCanonicalURL();
4273 * Mark the e-mail address confirmed.
4275 * @note Call saveSettings() after calling this function to commit the change.
4279 public function confirmEmail() {
4280 // Check if it's already confirmed, so we don't touch the database
4281 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4282 if ( !$this->isEmailConfirmed() ) {
4283 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4284 Hooks
::run( 'ConfirmEmailComplete', array( $this ) );
4290 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4291 * address if it was already confirmed.
4293 * @note Call saveSettings() after calling this function to commit the change.
4294 * @return bool Returns true
4296 public function invalidateEmail() {
4298 $this->mEmailToken
= null;
4299 $this->mEmailTokenExpires
= null;
4300 $this->setEmailAuthenticationTimestamp( null );
4302 Hooks
::run( 'InvalidateEmailComplete', array( $this ) );
4307 * Set the e-mail authentication timestamp.
4308 * @param string $timestamp TS_MW timestamp
4310 public function setEmailAuthenticationTimestamp( $timestamp ) {
4312 $this->mEmailAuthenticated
= $timestamp;
4313 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
4317 * Is this user allowed to send e-mails within limits of current
4318 * site configuration?
4321 public function canSendEmail() {
4322 global $wgEnableEmail, $wgEnableUserEmail;
4323 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4326 $canSend = $this->isEmailConfirmed();
4327 Hooks
::run( 'UserCanSendEmail', array( &$this, &$canSend ) );
4332 * Is this user allowed to receive e-mails within limits of current
4333 * site configuration?
4336 public function canReceiveEmail() {
4337 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4341 * Is this user's e-mail address valid-looking and confirmed within
4342 * limits of the current site configuration?
4344 * @note If $wgEmailAuthentication is on, this may require the user to have
4345 * confirmed their address by returning a code or using a password
4346 * sent to the address from the wiki.
4350 public function isEmailConfirmed() {
4351 global $wgEmailAuthentication;
4354 if ( Hooks
::run( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
4355 if ( $this->isAnon() ) {
4358 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4361 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4371 * Check whether there is an outstanding request for e-mail confirmation.
4374 public function isEmailConfirmationPending() {
4375 global $wgEmailAuthentication;
4376 return $wgEmailAuthentication &&
4377 !$this->isEmailConfirmed() &&
4378 $this->mEmailToken
&&
4379 $this->mEmailTokenExpires
> wfTimestamp();
4383 * Get the timestamp of account creation.
4385 * @return string|bool|null Timestamp of account creation, false for
4386 * non-existent/anonymous user accounts, or null if existing account
4387 * but information is not in database.
4389 public function getRegistration() {
4390 if ( $this->isAnon() ) {
4394 return $this->mRegistration
;
4398 * Get the timestamp of the first edit
4400 * @return string|bool Timestamp of first edit, or false for
4401 * non-existent/anonymous user accounts.
4403 public function getFirstEditTimestamp() {
4404 if ( $this->getId() == 0 ) {
4405 return false; // anons
4407 $dbr = wfGetDB( DB_SLAVE
);
4408 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4409 array( 'rev_user' => $this->getId() ),
4411 array( 'ORDER BY' => 'rev_timestamp ASC' )
4414 return false; // no edits
4416 return wfTimestamp( TS_MW
, $time );
4420 * Get the permissions associated with a given list of groups
4422 * @param array $groups Array of Strings List of internal group names
4423 * @return array Array of Strings List of permission key names for given groups combined
4425 public static function getGroupPermissions( $groups ) {
4426 global $wgGroupPermissions, $wgRevokePermissions;
4428 // grant every granted permission first
4429 foreach ( $groups as $group ) {
4430 if ( isset( $wgGroupPermissions[$group] ) ) {
4431 $rights = array_merge( $rights,
4432 // array_filter removes empty items
4433 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4436 // now revoke the revoked permissions
4437 foreach ( $groups as $group ) {
4438 if ( isset( $wgRevokePermissions[$group] ) ) {
4439 $rights = array_diff( $rights,
4440 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4443 return array_unique( $rights );
4447 * Get all the groups who have a given permission
4449 * @param string $role Role to check
4450 * @return array Array of Strings List of internal group names with the given permission
4452 public static function getGroupsWithPermission( $role ) {
4453 global $wgGroupPermissions;
4454 $allowedGroups = array();
4455 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4456 if ( self
::groupHasPermission( $group, $role ) ) {
4457 $allowedGroups[] = $group;
4460 return $allowedGroups;
4464 * Check, if the given group has the given permission
4466 * If you're wanting to check whether all users have a permission, use
4467 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4471 * @param string $group Group to check
4472 * @param string $role Role to check
4475 public static function groupHasPermission( $group, $role ) {
4476 global $wgGroupPermissions, $wgRevokePermissions;
4477 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4478 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4482 * Check if all users may be assumed to have the given permission
4484 * We generally assume so if the right is granted to '*' and isn't revoked
4485 * on any group. It doesn't attempt to take grants or other extension
4486 * limitations on rights into account in the general case, though, as that
4487 * would require it to always return false and defeat the purpose.
4488 * Specifically, session-based rights restrictions (such as OAuth or bot
4489 * passwords) are applied based on the current session.
4492 * @param string $right Right to check
4495 public static function isEveryoneAllowed( $right ) {
4496 global $wgGroupPermissions, $wgRevokePermissions;
4497 static $cache = array();
4499 // Use the cached results, except in unit tests which rely on
4500 // being able change the permission mid-request
4501 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4502 return $cache[$right];
4505 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4506 $cache[$right] = false;
4510 // If it's revoked anywhere, then everyone doesn't have it
4511 foreach ( $wgRevokePermissions as $rights ) {
4512 if ( isset( $rights[$right] ) && $rights[$right] ) {
4513 $cache[$right] = false;
4518 // Remove any rights that aren't allowed to the global-session user
4519 $allowedRights = SessionManager
::getGlobalSession()->getAllowedUserRights();
4520 if ( $allowedRights !== null && !in_array( $right, $allowedRights, true ) ) {
4521 $cache[$right] = false;
4525 // Allow extensions to say false
4526 if ( !Hooks
::run( 'UserIsEveryoneAllowed', array( $right ) ) ) {
4527 $cache[$right] = false;
4531 $cache[$right] = true;
4536 * Get the localized descriptive name for a group, if it exists
4538 * @param string $group Internal group name
4539 * @return string Localized descriptive group name
4541 public static function getGroupName( $group ) {
4542 $msg = wfMessage( "group-$group" );
4543 return $msg->isBlank() ?
$group : $msg->text();
4547 * Get the localized descriptive name for a member of a group, if it exists
4549 * @param string $group Internal group name
4550 * @param string $username Username for gender (since 1.19)
4551 * @return string Localized name for group member
4553 public static function getGroupMember( $group, $username = '#' ) {
4554 $msg = wfMessage( "group-$group-member", $username );
4555 return $msg->isBlank() ?
$group : $msg->text();
4559 * Return the set of defined explicit groups.
4560 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4561 * are not included, as they are defined automatically, not in the database.
4562 * @return array Array of internal group names
4564 public static function getAllGroups() {
4565 global $wgGroupPermissions, $wgRevokePermissions;
4567 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4568 self
::getImplicitGroups()
4573 * Get a list of all available permissions.
4574 * @return string[] Array of permission names
4576 public static function getAllRights() {
4577 if ( self
::$mAllRights === false ) {
4578 global $wgAvailableRights;
4579 if ( count( $wgAvailableRights ) ) {
4580 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
4582 self
::$mAllRights = self
::$mCoreRights;
4584 Hooks
::run( 'UserGetAllRights', array( &self
::$mAllRights ) );
4586 return self
::$mAllRights;
4590 * Get a list of implicit groups
4591 * @return array Array of Strings Array of internal group names
4593 public static function getImplicitGroups() {
4594 global $wgImplicitGroups;
4596 $groups = $wgImplicitGroups;
4597 # Deprecated, use $wgImplicitGroups instead
4598 Hooks
::run( 'UserGetImplicitGroups', array( &$groups ), '1.25' );
4604 * Get the title of a page describing a particular group
4606 * @param string $group Internal group name
4607 * @return Title|bool Title of the page if it exists, false otherwise
4609 public static function getGroupPage( $group ) {
4610 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4611 if ( $msg->exists() ) {
4612 $title = Title
::newFromText( $msg->text() );
4613 if ( is_object( $title ) ) {
4621 * Create a link to the group in HTML, if available;
4622 * else return the group name.
4624 * @param string $group Internal name of the group
4625 * @param string $text The text of the link
4626 * @return string HTML link to the group
4628 public static function makeGroupLinkHTML( $group, $text = '' ) {
4629 if ( $text == '' ) {
4630 $text = self
::getGroupName( $group );
4632 $title = self
::getGroupPage( $group );
4634 return Linker
::link( $title, htmlspecialchars( $text ) );
4636 return htmlspecialchars( $text );
4641 * Create a link to the group in Wikitext, if available;
4642 * else return the group name.
4644 * @param string $group Internal name of the group
4645 * @param string $text The text of the link
4646 * @return string Wikilink to the group
4648 public static function makeGroupLinkWiki( $group, $text = '' ) {
4649 if ( $text == '' ) {
4650 $text = self
::getGroupName( $group );
4652 $title = self
::getGroupPage( $group );
4654 $page = $title->getFullText();
4655 return "[[$page|$text]]";
4662 * Returns an array of the groups that a particular group can add/remove.
4664 * @param string $group The group to check for whether it can add/remove
4665 * @return array Array( 'add' => array( addablegroups ),
4666 * 'remove' => array( removablegroups ),
4667 * 'add-self' => array( addablegroups to self),
4668 * 'remove-self' => array( removable groups from self) )
4670 public static function changeableByGroup( $group ) {
4671 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4675 'remove' => array(),
4676 'add-self' => array(),
4677 'remove-self' => array()
4680 if ( empty( $wgAddGroups[$group] ) ) {
4681 // Don't add anything to $groups
4682 } elseif ( $wgAddGroups[$group] === true ) {
4683 // You get everything
4684 $groups['add'] = self
::getAllGroups();
4685 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4686 $groups['add'] = $wgAddGroups[$group];
4689 // Same thing for remove
4690 if ( empty( $wgRemoveGroups[$group] ) ) {
4692 } elseif ( $wgRemoveGroups[$group] === true ) {
4693 $groups['remove'] = self
::getAllGroups();
4694 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4695 $groups['remove'] = $wgRemoveGroups[$group];
4698 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4699 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4700 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4701 if ( is_int( $key ) ) {
4702 $wgGroupsAddToSelf['user'][] = $value;
4707 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
4708 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4709 if ( is_int( $key ) ) {
4710 $wgGroupsRemoveFromSelf['user'][] = $value;
4715 // Now figure out what groups the user can add to him/herself
4716 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4718 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4719 // No idea WHY this would be used, but it's there
4720 $groups['add-self'] = User
::getAllGroups();
4721 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4722 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4725 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4727 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4728 $groups['remove-self'] = User
::getAllGroups();
4729 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4730 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4737 * Returns an array of groups that this user can add and remove
4738 * @return array Array( 'add' => array( addablegroups ),
4739 * 'remove' => array( removablegroups ),
4740 * 'add-self' => array( addablegroups to self),
4741 * 'remove-self' => array( removable groups from self) )
4743 public function changeableGroups() {
4744 if ( $this->isAllowed( 'userrights' ) ) {
4745 // This group gives the right to modify everything (reverse-
4746 // compatibility with old "userrights lets you change
4748 // Using array_merge to make the groups reindexed
4749 $all = array_merge( User
::getAllGroups() );
4753 'add-self' => array(),
4754 'remove-self' => array()
4758 // Okay, it's not so simple, we will have to go through the arrays
4761 'remove' => array(),
4762 'add-self' => array(),
4763 'remove-self' => array()
4765 $addergroups = $this->getEffectiveGroups();
4767 foreach ( $addergroups as $addergroup ) {
4768 $groups = array_merge_recursive(
4769 $groups, $this->changeableByGroup( $addergroup )
4771 $groups['add'] = array_unique( $groups['add'] );
4772 $groups['remove'] = array_unique( $groups['remove'] );
4773 $groups['add-self'] = array_unique( $groups['add-self'] );
4774 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4780 * Deferred version of incEditCountImmediate()
4782 public function incEditCount() {
4784 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle( function() use ( $that ) {
4785 $that->incEditCountImmediate();
4790 * Increment the user's edit-count field.
4791 * Will have no effect for anonymous users.
4794 public function incEditCountImmediate() {
4795 if ( $this->isAnon() ) {
4799 $dbw = wfGetDB( DB_MASTER
);
4800 // No rows will be "affected" if user_editcount is NULL
4803 array( 'user_editcount=user_editcount+1' ),
4804 array( 'user_id' => $this->getId(), 'user_editcount IS NOT NULL' ),
4807 // Lazy initialization check...
4808 if ( $dbw->affectedRows() == 0 ) {
4809 // Now here's a goddamn hack...
4810 $dbr = wfGetDB( DB_SLAVE
);
4811 if ( $dbr !== $dbw ) {
4812 // If we actually have a slave server, the count is
4813 // at least one behind because the current transaction
4814 // has not been committed and replicated.
4815 $this->initEditCount( 1 );
4817 // But if DB_SLAVE is selecting the master, then the
4818 // count we just read includes the revision that was
4819 // just added in the working transaction.
4820 $this->initEditCount();
4823 // Edit count in user cache too
4824 $this->invalidateCache();
4828 * Initialize user_editcount from data out of the revision table
4830 * @param int $add Edits to add to the count from the revision table
4831 * @return int Number of edits
4833 protected function initEditCount( $add = 0 ) {
4834 // Pull from a slave to be less cruel to servers
4835 // Accuracy isn't the point anyway here
4836 $dbr = wfGetDB( DB_SLAVE
);
4837 $count = (int)$dbr->selectField(
4840 array( 'rev_user' => $this->getId() ),
4843 $count = $count +
$add;
4845 $dbw = wfGetDB( DB_MASTER
);
4848 array( 'user_editcount' => $count ),
4849 array( 'user_id' => $this->getId() ),
4857 * Get the description of a given right
4859 * @param string $right Right to query
4860 * @return string Localized description of the right
4862 public static function getRightDescription( $right ) {
4863 $key = "right-$right";
4864 $msg = wfMessage( $key );
4865 return $msg->isBlank() ?
$right : $msg->text();
4869 * Make a new-style password hash
4871 * @param string $password Plain-text password
4872 * @param bool|string $salt Optional salt, may be random or the user ID.
4873 * If unspecified or false, will generate one automatically
4874 * @return string Password hash
4875 * @deprecated since 1.24, use Password class
4877 public static function crypt( $password, $salt = false ) {
4878 wfDeprecated( __METHOD__
, '1.24' );
4879 $passwordFactory = new PasswordFactory();
4880 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4881 $hash = $passwordFactory->newFromPlaintext( $password );
4882 return $hash->toString();
4886 * Compare a password hash with a plain-text password. Requires the user
4887 * ID if there's a chance that the hash is an old-style hash.
4889 * @param string $hash Password hash
4890 * @param string $password Plain-text password to compare
4891 * @param string|bool $userId User ID for old-style password salt
4894 * @deprecated since 1.24, use Password class
4896 public static function comparePasswords( $hash, $password, $userId = false ) {
4897 wfDeprecated( __METHOD__
, '1.24' );
4899 // Check for *really* old password hashes that don't even have a type
4900 // The old hash format was just an md5 hex hash, with no type information
4901 if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) {
4902 global $wgPasswordSalt;
4903 if ( $wgPasswordSalt ) {
4904 $password = ":B:{$userId}:{$hash}";
4906 $password = ":A:{$hash}";
4910 $passwordFactory = new PasswordFactory();
4911 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4912 $hash = $passwordFactory->newFromCiphertext( $hash );
4913 return $hash->equals( $password );
4917 * Add a newuser log entry for this user.
4918 * Before 1.19 the return value was always true.
4920 * @param string|bool $action Account creation type.
4921 * - String, one of the following values:
4922 * - 'create' for an anonymous user creating an account for himself.
4923 * This will force the action's performer to be the created user itself,
4924 * no matter the value of $wgUser
4925 * - 'create2' for a logged in user creating an account for someone else
4926 * - 'byemail' when the created user will receive its password by e-mail
4927 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
4928 * - Boolean means whether the account was created by e-mail (deprecated):
4929 * - true will be converted to 'byemail'
4930 * - false will be converted to 'create' if this object is the same as
4931 * $wgUser and to 'create2' otherwise
4933 * @param string $reason User supplied reason
4935 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
4937 public function addNewUserLogEntry( $action = false, $reason = '' ) {
4938 global $wgUser, $wgNewUserLog;
4939 if ( empty( $wgNewUserLog ) ) {
4940 return true; // disabled
4943 if ( $action === true ) {
4944 $action = 'byemail';
4945 } elseif ( $action === false ) {
4946 if ( $this->equals( $wgUser ) ) {
4949 $action = 'create2';
4953 if ( $action === 'create' ||
$action === 'autocreate' ) {
4956 $performer = $wgUser;
4959 $logEntry = new ManualLogEntry( 'newusers', $action );
4960 $logEntry->setPerformer( $performer );
4961 $logEntry->setTarget( $this->getUserPage() );
4962 $logEntry->setComment( $reason );
4963 $logEntry->setParameters( array(
4964 '4::userid' => $this->getId(),
4966 $logid = $logEntry->insert();
4968 if ( $action !== 'autocreate' ) {
4969 $logEntry->publish( $logid );
4976 * Add an autocreate newuser log entry for this user
4977 * Used by things like CentralAuth and perhaps other authplugins.
4978 * Consider calling addNewUserLogEntry() directly instead.
4982 public function addNewUserLogEntryAutoCreate() {
4983 $this->addNewUserLogEntry( 'autocreate' );
4989 * Load the user options either from cache, the database or an array
4991 * @param array $data Rows for the current user out of the user_properties table
4993 protected function loadOptions( $data = null ) {
4998 if ( $this->mOptionsLoaded
) {
5002 $this->mOptions
= self
::getDefaultOptions();
5004 if ( !$this->getId() ) {
5005 // For unlogged-in users, load language/variant options from request.
5006 // There's no need to do it for logged-in users: they can set preferences,
5007 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5008 // so don't override user's choice (especially when the user chooses site default).
5009 $variant = $wgContLang->getDefaultVariant();
5010 $this->mOptions
['variant'] = $variant;
5011 $this->mOptions
['language'] = $variant;
5012 $this->mOptionsLoaded
= true;
5016 // Maybe load from the object
5017 if ( !is_null( $this->mOptionOverrides
) ) {
5018 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5019 foreach ( $this->mOptionOverrides
as $key => $value ) {
5020 $this->mOptions
[$key] = $value;
5023 if ( !is_array( $data ) ) {
5024 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5025 // Load from database
5026 $dbr = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
5027 ?
wfGetDB( DB_MASTER
)
5028 : wfGetDB( DB_SLAVE
);
5030 $res = $dbr->select(
5032 array( 'up_property', 'up_value' ),
5033 array( 'up_user' => $this->getId() ),
5037 $this->mOptionOverrides
= array();
5039 foreach ( $res as $row ) {
5040 $data[$row->up_property
] = $row->up_value
;
5043 foreach ( $data as $property => $value ) {
5044 $this->mOptionOverrides
[$property] = $value;
5045 $this->mOptions
[$property] = $value;
5049 $this->mOptionsLoaded
= true;
5051 Hooks
::run( 'UserLoadOptions', array( $this, &$this->mOptions
) );
5055 * Saves the non-default options for this user, as previously set e.g. via
5056 * setOption(), in the database's "user_properties" (preferences) table.
5057 * Usually used via saveSettings().
5059 protected function saveOptions() {
5060 $this->loadOptions();
5062 // Not using getOptions(), to keep hidden preferences in database
5063 $saveOptions = $this->mOptions
;
5065 // Allow hooks to abort, for instance to save to a global profile.
5066 // Reset options to default state before saving.
5067 if ( !Hooks
::run( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
5071 $userId = $this->getId();
5073 $insert_rows = array(); // all the new preference rows
5074 foreach ( $saveOptions as $key => $value ) {
5075 // Don't bother storing default values
5076 $defaultOption = self
::getDefaultOption( $key );
5077 if ( ( $defaultOption === null && $value !== false && $value !== null )
5078 ||
$value != $defaultOption
5080 $insert_rows[] = array(
5081 'up_user' => $userId,
5082 'up_property' => $key,
5083 'up_value' => $value,
5088 $dbw = wfGetDB( DB_MASTER
);
5090 $res = $dbw->select( 'user_properties',
5091 array( 'up_property', 'up_value' ), array( 'up_user' => $userId ), __METHOD__
);
5093 // Find prior rows that need to be removed or updated. These rows will
5094 // all be deleted (the later so that INSERT IGNORE applies the new values).
5095 $keysDelete = array();
5096 foreach ( $res as $row ) {
5097 if ( !isset( $saveOptions[$row->up_property
] )
5098 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
5100 $keysDelete[] = $row->up_property
;
5104 if ( count( $keysDelete ) ) {
5105 // Do the DELETE by PRIMARY KEY for prior rows.
5106 // In the past a very large portion of calls to this function are for setting
5107 // 'rememberpassword' for new accounts (a preference that has since been removed).
5108 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5109 // caused gap locks on [max user ID,+infinity) which caused high contention since
5110 // updates would pile up on each other as they are for higher (newer) user IDs.
5111 // It might not be necessary these days, but it shouldn't hurt either.
5112 $dbw->delete( 'user_properties',
5113 array( 'up_user' => $userId, 'up_property' => $keysDelete ), __METHOD__
);
5115 // Insert the new preference rows
5116 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, array( 'IGNORE' ) );
5120 * Lazily instantiate and return a factory object for making passwords
5122 * @deprecated since 1.27, create a PasswordFactory directly instead
5123 * @return PasswordFactory
5125 public static function getPasswordFactory() {
5126 wfDeprecated( __METHOD__
, '1.27' );
5127 $ret = new PasswordFactory();
5128 $ret->init( RequestContext
::getMain()->getConfig() );
5133 * Provide an array of HTML5 attributes to put on an input element
5134 * intended for the user to enter a new password. This may include
5135 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
5137 * Do *not* use this when asking the user to enter his current password!
5138 * Regardless of configuration, users may have invalid passwords for whatever
5139 * reason (e.g., they were set before requirements were tightened up).
5140 * Only use it when asking for a new password, like on account creation or
5143 * Obviously, you still need to do server-side checking.
5145 * NOTE: A combination of bugs in various browsers means that this function
5146 * actually just returns array() unconditionally at the moment. May as
5147 * well keep it around for when the browser bugs get fixed, though.
5149 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
5151 * @deprecated since 1.27
5152 * @return array Array of HTML attributes suitable for feeding to
5153 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
5154 * That will get confused by the boolean attribute syntax used.)
5156 public static function passwordChangeInputAttribs() {
5157 global $wgMinimalPasswordLength;
5159 if ( $wgMinimalPasswordLength == 0 ) {
5163 # Note that the pattern requirement will always be satisfied if the
5164 # input is empty, so we need required in all cases.
5166 # @todo FIXME: Bug 23769: This needs to not claim the password is required
5167 # if e-mail confirmation is being used. Since HTML5 input validation
5168 # is b0rked anyway in some browsers, just return nothing. When it's
5169 # re-enabled, fix this code to not output required for e-mail
5171 # $ret = array( 'required' );
5174 # We can't actually do this right now, because Opera 9.6 will print out
5175 # the entered password visibly in its error message! When other
5176 # browsers add support for this attribute, or Opera fixes its support,
5177 # we can add support with a version check to avoid doing this on Opera
5178 # versions where it will be a problem. Reported to Opera as
5179 # DSK-262266, but they don't have a public bug tracker for us to follow.
5181 if ( $wgMinimalPasswordLength > 1 ) {
5182 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
5183 $ret['title'] = wfMessage( 'passwordtooshort' )
5184 ->numParams( $wgMinimalPasswordLength )->text();
5192 * Return the list of user fields that should be selected to create
5193 * a new user object.
5196 public static function selectFields() {
5204 'user_email_authenticated',
5206 'user_email_token_expires',
5207 'user_registration',
5213 * Factory function for fatal permission-denied errors
5216 * @param string $permission User right required
5219 static function newFatalPermissionDeniedStatus( $permission ) {
5222 $groups = array_map(
5223 array( 'User', 'makeGroupLinkWiki' ),
5224 User
::getGroupsWithPermission( $permission )
5228 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5230 return Status
::newFatal( 'badaccess-group0' );
5235 * Get a new instance of this user that was loaded from the master via a locking read
5237 * Use this instead of the main context User when updating that user. This avoids races
5238 * where that user was loaded from a slave or even the master but without proper locks.
5240 * @return User|null Returns null if the user was not found in the DB
5243 public function getInstanceForUpdate() {
5244 if ( !$this->getId() ) {
5245 return null; // anon
5248 $user = self
::newFromId( $this->getId() );
5249 if ( !$user->loadFromId( self
::READ_EXCLUSIVE
) ) {
5257 * Checks if two user objects point to the same user.
5263 public function equals( User
$user ) {
5264 return $this->getName() === $user->getName();