3 * Implements the User class for the %MediaWiki software.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use MediaWiki\Session\SessionManager
;
26 * String Some punctuation to prevent editing from broken text-mangling proxies.
27 * @deprecated since 1.27, use \\MediaWiki\\Session\\Token::SUFFIX
30 define( 'EDIT_TOKEN_SUFFIX', MediaWiki\Session\Token
::SUFFIX
);
33 * The User object encapsulates all of the user-specific settings (user_id,
34 * name, rights, email address, options, last login time). Client
35 * classes use the getXXX() functions to access these fields. These functions
36 * do all the work of determining whether the user is logged in,
37 * whether the requested option can be satisfied from cookies or
38 * whether a database query is needed. Most of the settings needed
39 * for rendering normal pages are set in the cookie to minimize use
42 class User
implements IDBAccessObject
{
44 * @const int Number of characters in user_token field.
46 const TOKEN_LENGTH
= 32;
49 * @const string An invalid value for user_token
51 const INVALID_TOKEN
= '*** INVALID ***';
54 * Global constant made accessible as class constants so that autoloader
56 * @deprecated since 1.27, use \\MediaWiki\\Session\\Token::SUFFIX
58 const EDIT_TOKEN_SUFFIX
= EDIT_TOKEN_SUFFIX
;
61 * @const int Serialized record version.
66 * Maximum items in $mWatchedItems
68 const MAX_WATCHED_ITEMS_CACHE
= 100;
71 * Exclude user options that are set to their default value.
74 const GETOPTIONS_EXCLUDE_DEFAULTS
= 1;
77 * Array of Strings List of member variables which are saved to the
78 * shared cache (memcached). Any operation which changes the
79 * corresponding database fields must call a cache-clearing function.
82 protected static $mCacheVars = array(
90 'mEmailAuthenticated',
97 // user_properties table
102 * Array of Strings Core rights.
103 * Each of these should have a corresponding message of the form
107 protected static $mCoreRights = array(
137 'editusercssjs', # deprecated
150 'move-categorypages',
151 'move-rootuserpages',
155 'override-export-depth',
178 'userrights-interwiki',
186 * String Cached results of getAllRights()
188 protected static $mAllRights = false;
190 /** Cache variables */
200 /** @var string TS_MW timestamp from the DB */
202 /** @var string TS_MW timestamp from cache */
203 protected $mQuickTouched;
207 public $mEmailAuthenticated;
209 protected $mEmailToken;
211 protected $mEmailTokenExpires;
213 protected $mRegistration;
215 protected $mEditCount;
219 protected $mOptionOverrides;
223 * Bool Whether the cache variables have been loaded.
226 public $mOptionsLoaded;
229 * Array with already loaded items or true if all items have been loaded.
231 protected $mLoadedItems = array();
235 * String Initialization data source if mLoadedItems!==true. May be one of:
236 * - 'defaults' anonymous user initialised from class defaults
237 * - 'name' initialise from mName
238 * - 'id' initialise from mId
239 * - 'session' log in from session if possible
241 * Use the User::newFrom*() family of functions to set this.
246 * Lazy-initialized variables, invalidated with clearInstanceCache
250 protected $mDatePreference;
258 protected $mBlockreason;
260 protected $mEffectiveGroups;
262 protected $mImplicitGroups;
264 protected $mFormerGroups;
266 protected $mBlockedGlobally;
283 protected $mAllowUsertalk;
286 private $mBlockedFromCreateAccount = false;
289 private $mWatchedItems = array();
291 /** @var integer User::READ_* constant bitfield used to load data */
292 protected $queryFlagsUsed = self
::READ_NORMAL
;
294 public static $idCacheByName = array();
297 * Lightweight constructor for an anonymous user.
298 * Use the User::newFrom* factory functions for other kinds of users.
302 * @see newFromConfirmationCode()
303 * @see newFromSession()
306 public function __construct() {
307 $this->clearInstanceCache( 'defaults' );
313 public function __toString() {
314 return $this->getName();
318 * Load the user table data for this object from the source given by mFrom.
320 * @param integer $flags User::READ_* constant bitfield
322 public function load( $flags = self
::READ_NORMAL
) {
323 global $wgFullyInitialised;
325 if ( $this->mLoadedItems
=== true ) {
329 // Set it now to avoid infinite recursion in accessors
330 $oldLoadedItems = $this->mLoadedItems
;
331 $this->mLoadedItems
= true;
332 $this->queryFlagsUsed
= $flags;
334 // If this is called too early, things are likely to break.
335 if ( $this->mFrom
=== 'session' && empty( $wgFullyInitialised ) ) {
336 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
337 ->warning( 'User::loadFromSession called before the end of Setup.php', array(
338 'exception' => new Exception( 'User::loadFromSession called before the end of Setup.php' ),
340 $this->loadDefaults();
341 $this->mLoadedItems
= $oldLoadedItems;
345 switch ( $this->mFrom
) {
347 $this->loadDefaults();
350 // Make sure this thread sees its own changes
351 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
352 $flags |
= self
::READ_LATEST
;
353 $this->queryFlagsUsed
= $flags;
356 $this->mId
= self
::idFromName( $this->mName
, $flags );
358 // Nonexistent user placeholder object
359 $this->loadDefaults( $this->mName
);
361 $this->loadFromId( $flags );
365 $this->loadFromId( $flags );
368 if ( !$this->loadFromSession() ) {
369 // Loading from session failed. Load defaults.
370 $this->loadDefaults();
372 Hooks
::run( 'UserLoadAfterLoadFromSession', array( $this ) );
375 throw new UnexpectedValueException(
376 "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
381 * Load user table data, given mId has already been set.
382 * @param integer $flags User::READ_* constant bitfield
383 * @return bool False if the ID does not exist, true otherwise
385 public function loadFromId( $flags = self
::READ_NORMAL
) {
386 if ( $this->mId
== 0 ) {
387 $this->loadDefaults();
391 // Try cache (unless this needs data from the master DB).
392 // NOTE: if this thread called saveSettings(), the cache was cleared.
393 $latest = DBAccessObjectUtils
::hasFlags( $flags, self
::READ_LATEST
);
394 if ( $latest ||
!$this->loadFromCache() ) {
395 wfDebug( "User: cache miss for user {$this->mId}\n" );
396 // Load from DB (make sure this thread sees its own changes)
397 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
398 $flags |
= self
::READ_LATEST
;
400 if ( !$this->loadFromDatabase( $flags ) ) {
401 // Can't load from ID, user is anonymous
404 $this->saveToCache();
407 $this->mLoadedItems
= true;
408 $this->queryFlagsUsed
= $flags;
415 * @param string $wikiId
416 * @param integer $userId
418 public static function purge( $wikiId, $userId ) {
419 $cache = ObjectCache
::getMainWANInstance();
420 $cache->delete( $cache->makeGlobalKey( 'user', 'id', $wikiId, $userId ) );
425 * @param WANObjectCache $cache
428 protected function getCacheKey( WANObjectCache
$cache ) {
429 return $cache->makeGlobalKey( 'user', 'id', wfWikiID(), $this->mId
);
433 * Load user data from shared cache, given mId has already been set.
435 * @return bool false if the ID does not exist or data is invalid, true otherwise
438 protected function loadFromCache() {
439 if ( $this->mId
== 0 ) {
440 $this->loadDefaults();
444 $cache = ObjectCache
::getMainWANInstance();
445 $data = $cache->get( $this->getCacheKey( $cache ) );
446 if ( !is_array( $data ) ||
$data['mVersion'] < self
::VERSION
) {
451 wfDebug( "User: got user {$this->mId} from cache\n" );
453 // Restore from cache
454 foreach ( self
::$mCacheVars as $name ) {
455 $this->$name = $data[$name];
462 * Save user data to the shared cache
464 * This method should not be called outside the User class
466 public function saveToCache() {
469 $this->loadOptions();
471 if ( $this->isAnon() ) {
472 // Anonymous users are uncached
477 foreach ( self
::$mCacheVars as $name ) {
478 $data[$name] = $this->$name;
480 $data['mVersion'] = self
::VERSION
;
481 $opts = Database
::getCacheSetOptions( wfGetDB( DB_SLAVE
) );
483 $cache = ObjectCache
::getMainWANInstance();
484 $key = $this->getCacheKey( $cache );
485 $cache->set( $key, $data, $cache::TTL_HOUR
, $opts );
488 /** @name newFrom*() static factory methods */
492 * Static factory method for creation from username.
494 * This is slightly less efficient than newFromId(), so use newFromId() if
495 * you have both an ID and a name handy.
497 * @param string $name Username, validated by Title::newFromText()
498 * @param string|bool $validate Validate username. Takes the same parameters as
499 * User::getCanonicalName(), except that true is accepted as an alias
500 * for 'valid', for BC.
502 * @return User|bool User object, or false if the username is invalid
503 * (e.g. if it contains illegal characters or is an IP address). If the
504 * username is not present in the database, the result will be a user object
505 * with a name, zero user ID and default settings.
507 public static function newFromName( $name, $validate = 'valid' ) {
508 if ( $validate === true ) {
511 $name = self
::getCanonicalName( $name, $validate );
512 if ( $name === false ) {
515 // Create unloaded user object
519 $u->setItemLoaded( 'name' );
525 * Static factory method for creation from a given user ID.
527 * @param int $id Valid user ID
528 * @return User The corresponding User object
530 public static function newFromId( $id ) {
534 $u->setItemLoaded( 'id' );
539 * Factory method to fetch whichever user has a given email confirmation code.
540 * This code is generated when an account is created or its e-mail address
543 * If the code is invalid or has expired, returns NULL.
545 * @param string $code Confirmation code
546 * @param int $flags User::READ_* bitfield
549 public static function newFromConfirmationCode( $code, $flags = 0 ) {
550 $db = ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
551 ?
wfGetDB( DB_MASTER
)
552 : wfGetDB( DB_SLAVE
);
554 $id = $db->selectField(
558 'user_email_token' => md5( $code ),
559 'user_email_token_expires > ' . $db->addQuotes( $db->timestamp() ),
563 return $id ? User
::newFromId( $id ) : null;
567 * Create a new user object using data from session. If the login
568 * credentials are invalid, the result is an anonymous user.
570 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
573 public static function newFromSession( WebRequest
$request = null ) {
575 $user->mFrom
= 'session';
576 $user->mRequest
= $request;
581 * Create a new user object from a user row.
582 * The row should have the following fields from the user table in it:
583 * - either user_name or user_id to load further data if needed (or both)
585 * - all other fields (email, etc.)
586 * It is useless to provide the remaining fields if either user_id,
587 * user_name and user_real_name are not provided because the whole row
588 * will be loaded once more from the database when accessing them.
590 * @param stdClass $row A row from the user table
591 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
594 public static function newFromRow( $row, $data = null ) {
596 $user->loadFromRow( $row, $data );
601 * Static factory method for creation of a "system" user from username.
603 * A "system" user is an account that's used to attribute logged actions
604 * taken by MediaWiki itself, as opposed to a bot or human user. Examples
605 * might include the 'Maintenance script' or 'Conversion script' accounts
606 * used by various scripts in the maintenance/ directory or accounts such
607 * as 'MediaWiki message delivery' used by the MassMessage extension.
609 * This can optionally create the user if it doesn't exist, and "steal" the
610 * account if it does exist.
612 * @param string $name Username
613 * @param array $options Options are:
614 * - validate: As for User::getCanonicalName(), default 'valid'
615 * - create: Whether to create the user if it doesn't already exist, default true
616 * - steal: Whether to reset the account's password and email if it
617 * already exists, default false
620 public static function newSystemUser( $name, $options = array() ) {
622 'validate' => 'valid',
627 $name = self
::getCanonicalName( $name, $options['validate'] );
628 if ( $name === false ) {
632 $dbw = wfGetDB( DB_MASTER
);
633 $row = $dbw->selectRow(
636 self
::selectFields(),
637 array( 'user_password', 'user_newpassword' )
639 array( 'user_name' => $name ),
643 // No user. Create it?
644 return $options['create'] ? self
::createNew( $name ) : null;
646 $user = self
::newFromRow( $row );
648 // A user is considered to exist as a non-system user if it has a
649 // password set, or a temporary password set, or an email set, or a
650 // non-invalid token.
651 $passwordFactory = new PasswordFactory();
652 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
654 $password = $passwordFactory->newFromCiphertext( $row->user_password
);
655 } catch ( PasswordError
$e ) {
656 wfDebug( 'Invalid password hash found in database.' );
657 $password = PasswordFactory
::newInvalidPassword();
660 $newpassword = $passwordFactory->newFromCiphertext( $row->user_newpassword
);
661 } catch ( PasswordError
$e ) {
662 wfDebug( 'Invalid password hash found in database.' );
663 $newpassword = PasswordFactory
::newInvalidPassword();
665 if ( !$password instanceof InvalidPassword ||
!$newpassword instanceof InvalidPassword
666 ||
$user->mEmail ||
$user->mToken
!== self
::INVALID_TOKEN
668 // User exists. Steal it?
669 if ( !$options['steal'] ) {
673 $nopass = PasswordFactory
::newInvalidPassword()->toString();
678 'user_password' => $nopass,
679 'user_newpassword' => $nopass,
680 'user_newpass_time' => null,
682 array( 'user_id' => $user->getId() ),
685 $user->invalidateEmail();
686 $user->mToken
= self
::INVALID_TOKEN
;
687 $user->saveSettings();
688 SessionManager
::singleton()->preventSessionsForUser( $user->getName() );
697 * Get the username corresponding to a given user ID
698 * @param int $id User ID
699 * @return string|bool The corresponding username
701 public static function whoIs( $id ) {
702 return UserCache
::singleton()->getProp( $id, 'name' );
706 * Get the real name of a user given their user ID
708 * @param int $id User ID
709 * @return string|bool The corresponding user's real name
711 public static function whoIsReal( $id ) {
712 return UserCache
::singleton()->getProp( $id, 'real_name' );
716 * Get database id given a user name
717 * @param string $name Username
718 * @param integer $flags User::READ_* constant bitfield
719 * @return int|null The corresponding user's ID, or null if user is nonexistent
721 public static function idFromName( $name, $flags = self
::READ_NORMAL
) {
722 $nt = Title
::makeTitleSafe( NS_USER
, $name );
723 if ( is_null( $nt ) ) {
728 if ( !( $flags & self
::READ_LATEST
) && isset( self
::$idCacheByName[$name] ) ) {
729 return self
::$idCacheByName[$name];
732 $db = ( $flags & self
::READ_LATEST
)
733 ?
wfGetDB( DB_MASTER
)
734 : wfGetDB( DB_SLAVE
);
739 array( 'user_name' => $nt->getText() ),
743 if ( $s === false ) {
746 $result = $s->user_id
;
749 self
::$idCacheByName[$name] = $result;
751 if ( count( self
::$idCacheByName ) > 1000 ) {
752 self
::$idCacheByName = array();
759 * Reset the cache used in idFromName(). For use in tests.
761 public static function resetIdByNameCache() {
762 self
::$idCacheByName = array();
766 * Does the string match an anonymous IPv4 address?
768 * This function exists for username validation, in order to reject
769 * usernames which are similar in form to IP addresses. Strings such
770 * as 300.300.300.300 will return true because it looks like an IP
771 * address, despite not being strictly valid.
773 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
774 * address because the usemod software would "cloak" anonymous IP
775 * addresses like this, if we allowed accounts like this to be created
776 * new users could get the old edits of these anonymous users.
778 * @param string $name Name to match
781 public static function isIP( $name ) {
782 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
783 || IP
::isIPv6( $name );
787 * Is the input a valid username?
789 * Checks if the input is a valid username, we don't want an empty string,
790 * an IP address, anything that contains slashes (would mess up subpages),
791 * is longer than the maximum allowed username size or doesn't begin with
794 * @param string $name Name to match
797 public static function isValidUserName( $name ) {
798 global $wgContLang, $wgMaxNameChars;
801 || User
::isIP( $name )
802 ||
strpos( $name, '/' ) !== false
803 ||
strlen( $name ) > $wgMaxNameChars
804 ||
$name != $wgContLang->ucfirst( $name )
806 wfDebugLog( 'username', __METHOD__
.
807 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
811 // Ensure that the name can't be misresolved as a different title,
812 // such as with extra namespace keys at the start.
813 $parsed = Title
::newFromText( $name );
814 if ( is_null( $parsed )
815 ||
$parsed->getNamespace()
816 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
817 wfDebugLog( 'username', __METHOD__
.
818 ": '$name' invalid due to ambiguous prefixes" );
822 // Check an additional blacklist of troublemaker characters.
823 // Should these be merged into the title char list?
824 $unicodeBlacklist = '/[' .
825 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
826 '\x{00a0}' . # non-breaking space
827 '\x{2000}-\x{200f}' . # various whitespace
828 '\x{2028}-\x{202f}' . # breaks and control chars
829 '\x{3000}' . # ideographic space
830 '\x{e000}-\x{f8ff}' . # private use
832 if ( preg_match( $unicodeBlacklist, $name ) ) {
833 wfDebugLog( 'username', __METHOD__
.
834 ": '$name' invalid due to blacklisted characters" );
842 * Usernames which fail to pass this function will be blocked
843 * from user login and new account registrations, but may be used
844 * internally by batch processes.
846 * If an account already exists in this form, login will be blocked
847 * by a failure to pass this function.
849 * @param string $name Name to match
852 public static function isUsableName( $name ) {
853 global $wgReservedUsernames;
854 // Must be a valid username, obviously ;)
855 if ( !self
::isValidUserName( $name ) ) {
859 static $reservedUsernames = false;
860 if ( !$reservedUsernames ) {
861 $reservedUsernames = $wgReservedUsernames;
862 Hooks
::run( 'UserGetReservedNames', array( &$reservedUsernames ) );
865 // Certain names may be reserved for batch processes.
866 foreach ( $reservedUsernames as $reserved ) {
867 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
868 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
870 if ( $reserved == $name ) {
878 * Usernames which fail to pass this function will be blocked
879 * from new account registrations, but may be used internally
880 * either by batch processes or by user accounts which have
881 * already been created.
883 * Additional blacklisting may be added here rather than in
884 * isValidUserName() to avoid disrupting existing accounts.
886 * @param string $name String to match
889 public static function isCreatableName( $name ) {
890 global $wgInvalidUsernameCharacters;
892 // Ensure that the username isn't longer than 235 bytes, so that
893 // (at least for the builtin skins) user javascript and css files
894 // will work. (bug 23080)
895 if ( strlen( $name ) > 235 ) {
896 wfDebugLog( 'username', __METHOD__
.
897 ": '$name' invalid due to length" );
901 // Preg yells if you try to give it an empty string
902 if ( $wgInvalidUsernameCharacters !== '' ) {
903 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
904 wfDebugLog( 'username', __METHOD__
.
905 ": '$name' invalid due to wgInvalidUsernameCharacters" );
910 return self
::isUsableName( $name );
914 * Is the input a valid password for this user?
916 * @param string $password Desired password
919 public function isValidPassword( $password ) {
920 // simple boolean wrapper for getPasswordValidity
921 return $this->getPasswordValidity( $password ) === true;
925 * Given unvalidated password input, return error message on failure.
927 * @param string $password Desired password
928 * @return bool|string|array True on success, string or array of error message on failure
930 public function getPasswordValidity( $password ) {
931 $result = $this->checkPasswordValidity( $password );
932 if ( $result->isGood() ) {
936 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
937 $messages[] = $error['message'];
939 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
940 $messages[] = $warning['message'];
942 if ( count( $messages ) === 1 ) {
950 * Check if this is a valid password for this user
952 * Create a Status object based on the password's validity.
953 * The Status should be set to fatal if the user should not
954 * be allowed to log in, and should have any errors that
955 * would block changing the password.
957 * If the return value of this is not OK, the password
958 * should not be checked. If the return value is not Good,
959 * the password can be checked, but the user should not be
960 * able to set their password to this.
962 * @param string $password Desired password
963 * @param string $purpose one of 'login', 'create', 'reset'
967 public function checkPasswordValidity( $password, $purpose = 'login' ) {
968 global $wgPasswordPolicy;
970 $upp = new UserPasswordPolicy(
971 $wgPasswordPolicy['policies'],
972 $wgPasswordPolicy['checks']
975 $status = Status
::newGood();
976 $result = false; // init $result to false for the internal checks
978 if ( !Hooks
::run( 'isValidPassword', array( $password, &$result, $this ) ) ) {
979 $status->error( $result );
983 if ( $result === false ) {
984 $status->merge( $upp->checkUserPassword( $this, $password, $purpose ) );
986 } elseif ( $result === true ) {
989 $status->error( $result );
990 return $status; // the isValidPassword hook set a string $result and returned true
995 * Given unvalidated user input, return a canonical username, or false if
996 * the username is invalid.
997 * @param string $name User input
998 * @param string|bool $validate Type of validation to use:
999 * - false No validation
1000 * - 'valid' Valid for batch processes
1001 * - 'usable' Valid for batch processes and login
1002 * - 'creatable' Valid for batch processes, login and account creation
1004 * @throws InvalidArgumentException
1005 * @return bool|string
1007 public static function getCanonicalName( $name, $validate = 'valid' ) {
1008 // Force usernames to capital
1010 $name = $wgContLang->ucfirst( $name );
1012 # Reject names containing '#'; these will be cleaned up
1013 # with title normalisation, but then it's too late to
1015 if ( strpos( $name, '#' ) !== false ) {
1019 // Clean up name according to title rules,
1020 // but only when validation is requested (bug 12654)
1021 $t = ( $validate !== false ) ?
1022 Title
::newFromText( $name ) : Title
::makeTitle( NS_USER
, $name );
1023 // Check for invalid titles
1024 if ( is_null( $t ) ) {
1028 // Reject various classes of invalid names
1030 $name = $wgAuth->getCanonicalName( $t->getText() );
1032 switch ( $validate ) {
1036 if ( !User
::isValidUserName( $name ) ) {
1041 if ( !User
::isUsableName( $name ) ) {
1046 if ( !User
::isCreatableName( $name ) ) {
1051 throw new InvalidArgumentException(
1052 'Invalid parameter value for $validate in ' . __METHOD__
);
1058 * Count the number of edits of a user
1060 * @param int $uid User ID to check
1061 * @return int The user's edit count
1063 * @deprecated since 1.21 in favour of User::getEditCount
1065 public static function edits( $uid ) {
1066 wfDeprecated( __METHOD__
, '1.21' );
1067 $user = self
::newFromId( $uid );
1068 return $user->getEditCount();
1072 * Return a random password.
1074 * @deprecated since 1.27, use PasswordFactory::generateRandomPasswordString()
1075 * @return string New random password
1077 public static function randomPassword() {
1078 global $wgMinimalPasswordLength;
1079 return PasswordFactory
::generateRandomPasswordString( $wgMinimalPasswordLength );
1083 * Set cached properties to default.
1085 * @note This no longer clears uncached lazy-initialised properties;
1086 * the constructor does that instead.
1088 * @param string|bool $name
1090 public function loadDefaults( $name = false ) {
1092 $this->mName
= $name;
1093 $this->mRealName
= '';
1095 $this->mOptionOverrides
= null;
1096 $this->mOptionsLoaded
= false;
1098 $loggedOut = $this->mRequest ?
$this->mRequest
->getSession()->getLoggedOutTimestamp() : 0;
1099 if ( $loggedOut !== 0 ) {
1100 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1102 $this->mTouched
= '1'; # Allow any pages to be cached
1105 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1106 $this->mEmailAuthenticated
= null;
1107 $this->mEmailToken
= '';
1108 $this->mEmailTokenExpires
= null;
1109 $this->mRegistration
= wfTimestamp( TS_MW
);
1110 $this->mGroups
= array();
1112 Hooks
::run( 'UserLoadDefaults', array( $this, $name ) );
1116 * Return whether an item has been loaded.
1118 * @param string $item Item to check. Current possibilities:
1122 * @param string $all 'all' to check if the whole object has been loaded
1123 * or any other string to check if only the item is available (e.g.
1127 public function isItemLoaded( $item, $all = 'all' ) {
1128 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1129 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1133 * Set that an item has been loaded
1135 * @param string $item
1137 protected function setItemLoaded( $item ) {
1138 if ( is_array( $this->mLoadedItems
) ) {
1139 $this->mLoadedItems
[$item] = true;
1144 * Load user data from the session.
1146 * @return bool True if the user is logged in, false otherwise.
1148 private function loadFromSession() {
1151 Hooks
::run( 'UserLoadFromSession', array( $this, &$result ), '1.27' );
1152 if ( $result !== null ) {
1156 // MediaWiki\Session\Session already did the necessary authentication of the user
1157 // returned here, so just use it if applicable.
1158 $session = $this->getRequest()->getSession();
1159 $user = $session->getUser();
1160 if ( $user->isLoggedIn() ) {
1161 $this->loadFromUserObject( $user );
1162 // Other code expects these to be set in the session, so set them.
1163 $session->set( 'wsUserID', $this->getId() );
1164 $session->set( 'wsUserName', $this->getName() );
1165 $session->set( 'wsToken', $this->getToken() );
1173 * Load user and user_group data from the database.
1174 * $this->mId must be set, this is how the user is identified.
1176 * @param integer $flags User::READ_* constant bitfield
1177 * @return bool True if the user exists, false if the user is anonymous
1179 public function loadFromDatabase( $flags = self
::READ_LATEST
) {
1181 $this->mId
= intval( $this->mId
);
1184 if ( !$this->mId
) {
1185 $this->loadDefaults();
1189 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
1190 $db = wfGetDB( $index );
1192 $s = $db->selectRow(
1194 self
::selectFields(),
1195 array( 'user_id' => $this->mId
),
1200 $this->queryFlagsUsed
= $flags;
1201 Hooks
::run( 'UserLoadFromDatabase', array( $this, &$s ) );
1203 if ( $s !== false ) {
1204 // Initialise user table data
1205 $this->loadFromRow( $s );
1206 $this->mGroups
= null; // deferred
1207 $this->getEditCount(); // revalidation for nulls
1212 $this->loadDefaults();
1218 * Initialize this object from a row from the user table.
1220 * @param stdClass $row Row from the user table to load.
1221 * @param array $data Further user data to load into the object
1223 * user_groups Array with groups out of the user_groups table
1224 * user_properties Array with properties out of the user_properties table
1226 protected function loadFromRow( $row, $data = null ) {
1229 $this->mGroups
= null; // deferred
1231 if ( isset( $row->user_name
) ) {
1232 $this->mName
= $row->user_name
;
1233 $this->mFrom
= 'name';
1234 $this->setItemLoaded( 'name' );
1239 if ( isset( $row->user_real_name
) ) {
1240 $this->mRealName
= $row->user_real_name
;
1241 $this->setItemLoaded( 'realname' );
1246 if ( isset( $row->user_id
) ) {
1247 $this->mId
= intval( $row->user_id
);
1248 $this->mFrom
= 'id';
1249 $this->setItemLoaded( 'id' );
1254 if ( isset( $row->user_id
) && isset( $row->user_name
) ) {
1255 self
::$idCacheByName[$row->user_name
] = $row->user_id
;
1258 if ( isset( $row->user_editcount
) ) {
1259 $this->mEditCount
= $row->user_editcount
;
1264 if ( isset( $row->user_touched
) ) {
1265 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1270 if ( isset( $row->user_token
) ) {
1271 // The definition for the column is binary(32), so trim the NULs
1272 // that appends. The previous definition was char(32), so trim
1274 $this->mToken
= rtrim( $row->user_token
, " \0" );
1275 if ( $this->mToken
=== '' ) {
1276 $this->mToken
= null;
1282 if ( isset( $row->user_email
) ) {
1283 $this->mEmail
= $row->user_email
;
1284 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1285 $this->mEmailToken
= $row->user_email_token
;
1286 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1287 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1293 $this->mLoadedItems
= true;
1296 if ( is_array( $data ) ) {
1297 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1298 $this->mGroups
= $data['user_groups'];
1300 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1301 $this->loadOptions( $data['user_properties'] );
1307 * Load the data for this user object from another user object.
1311 protected function loadFromUserObject( $user ) {
1313 $user->loadGroups();
1314 $user->loadOptions();
1315 foreach ( self
::$mCacheVars as $var ) {
1316 $this->$var = $user->$var;
1321 * Load the groups from the database if they aren't already loaded.
1323 private function loadGroups() {
1324 if ( is_null( $this->mGroups
) ) {
1325 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
1326 ?
wfGetDB( DB_MASTER
)
1327 : wfGetDB( DB_SLAVE
);
1328 $res = $db->select( 'user_groups',
1329 array( 'ug_group' ),
1330 array( 'ug_user' => $this->mId
),
1332 $this->mGroups
= array();
1333 foreach ( $res as $row ) {
1334 $this->mGroups
[] = $row->ug_group
;
1340 * Add the user to the group if he/she meets given criteria.
1342 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1343 * possible to remove manually via Special:UserRights. In such case it
1344 * will not be re-added automatically. The user will also not lose the
1345 * group if they no longer meet the criteria.
1347 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1349 * @return array Array of groups the user has been promoted to.
1351 * @see $wgAutopromoteOnce
1353 public function addAutopromoteOnceGroups( $event ) {
1354 global $wgAutopromoteOnceLogInRC, $wgAuth;
1356 if ( wfReadOnly() ||
!$this->getId() ) {
1360 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1361 if ( !count( $toPromote ) ) {
1365 if ( !$this->checkAndSetTouched() ) {
1366 return array(); // raced out (bug T48834)
1369 $oldGroups = $this->getGroups(); // previous groups
1370 foreach ( $toPromote as $group ) {
1371 $this->addGroup( $group );
1373 // update groups in external authentication database
1374 Hooks
::run( 'UserGroupsChanged', array( $this, $toPromote, array(), false ) );
1375 $wgAuth->updateExternalDBGroups( $this, $toPromote );
1377 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1379 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1380 $logEntry->setPerformer( $this );
1381 $logEntry->setTarget( $this->getUserPage() );
1382 $logEntry->setParameters( array(
1383 '4::oldgroups' => $oldGroups,
1384 '5::newgroups' => $newGroups,
1386 $logid = $logEntry->insert();
1387 if ( $wgAutopromoteOnceLogInRC ) {
1388 $logEntry->publish( $logid );
1395 * Bump user_touched if it didn't change since this object was loaded
1397 * On success, the mTouched field is updated.
1398 * The user serialization cache is always cleared.
1400 * @return bool Whether user_touched was actually updated
1403 protected function checkAndSetTouched() {
1406 if ( !$this->mId
) {
1407 return false; // anon
1410 // Get a new user_touched that is higher than the old one
1411 $oldTouched = $this->mTouched
;
1412 $newTouched = $this->newTouchedTimestamp();
1414 $dbw = wfGetDB( DB_MASTER
);
1415 $dbw->update( 'user',
1416 array( 'user_touched' => $dbw->timestamp( $newTouched ) ),
1418 'user_id' => $this->mId
,
1419 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
1423 $success = ( $dbw->affectedRows() > 0 );
1426 $this->mTouched
= $newTouched;
1427 $this->clearSharedCache();
1429 // Clears on failure too since that is desired if the cache is stale
1430 $this->clearSharedCache( 'refresh' );
1437 * Clear various cached data stored in this object. The cache of the user table
1438 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1440 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1441 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1443 public function clearInstanceCache( $reloadFrom = false ) {
1444 $this->mNewtalk
= -1;
1445 $this->mDatePreference
= null;
1446 $this->mBlockedby
= -1; # Unset
1447 $this->mHash
= false;
1448 $this->mRights
= null;
1449 $this->mEffectiveGroups
= null;
1450 $this->mImplicitGroups
= null;
1451 $this->mGroups
= null;
1452 $this->mOptions
= null;
1453 $this->mOptionsLoaded
= false;
1454 $this->mEditCount
= null;
1456 if ( $reloadFrom ) {
1457 $this->mLoadedItems
= array();
1458 $this->mFrom
= $reloadFrom;
1463 * Combine the language default options with any site-specific options
1464 * and add the default language variants.
1466 * @return array Array of String options
1468 public static function getDefaultOptions() {
1469 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1471 static $defOpt = null;
1472 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1473 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1474 // mid-request and see that change reflected in the return value of this function.
1475 // Which is insane and would never happen during normal MW operation
1479 $defOpt = $wgDefaultUserOptions;
1480 // Default language setting
1481 $defOpt['language'] = $wgContLang->getCode();
1482 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1483 $defOpt[$langCode == $wgContLang->getCode() ?
'variant' : "variant-$langCode"] = $langCode;
1485 foreach ( SearchEngine
::searchableNamespaces() as $nsnum => $nsname ) {
1486 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1488 $defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1490 Hooks
::run( 'UserGetDefaultOptions', array( &$defOpt ) );
1496 * Get a given default option value.
1498 * @param string $opt Name of option to retrieve
1499 * @return string Default option value
1501 public static function getDefaultOption( $opt ) {
1502 $defOpts = self
::getDefaultOptions();
1503 if ( isset( $defOpts[$opt] ) ) {
1504 return $defOpts[$opt];
1511 * Get blocking information
1512 * @param bool $bFromSlave Whether to check the slave database first.
1513 * To improve performance, non-critical checks are done against slaves.
1514 * Check when actually saving should be done against master.
1516 private function getBlockedStatus( $bFromSlave = true ) {
1517 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1519 if ( -1 != $this->mBlockedby
) {
1523 wfDebug( __METHOD__
. ": checking...\n" );
1525 // Initialize data...
1526 // Otherwise something ends up stomping on $this->mBlockedby when
1527 // things get lazy-loaded later, causing false positive block hits
1528 // due to -1 !== 0. Probably session-related... Nothing should be
1529 // overwriting mBlockedby, surely?
1532 # We only need to worry about passing the IP address to the Block generator if the
1533 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1534 # know which IP address they're actually coming from
1535 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->equals( $wgUser ) ) {
1536 $ip = $this->getRequest()->getIP();
1542 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1545 if ( !$block instanceof Block
&& $ip !== null && !in_array( $ip, $wgProxyWhitelist ) ) {
1547 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1549 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1550 $block->mReason
= wfMessage( 'proxyblockreason' )->text();
1551 $block->setTarget( $ip );
1552 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1554 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1555 $block->mReason
= wfMessage( 'sorbsreason' )->text();
1556 $block->setTarget( $ip );
1560 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1561 if ( !$block instanceof Block
1562 && $wgApplyIpBlocksToXff
1564 && !in_array( $ip, $wgProxyWhitelist )
1566 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1567 $xff = array_map( 'trim', explode( ',', $xff ) );
1568 $xff = array_diff( $xff, array( $ip ) );
1569 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1570 $block = Block
::chooseBlock( $xffblocks, $xff );
1571 if ( $block instanceof Block
) {
1572 # Mangle the reason to alert the user that the block
1573 # originated from matching the X-Forwarded-For header.
1574 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->text();
1578 if ( $block instanceof Block
) {
1579 wfDebug( __METHOD__
. ": Found block.\n" );
1580 $this->mBlock
= $block;
1581 $this->mBlockedby
= $block->getByName();
1582 $this->mBlockreason
= $block->mReason
;
1583 $this->mHideName
= $block->mHideName
;
1584 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1586 $this->mBlockedby
= '';
1587 $this->mHideName
= 0;
1588 $this->mAllowUsertalk
= false;
1592 Hooks
::run( 'GetBlockedStatus', array( &$this ) );
1597 * Whether the given IP is in a DNS blacklist.
1599 * @param string $ip IP to check
1600 * @param bool $checkWhitelist Whether to check the whitelist first
1601 * @return bool True if blacklisted.
1603 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1604 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1606 if ( !$wgEnableDnsBlacklist ) {
1610 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1614 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1618 * Whether the given IP is in a given DNS blacklist.
1620 * @param string $ip IP to check
1621 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1622 * @return bool True if blacklisted.
1624 public function inDnsBlacklist( $ip, $bases ) {
1627 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1628 if ( IP
::isIPv4( $ip ) ) {
1629 // Reverse IP, bug 21255
1630 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1632 foreach ( (array)$bases as $base ) {
1634 // If we have an access key, use that too (ProjectHoneypot, etc.)
1636 if ( is_array( $base ) ) {
1637 if ( count( $base ) >= 2 ) {
1638 // Access key is 1, base URL is 0
1639 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1641 $host = "$ipReversed.{$base[0]}";
1643 $basename = $base[0];
1645 $host = "$ipReversed.$base";
1649 $ipList = gethostbynamel( $host );
1652 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
1656 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
1665 * Check if an IP address is in the local proxy list
1671 public static function isLocallyBlockedProxy( $ip ) {
1672 global $wgProxyList;
1674 if ( !$wgProxyList ) {
1678 if ( !is_array( $wgProxyList ) ) {
1679 // Load from the specified file
1680 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1683 if ( !is_array( $wgProxyList ) ) {
1685 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1687 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1688 // Old-style flipped proxy list
1697 * Is this user subject to rate limiting?
1699 * @return bool True if rate limited
1701 public function isPingLimitable() {
1702 global $wgRateLimitsExcludedIPs;
1703 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1704 // No other good way currently to disable rate limits
1705 // for specific IPs. :P
1706 // But this is a crappy hack and should die.
1709 return !$this->isAllowed( 'noratelimit' );
1713 * Primitive rate limits: enforce maximum actions per time period
1714 * to put a brake on flooding.
1716 * The method generates both a generic profiling point and a per action one
1717 * (suffix being "-$action".
1719 * @note When using a shared cache like memcached, IP-address
1720 * last-hit counters will be shared across wikis.
1722 * @param string $action Action to enforce; 'edit' if unspecified
1723 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1724 * @return bool True if a rate limiter was tripped
1726 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1727 // Call the 'PingLimiter' hook
1729 if ( !Hooks
::run( 'PingLimiter', array( &$this, $action, &$result, $incrBy ) ) ) {
1733 global $wgRateLimits;
1734 if ( !isset( $wgRateLimits[$action] ) ) {
1738 // Some groups shouldn't trigger the ping limiter, ever
1739 if ( !$this->isPingLimitable() ) {
1743 $limits = $wgRateLimits[$action];
1745 $id = $this->getId();
1748 if ( isset( $limits['anon'] ) && $id == 0 ) {
1749 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1752 if ( isset( $limits['user'] ) && $id != 0 ) {
1753 $userLimit = $limits['user'];
1755 if ( $this->isNewbie() ) {
1756 if ( isset( $limits['newbie'] ) && $id != 0 ) {
1757 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1759 if ( isset( $limits['ip'] ) ) {
1760 $ip = $this->getRequest()->getIP();
1761 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1763 if ( isset( $limits['subnet'] ) ) {
1764 $ip = $this->getRequest()->getIP();
1767 if ( IP
::isIPv6( $ip ) ) {
1768 $parts = IP
::parseRange( "$ip/64" );
1769 $subnet = $parts[0];
1770 } elseif ( preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1772 $subnet = $matches[1];
1774 if ( $subnet !== false ) {
1775 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1779 // Check for group-specific permissions
1780 // If more than one group applies, use the group with the highest limit
1781 foreach ( $this->getGroups() as $group ) {
1782 if ( isset( $limits[$group] ) ) {
1783 if ( $userLimit === false
1784 ||
$limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1786 $userLimit = $limits[$group];
1790 // Set the user limit key
1791 if ( $userLimit !== false ) {
1792 list( $max, $period ) = $userLimit;
1793 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
1794 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1797 $cache = ObjectCache
::getLocalClusterInstance();
1800 foreach ( $keys as $key => $limit ) {
1801 list( $max, $period ) = $limit;
1802 $summary = "(limit $max in {$period}s)";
1803 $count = $cache->get( $key );
1806 if ( $count >= $max ) {
1807 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1808 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1811 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1814 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1815 if ( $incrBy > 0 ) {
1816 $cache->add( $key, 0, intval( $period ) ); // first ping
1819 if ( $incrBy > 0 ) {
1820 $cache->incr( $key, $incrBy );
1828 * Check if user is blocked
1830 * @param bool $bFromSlave Whether to check the slave database instead of
1831 * the master. Hacked from false due to horrible probs on site.
1832 * @return bool True if blocked, false otherwise
1834 public function isBlocked( $bFromSlave = true ) {
1835 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
1839 * Get the block affecting the user, or null if the user is not blocked
1841 * @param bool $bFromSlave Whether to check the slave database instead of the master
1842 * @return Block|null
1844 public function getBlock( $bFromSlave = true ) {
1845 $this->getBlockedStatus( $bFromSlave );
1846 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
1850 * Check if user is blocked from editing a particular article
1852 * @param Title $title Title to check
1853 * @param bool $bFromSlave Whether to check the slave database instead of the master
1856 public function isBlockedFrom( $title, $bFromSlave = false ) {
1857 global $wgBlockAllowsUTEdit;
1859 $blocked = $this->isBlocked( $bFromSlave );
1860 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
1861 // If a user's name is suppressed, they cannot make edits anywhere
1862 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName()
1863 && $title->getNamespace() == NS_USER_TALK
) {
1865 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
1868 Hooks
::run( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1874 * If user is blocked, return the name of the user who placed the block
1875 * @return string Name of blocker
1877 public function blockedBy() {
1878 $this->getBlockedStatus();
1879 return $this->mBlockedby
;
1883 * If user is blocked, return the specified reason for the block
1884 * @return string Blocking reason
1886 public function blockedFor() {
1887 $this->getBlockedStatus();
1888 return $this->mBlockreason
;
1892 * If user is blocked, return the ID for the block
1893 * @return int Block ID
1895 public function getBlockId() {
1896 $this->getBlockedStatus();
1897 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
1901 * Check if user is blocked on all wikis.
1902 * Do not use for actual edit permission checks!
1903 * This is intended for quick UI checks.
1905 * @param string $ip IP address, uses current client if none given
1906 * @return bool True if blocked, false otherwise
1908 public function isBlockedGlobally( $ip = '' ) {
1909 if ( $this->mBlockedGlobally
!== null ) {
1910 return $this->mBlockedGlobally
;
1912 // User is already an IP?
1913 if ( IP
::isIPAddress( $this->getName() ) ) {
1914 $ip = $this->getName();
1916 $ip = $this->getRequest()->getIP();
1919 Hooks
::run( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1920 $this->mBlockedGlobally
= (bool)$blocked;
1921 return $this->mBlockedGlobally
;
1925 * Check if user account is locked
1927 * @return bool True if locked, false otherwise
1929 public function isLocked() {
1930 if ( $this->mLocked
!== null ) {
1931 return $this->mLocked
;
1934 $authUser = $wgAuth->getUserInstance( $this );
1935 $this->mLocked
= (bool)$authUser->isLocked();
1936 Hooks
::run( 'UserIsLocked', array( $this, &$this->mLocked
) );
1937 return $this->mLocked
;
1941 * Check if user account is hidden
1943 * @return bool True if hidden, false otherwise
1945 public function isHidden() {
1946 if ( $this->mHideName
!== null ) {
1947 return $this->mHideName
;
1949 $this->getBlockedStatus();
1950 if ( !$this->mHideName
) {
1952 $authUser = $wgAuth->getUserInstance( $this );
1953 $this->mHideName
= (bool)$authUser->isHidden();
1954 Hooks
::run( 'UserIsHidden', array( $this, &$this->mHideName
) );
1956 return $this->mHideName
;
1960 * Get the user's ID.
1961 * @return int The user's ID; 0 if the user is anonymous or nonexistent
1963 public function getId() {
1964 if ( $this->mId
=== null && $this->mName
!== null && User
::isIP( $this->mName
) ) {
1965 // Special case, we know the user is anonymous
1967 } elseif ( !$this->isItemLoaded( 'id' ) ) {
1968 // Don't load if this was initialized from an ID
1975 * Set the user and reload all fields according to a given ID
1976 * @param int $v User ID to reload
1978 public function setId( $v ) {
1980 $this->clearInstanceCache( 'id' );
1984 * Get the user name, or the IP of an anonymous user
1985 * @return string User's name or IP address
1987 public function getName() {
1988 if ( $this->isItemLoaded( 'name', 'only' ) ) {
1989 // Special case optimisation
1990 return $this->mName
;
1993 if ( $this->mName
=== false ) {
1995 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
1997 return $this->mName
;
2002 * Set the user name.
2004 * This does not reload fields from the database according to the given
2005 * name. Rather, it is used to create a temporary "nonexistent user" for
2006 * later addition to the database. It can also be used to set the IP
2007 * address for an anonymous user to something other than the current
2010 * @note User::newFromName() has roughly the same function, when the named user
2012 * @param string $str New user name to set
2014 public function setName( $str ) {
2016 $this->mName
= $str;
2020 * Get the user's name escaped by underscores.
2021 * @return string Username escaped by underscores.
2023 public function getTitleKey() {
2024 return str_replace( ' ', '_', $this->getName() );
2028 * Check if the user has new messages.
2029 * @return bool True if the user has new messages
2031 public function getNewtalk() {
2034 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2035 if ( $this->mNewtalk
=== -1 ) {
2036 $this->mNewtalk
= false; # reset talk page status
2038 // Check memcached separately for anons, who have no
2039 // entire User object stored in there.
2040 if ( !$this->mId
) {
2041 global $wgDisableAnonTalk;
2042 if ( $wgDisableAnonTalk ) {
2043 // Anon newtalk disabled by configuration.
2044 $this->mNewtalk
= false;
2046 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
2049 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2053 return (bool)$this->mNewtalk
;
2057 * Return the data needed to construct links for new talk page message
2058 * alerts. If there are new messages, this will return an associative array
2059 * with the following data:
2060 * wiki: The database name of the wiki
2061 * link: Root-relative link to the user's talk page
2062 * rev: The last talk page revision that the user has seen or null. This
2063 * is useful for building diff links.
2064 * If there are no new messages, it returns an empty array.
2065 * @note This function was designed to accomodate multiple talk pages, but
2066 * currently only returns a single link and revision.
2069 public function getNewMessageLinks() {
2071 if ( !Hooks
::run( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) ) {
2073 } elseif ( !$this->getNewtalk() ) {
2076 $utp = $this->getTalkPage();
2077 $dbr = wfGetDB( DB_SLAVE
);
2078 // Get the "last viewed rev" timestamp from the oldest message notification
2079 $timestamp = $dbr->selectField( 'user_newtalk',
2080 'MIN(user_last_timestamp)',
2081 $this->isAnon() ?
array( 'user_ip' => $this->getName() ) : array( 'user_id' => $this->getID() ),
2083 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2084 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ) );
2088 * Get the revision ID for the last talk page revision viewed by the talk
2090 * @return int|null Revision ID or null
2092 public function getNewMessageRevisionId() {
2093 $newMessageRevisionId = null;
2094 $newMessageLinks = $this->getNewMessageLinks();
2095 if ( $newMessageLinks ) {
2096 // Note: getNewMessageLinks() never returns more than a single link
2097 // and it is always for the same wiki, but we double-check here in
2098 // case that changes some time in the future.
2099 if ( count( $newMessageLinks ) === 1
2100 && $newMessageLinks[0]['wiki'] === wfWikiID()
2101 && $newMessageLinks[0]['rev']
2103 /** @var Revision $newMessageRevision */
2104 $newMessageRevision = $newMessageLinks[0]['rev'];
2105 $newMessageRevisionId = $newMessageRevision->getId();
2108 return $newMessageRevisionId;
2112 * Internal uncached check for new messages
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 * @return bool True if the user has new messages
2119 protected function checkNewtalk( $field, $id ) {
2120 $dbr = wfGetDB( DB_SLAVE
);
2122 $ok = $dbr->selectField( 'user_newtalk', $field, array( $field => $id ), __METHOD__
);
2124 return $ok !== false;
2128 * Add or update the new messages flag
2129 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2130 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2131 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2132 * @return bool True if successful, false otherwise
2134 protected function updateNewtalk( $field, $id, $curRev = null ) {
2135 // Get timestamp of the talk page revision prior to the current one
2136 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2137 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2138 // Mark the user as having new messages since this revision
2139 $dbw = wfGetDB( DB_MASTER
);
2140 $dbw->insert( 'user_newtalk',
2141 array( $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ),
2144 if ( $dbw->affectedRows() ) {
2145 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2148 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2154 * Clear the new messages flag for the given user
2155 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2156 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2157 * @return bool True if successful, false otherwise
2159 protected function deleteNewtalk( $field, $id ) {
2160 $dbw = wfGetDB( DB_MASTER
);
2161 $dbw->delete( 'user_newtalk',
2162 array( $field => $id ),
2164 if ( $dbw->affectedRows() ) {
2165 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2168 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2174 * Update the 'You have new messages!' status.
2175 * @param bool $val Whether the user has new messages
2176 * @param Revision $curRev New, as yet unseen revision of the user talk
2177 * page. Ignored if null or !$val.
2179 public function setNewtalk( $val, $curRev = null ) {
2180 if ( wfReadOnly() ) {
2185 $this->mNewtalk
= $val;
2187 if ( $this->isAnon() ) {
2189 $id = $this->getName();
2192 $id = $this->getId();
2196 $changed = $this->updateNewtalk( $field, $id, $curRev );
2198 $changed = $this->deleteNewtalk( $field, $id );
2202 $this->invalidateCache();
2207 * Generate a current or new-future timestamp to be stored in the
2208 * user_touched field when we update things.
2209 * @return string Timestamp in TS_MW format
2211 private function newTouchedTimestamp() {
2212 global $wgClockSkewFudge;
2214 $time = wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2215 if ( $this->mTouched
&& $time <= $this->mTouched
) {
2216 $time = wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $this->mTouched
) +
1 );
2223 * Clear user data from memcached
2225 * Use after applying updates to the database; caller's
2226 * responsibility to update user_touched if appropriate.
2228 * Called implicitly from invalidateCache() and saveSettings().
2230 * @param string $mode Use 'refresh' to clear now; otherwise before DB commit
2232 public function clearSharedCache( $mode = 'changed' ) {
2233 if ( !$this->getId() ) {
2237 $cache = ObjectCache
::getMainWANInstance();
2238 $key = $this->getCacheKey( $cache );
2239 if ( $mode === 'refresh' ) {
2240 $cache->delete( $key, 1 );
2242 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle( function() use ( $cache, $key ) {
2243 $cache->delete( $key );
2249 * Immediately touch the user data cache for this account
2251 * Calls touch() and removes account data from memcached
2253 public function invalidateCache() {
2255 $this->clearSharedCache();
2259 * Update the "touched" timestamp for the user
2261 * This is useful on various login/logout events when making sure that
2262 * a browser or proxy that has multiple tenants does not suffer cache
2263 * pollution where the new user sees the old users content. The value
2264 * of getTouched() is checked when determining 304 vs 200 responses.
2265 * Unlike invalidateCache(), this preserves the User object cache and
2266 * avoids database writes.
2270 public function touch() {
2271 $id = $this->getId();
2273 $key = wfMemcKey( 'user-quicktouched', 'id', $id );
2274 ObjectCache
::getMainWANInstance()->touchCheckKey( $key );
2275 $this->mQuickTouched
= null;
2280 * Validate the cache for this account.
2281 * @param string $timestamp A timestamp in TS_MW format
2284 public function validateCache( $timestamp ) {
2285 return ( $timestamp >= $this->getTouched() );
2289 * Get the user touched timestamp
2291 * Use this value only to validate caches via inequalities
2292 * such as in the case of HTTP If-Modified-Since response logic
2294 * @return string TS_MW Timestamp
2296 public function getTouched() {
2300 if ( $this->mQuickTouched
=== null ) {
2301 $key = wfMemcKey( 'user-quicktouched', 'id', $this->mId
);
2302 $cache = ObjectCache
::getMainWANInstance();
2304 $this->mQuickTouched
= wfTimestamp( TS_MW
, $cache->getCheckKeyTime( $key ) );
2307 return max( $this->mTouched
, $this->mQuickTouched
);
2310 return $this->mTouched
;
2314 * Get the user_touched timestamp field (time of last DB updates)
2315 * @return string TS_MW Timestamp
2318 public function getDBTouched() {
2321 return $this->mTouched
;
2325 * @deprecated Removed in 1.27.
2329 public function getPassword() {
2330 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2334 * @deprecated Removed in 1.27.
2338 public function getTemporaryPassword() {
2339 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2343 * Set the password and reset the random token.
2344 * Calls through to authentication plugin if necessary;
2345 * will have no effect if the auth plugin refuses to
2346 * pass the change through or if the legal password
2349 * As a special case, setting the password to null
2350 * wipes it, so the account cannot be logged in until
2351 * a new password is set, for instance via e-mail.
2353 * @deprecated since 1.27. AuthManager is coming.
2354 * @param string $str New password to set
2355 * @throws PasswordError On failure
2358 public function setPassword( $str ) {
2361 if ( $str !== null ) {
2362 if ( !$wgAuth->allowPasswordChange() ) {
2363 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2366 $status = $this->checkPasswordValidity( $str );
2367 if ( !$status->isGood() ) {
2368 throw new PasswordError( $status->getMessage()->text() );
2372 if ( !$wgAuth->setPassword( $this, $str ) ) {
2373 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2377 $this->setOption( 'watchlisttoken', false );
2378 $this->setPasswordInternal( $str );
2384 * Set the password and reset the random token unconditionally.
2386 * @deprecated since 1.27. AuthManager is coming.
2387 * @param string|null $str New password to set or null to set an invalid
2388 * password hash meaning that the user will not be able to log in
2389 * through the web interface.
2391 public function setInternalPassword( $str ) {
2394 if ( $wgAuth->allowSetLocalPassword() ) {
2396 $this->setOption( 'watchlisttoken', false );
2397 $this->setPasswordInternal( $str );
2402 * Actually set the password and such
2403 * @since 1.27 cannot set a password for a user not in the database
2404 * @param string|null $str New password to set or null to set an invalid
2405 * password hash meaning that the user will not be able to log in
2406 * through the web interface.
2408 private function setPasswordInternal( $str ) {
2409 $id = self
::idFromName( $this->getName(), self
::READ_LATEST
);
2411 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2414 $passwordFactory = new PasswordFactory();
2415 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
2416 $dbw = wfGetDB( DB_MASTER
);
2420 'user_password' => $passwordFactory->newFromPlaintext( $str )->toString(),
2421 'user_newpassword' => PasswordFactory
::newInvalidPassword()->toString(),
2422 'user_newpass_time' => $dbw->timestampOrNull( null ),
2430 // When the main password is changed, invalidate all bot passwords too
2431 BotPassword
::invalidateAllPasswordsForUser( $this->getName() );
2435 * Get the user's current token.
2436 * @param bool $forceCreation Force the generation of a new token if the
2437 * user doesn't have one (default=true for backwards compatibility).
2438 * @return string|null Token
2440 public function getToken( $forceCreation = true ) {
2441 global $wgAuthenticationTokenVersion;
2444 if ( !$this->mToken
&& $forceCreation ) {
2448 if ( !$this->mToken
) {
2449 // The user doesn't have a token, return null to indicate that.
2451 } elseif ( $this->mToken
=== self
::INVALID_TOKEN
) {
2452 // We return a random value here so existing token checks are very
2454 return MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2455 } elseif ( $wgAuthenticationTokenVersion === null ) {
2456 // $wgAuthenticationTokenVersion not in use, so return the raw secret
2457 return $this->mToken
;
2459 // $wgAuthenticationTokenVersion in use, so hmac it.
2460 $ret = MWCryptHash
::hmac( $wgAuthenticationTokenVersion, $this->mToken
, false );
2462 // The raw hash can be overly long. Shorten it up.
2463 $len = max( 32, self
::TOKEN_LENGTH
);
2464 if ( strlen( $ret ) < $len ) {
2465 // Should never happen, even md5 is 128 bits
2466 throw new \
UnexpectedValueException( 'Hmac returned less than 128 bits' );
2468 return substr( $ret, -$len );
2473 * Set the random token (used for persistent authentication)
2474 * Called from loadDefaults() among other places.
2476 * @param string|bool $token If specified, set the token to this value
2478 public function setToken( $token = false ) {
2480 if ( $this->mToken
=== self
::INVALID_TOKEN
) {
2481 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
2482 ->debug( __METHOD__
. ": Ignoring attempt to set token for system user \"$this\"" );
2483 } elseif ( !$token ) {
2484 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2486 $this->mToken
= $token;
2491 * Set the password for a password reminder or new account email
2493 * @deprecated since 1.27, AuthManager is coming
2494 * @param string $str New password to set or null to set an invalid
2495 * password hash meaning that the user will not be able to use it
2496 * @param bool $throttle If true, reset the throttle timestamp to the present
2498 public function setNewpassword( $str, $throttle = true ) {
2499 $id = $this->getId();
2501 throw new LogicException( 'Cannot set new password for a user that is not in the database.' );
2504 $dbw = wfGetDB( DB_MASTER
);
2506 $passwordFactory = new PasswordFactory();
2507 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
2509 'user_newpassword' => $passwordFactory->newFromPlaintext( $str )->toString(),
2512 if ( $str === null ) {
2513 $update['user_newpass_time'] = null;
2514 } elseif ( $throttle ) {
2515 $update['user_newpass_time'] = $dbw->timestamp();
2518 $dbw->update( 'user', $update, array( 'user_id' => $id ), __METHOD__
);
2522 * Has password reminder email been sent within the last
2523 * $wgPasswordReminderResendTime hours?
2526 public function isPasswordReminderThrottled() {
2527 global $wgPasswordReminderResendTime;
2529 if ( !$wgPasswordReminderResendTime ) {
2535 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
2536 ?
wfGetDB( DB_MASTER
)
2537 : wfGetDB( DB_SLAVE
);
2538 $newpassTime = $db->selectField(
2540 'user_newpass_time',
2541 array( 'user_id' => $this->getId() ),
2545 if ( $newpassTime === null ) {
2548 $expiry = wfTimestamp( TS_UNIX
, $newpassTime ) +
$wgPasswordReminderResendTime * 3600;
2549 return time() < $expiry;
2553 * Get the user's e-mail address
2554 * @return string User's email address
2556 public function getEmail() {
2558 Hooks
::run( 'UserGetEmail', array( $this, &$this->mEmail
) );
2559 return $this->mEmail
;
2563 * Get the timestamp of the user's e-mail authentication
2564 * @return string TS_MW timestamp
2566 public function getEmailAuthenticationTimestamp() {
2568 Hooks
::run( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
2569 return $this->mEmailAuthenticated
;
2573 * Set the user's e-mail address
2574 * @param string $str New e-mail address
2576 public function setEmail( $str ) {
2578 if ( $str == $this->mEmail
) {
2581 $this->invalidateEmail();
2582 $this->mEmail
= $str;
2583 Hooks
::run( 'UserSetEmail', array( $this, &$this->mEmail
) );
2587 * Set the user's e-mail address and a confirmation mail if needed.
2590 * @param string $str New e-mail address
2593 public function setEmailWithConfirmation( $str ) {
2594 global $wgEnableEmail, $wgEmailAuthentication;
2596 if ( !$wgEnableEmail ) {
2597 return Status
::newFatal( 'emaildisabled' );
2600 $oldaddr = $this->getEmail();
2601 if ( $str === $oldaddr ) {
2602 return Status
::newGood( true );
2605 $this->setEmail( $str );
2607 if ( $str !== '' && $wgEmailAuthentication ) {
2608 // Send a confirmation request to the new address if needed
2609 $type = $oldaddr != '' ?
'changed' : 'set';
2610 $result = $this->sendConfirmationMail( $type );
2611 if ( $result->isGood() ) {
2612 // Say to the caller that a confirmation mail has been sent
2613 $result->value
= 'eauth';
2616 $result = Status
::newGood( true );
2623 * Get the user's real name
2624 * @return string User's real name
2626 public function getRealName() {
2627 if ( !$this->isItemLoaded( 'realname' ) ) {
2631 return $this->mRealName
;
2635 * Set the user's real name
2636 * @param string $str New real name
2638 public function setRealName( $str ) {
2640 $this->mRealName
= $str;
2644 * Get the user's current setting for a given option.
2646 * @param string $oname The option to check
2647 * @param string $defaultOverride A default value returned if the option does not exist
2648 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2649 * @return string User's current value for the option
2650 * @see getBoolOption()
2651 * @see getIntOption()
2653 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2654 global $wgHiddenPrefs;
2655 $this->loadOptions();
2657 # We want 'disabled' preferences to always behave as the default value for
2658 # users, even if they have set the option explicitly in their settings (ie they
2659 # set it, and then it was disabled removing their ability to change it). But
2660 # we don't want to erase the preferences in the database in case the preference
2661 # is re-enabled again. So don't touch $mOptions, just override the returned value
2662 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2663 return self
::getDefaultOption( $oname );
2666 if ( array_key_exists( $oname, $this->mOptions
) ) {
2667 return $this->mOptions
[$oname];
2669 return $defaultOverride;
2674 * Get all user's options
2676 * @param int $flags Bitwise combination of:
2677 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2678 * to the default value. (Since 1.25)
2681 public function getOptions( $flags = 0 ) {
2682 global $wgHiddenPrefs;
2683 $this->loadOptions();
2684 $options = $this->mOptions
;
2686 # We want 'disabled' preferences to always behave as the default value for
2687 # users, even if they have set the option explicitly in their settings (ie they
2688 # set it, and then it was disabled removing their ability to change it). But
2689 # we don't want to erase the preferences in the database in case the preference
2690 # is re-enabled again. So don't touch $mOptions, just override the returned value
2691 foreach ( $wgHiddenPrefs as $pref ) {
2692 $default = self
::getDefaultOption( $pref );
2693 if ( $default !== null ) {
2694 $options[$pref] = $default;
2698 if ( $flags & self
::GETOPTIONS_EXCLUDE_DEFAULTS
) {
2699 $options = array_diff_assoc( $options, self
::getDefaultOptions() );
2706 * Get the user's current setting for a given option, as a boolean value.
2708 * @param string $oname The option to check
2709 * @return bool User's current value for the option
2712 public function getBoolOption( $oname ) {
2713 return (bool)$this->getOption( $oname );
2717 * Get the user's current setting for a given option, as an integer value.
2719 * @param string $oname The option to check
2720 * @param int $defaultOverride A default value returned if the option does not exist
2721 * @return int User's current value for the option
2724 public function getIntOption( $oname, $defaultOverride = 0 ) {
2725 $val = $this->getOption( $oname );
2727 $val = $defaultOverride;
2729 return intval( $val );
2733 * Set the given option for a user.
2735 * You need to call saveSettings() to actually write to the database.
2737 * @param string $oname The option to set
2738 * @param mixed $val New value to set
2740 public function setOption( $oname, $val ) {
2741 $this->loadOptions();
2743 // Explicitly NULL values should refer to defaults
2744 if ( is_null( $val ) ) {
2745 $val = self
::getDefaultOption( $oname );
2748 $this->mOptions
[$oname] = $val;
2752 * Get a token stored in the preferences (like the watchlist one),
2753 * resetting it if it's empty (and saving changes).
2755 * @param string $oname The option name to retrieve the token from
2756 * @return string|bool User's current value for the option, or false if this option is disabled.
2757 * @see resetTokenFromOption()
2759 * @deprecated 1.26 Applications should use the OAuth extension
2761 public function getTokenFromOption( $oname ) {
2762 global $wgHiddenPrefs;
2764 $id = $this->getId();
2765 if ( !$id ||
in_array( $oname, $wgHiddenPrefs ) ) {
2769 $token = $this->getOption( $oname );
2771 // Default to a value based on the user token to avoid space
2772 // wasted on storing tokens for all users. When this option
2773 // is set manually by the user, only then is it stored.
2774 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
2781 * Reset a token stored in the preferences (like the watchlist one).
2782 * *Does not* save user's preferences (similarly to setOption()).
2784 * @param string $oname The option name to reset the token in
2785 * @return string|bool New token value, or false if this option is disabled.
2786 * @see getTokenFromOption()
2789 public function resetTokenFromOption( $oname ) {
2790 global $wgHiddenPrefs;
2791 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2795 $token = MWCryptRand
::generateHex( 40 );
2796 $this->setOption( $oname, $token );
2801 * Return a list of the types of user options currently returned by
2802 * User::getOptionKinds().
2804 * Currently, the option kinds are:
2805 * - 'registered' - preferences which are registered in core MediaWiki or
2806 * by extensions using the UserGetDefaultOptions hook.
2807 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2808 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2809 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2810 * be used by user scripts.
2811 * - 'special' - "preferences" that are not accessible via User::getOptions
2812 * or User::setOptions.
2813 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2814 * These are usually legacy options, removed in newer versions.
2816 * The API (and possibly others) use this function to determine the possible
2817 * option types for validation purposes, so make sure to update this when a
2818 * new option kind is added.
2820 * @see User::getOptionKinds
2821 * @return array Option kinds
2823 public static function listOptionKinds() {
2826 'registered-multiselect',
2827 'registered-checkmatrix',
2835 * Return an associative array mapping preferences keys to the kind of a preference they're
2836 * used for. Different kinds are handled differently when setting or reading preferences.
2838 * See User::listOptionKinds for the list of valid option types that can be provided.
2840 * @see User::listOptionKinds
2841 * @param IContextSource $context
2842 * @param array $options Assoc. array with options keys to check as keys.
2843 * Defaults to $this->mOptions.
2844 * @return array The key => kind mapping data
2846 public function getOptionKinds( IContextSource
$context, $options = null ) {
2847 $this->loadOptions();
2848 if ( $options === null ) {
2849 $options = $this->mOptions
;
2852 $prefs = Preferences
::getPreferences( $this, $context );
2855 // Pull out the "special" options, so they don't get converted as
2856 // multiselect or checkmatrix.
2857 $specialOptions = array_fill_keys( Preferences
::getSaveBlacklist(), true );
2858 foreach ( $specialOptions as $name => $value ) {
2859 unset( $prefs[$name] );
2862 // Multiselect and checkmatrix options are stored in the database with
2863 // one key per option, each having a boolean value. Extract those keys.
2864 $multiselectOptions = array();
2865 foreach ( $prefs as $name => $info ) {
2866 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2867 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2868 $opts = HTMLFormField
::flattenOptions( $info['options'] );
2869 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2871 foreach ( $opts as $value ) {
2872 $multiselectOptions["$prefix$value"] = true;
2875 unset( $prefs[$name] );
2878 $checkmatrixOptions = array();
2879 foreach ( $prefs as $name => $info ) {
2880 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2881 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2882 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
2883 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
2884 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2886 foreach ( $columns as $column ) {
2887 foreach ( $rows as $row ) {
2888 $checkmatrixOptions["$prefix$column-$row"] = true;
2892 unset( $prefs[$name] );
2896 // $value is ignored
2897 foreach ( $options as $key => $value ) {
2898 if ( isset( $prefs[$key] ) ) {
2899 $mapping[$key] = 'registered';
2900 } elseif ( isset( $multiselectOptions[$key] ) ) {
2901 $mapping[$key] = 'registered-multiselect';
2902 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2903 $mapping[$key] = 'registered-checkmatrix';
2904 } elseif ( isset( $specialOptions[$key] ) ) {
2905 $mapping[$key] = 'special';
2906 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2907 $mapping[$key] = 'userjs';
2909 $mapping[$key] = 'unused';
2917 * Reset certain (or all) options to the site defaults
2919 * The optional parameter determines which kinds of preferences will be reset.
2920 * Supported values are everything that can be reported by getOptionKinds()
2921 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2923 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
2924 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2925 * for backwards-compatibility.
2926 * @param IContextSource|null $context Context source used when $resetKinds
2927 * does not contain 'all', passed to getOptionKinds().
2928 * Defaults to RequestContext::getMain() when null.
2930 public function resetOptions(
2931 $resetKinds = array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ),
2932 IContextSource
$context = null
2935 $defaultOptions = self
::getDefaultOptions();
2937 if ( !is_array( $resetKinds ) ) {
2938 $resetKinds = array( $resetKinds );
2941 if ( in_array( 'all', $resetKinds ) ) {
2942 $newOptions = $defaultOptions;
2944 if ( $context === null ) {
2945 $context = RequestContext
::getMain();
2948 $optionKinds = $this->getOptionKinds( $context );
2949 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
2950 $newOptions = array();
2952 // Use default values for the options that should be deleted, and
2953 // copy old values for the ones that shouldn't.
2954 foreach ( $this->mOptions
as $key => $value ) {
2955 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
2956 if ( array_key_exists( $key, $defaultOptions ) ) {
2957 $newOptions[$key] = $defaultOptions[$key];
2960 $newOptions[$key] = $value;
2965 Hooks
::run( 'UserResetAllOptions', array( $this, &$newOptions, $this->mOptions
, $resetKinds ) );
2967 $this->mOptions
= $newOptions;
2968 $this->mOptionsLoaded
= true;
2972 * Get the user's preferred date format.
2973 * @return string User's preferred date format
2975 public function getDatePreference() {
2976 // Important migration for old data rows
2977 if ( is_null( $this->mDatePreference
) ) {
2979 $value = $this->getOption( 'date' );
2980 $map = $wgLang->getDatePreferenceMigrationMap();
2981 if ( isset( $map[$value] ) ) {
2982 $value = $map[$value];
2984 $this->mDatePreference
= $value;
2986 return $this->mDatePreference
;
2990 * Determine based on the wiki configuration and the user's options,
2991 * whether this user must be over HTTPS no matter what.
2995 public function requiresHTTPS() {
2996 global $wgSecureLogin;
2997 if ( !$wgSecureLogin ) {
3000 $https = $this->getBoolOption( 'prefershttps' );
3001 Hooks
::run( 'UserRequiresHTTPS', array( $this, &$https ) );
3003 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
3010 * Get the user preferred stub threshold
3014 public function getStubThreshold() {
3015 global $wgMaxArticleSize; # Maximum article size, in Kb
3016 $threshold = $this->getIntOption( 'stubthreshold' );
3017 if ( $threshold > $wgMaxArticleSize * 1024 ) {
3018 // If they have set an impossible value, disable the preference
3019 // so we can use the parser cache again.
3026 * Get the permissions this user has.
3027 * @return array Array of String permission names
3029 public function getRights() {
3030 if ( is_null( $this->mRights
) ) {
3031 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
3033 $allowedRights = $this->getRequest()->getSession()->getAllowedUserRights();
3034 if ( $allowedRights !== null ) {
3035 $this->mRights
= array_intersect( $this->mRights
, $allowedRights );
3038 Hooks
::run( 'UserGetRights', array( $this, &$this->mRights
) );
3039 // Force reindexation of rights when a hook has unset one of them
3040 $this->mRights
= array_values( array_unique( $this->mRights
) );
3042 return $this->mRights
;
3046 * Get the list of explicit group memberships this user has.
3047 * The implicit * and user groups are not included.
3048 * @return array Array of String internal group names
3050 public function getGroups() {
3052 $this->loadGroups();
3053 return $this->mGroups
;
3057 * Get the list of implicit group memberships this user has.
3058 * This includes all explicit groups, plus 'user' if logged in,
3059 * '*' for all accounts, and autopromoted groups
3060 * @param bool $recache Whether to avoid the cache
3061 * @return array Array of String internal group names
3063 public function getEffectiveGroups( $recache = false ) {
3064 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
3065 $this->mEffectiveGroups
= array_unique( array_merge(
3066 $this->getGroups(), // explicit groups
3067 $this->getAutomaticGroups( $recache ) // implicit groups
3069 // Hook for additional groups
3070 Hooks
::run( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
3071 // Force reindexation of groups when a hook has unset one of them
3072 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
3074 return $this->mEffectiveGroups
;
3078 * Get the list of implicit group memberships this user has.
3079 * This includes 'user' if logged in, '*' for all accounts,
3080 * and autopromoted groups
3081 * @param bool $recache Whether to avoid the cache
3082 * @return array Array of String internal group names
3084 public function getAutomaticGroups( $recache = false ) {
3085 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
3086 $this->mImplicitGroups
= array( '*' );
3087 if ( $this->getId() ) {
3088 $this->mImplicitGroups
[] = 'user';
3090 $this->mImplicitGroups
= array_unique( array_merge(
3091 $this->mImplicitGroups
,
3092 Autopromote
::getAutopromoteGroups( $this )
3096 // Assure data consistency with rights/groups,
3097 // as getEffectiveGroups() depends on this function
3098 $this->mEffectiveGroups
= null;
3101 return $this->mImplicitGroups
;
3105 * Returns the groups the user has belonged to.
3107 * The user may still belong to the returned groups. Compare with getGroups().
3109 * The function will not return groups the user had belonged to before MW 1.17
3111 * @return array Names of the groups the user has belonged to.
3113 public function getFormerGroups() {
3116 if ( is_null( $this->mFormerGroups
) ) {
3117 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3118 ?
wfGetDB( DB_MASTER
)
3119 : wfGetDB( DB_SLAVE
);
3120 $res = $db->select( 'user_former_groups',
3121 array( 'ufg_group' ),
3122 array( 'ufg_user' => $this->mId
),
3124 $this->mFormerGroups
= array();
3125 foreach ( $res as $row ) {
3126 $this->mFormerGroups
[] = $row->ufg_group
;
3130 return $this->mFormerGroups
;
3134 * Get the user's edit count.
3135 * @return int|null Null for anonymous users
3137 public function getEditCount() {
3138 if ( !$this->getId() ) {
3142 if ( $this->mEditCount
=== null ) {
3143 /* Populate the count, if it has not been populated yet */
3144 $dbr = wfGetDB( DB_SLAVE
);
3145 // check if the user_editcount field has been initialized
3146 $count = $dbr->selectField(
3147 'user', 'user_editcount',
3148 array( 'user_id' => $this->mId
),
3152 if ( $count === null ) {
3153 // it has not been initialized. do so.
3154 $count = $this->initEditCount();
3156 $this->mEditCount
= $count;
3158 return (int)$this->mEditCount
;
3162 * Add the user to the given group.
3163 * This takes immediate effect.
3164 * @param string $group Name of the group to add
3167 public function addGroup( $group ) {
3170 if ( !Hooks
::run( 'UserAddGroup', array( $this, &$group ) ) ) {
3174 $dbw = wfGetDB( DB_MASTER
);
3175 if ( $this->getId() ) {
3176 $dbw->insert( 'user_groups',
3178 'ug_user' => $this->getID(),
3179 'ug_group' => $group,
3182 array( 'IGNORE' ) );
3185 $this->loadGroups();
3186 $this->mGroups
[] = $group;
3187 // In case loadGroups was not called before, we now have the right twice.
3188 // Get rid of the duplicate.
3189 $this->mGroups
= array_unique( $this->mGroups
);
3191 // Refresh the groups caches, and clear the rights cache so it will be
3192 // refreshed on the next call to $this->getRights().
3193 $this->getEffectiveGroups( true );
3194 $this->mRights
= null;
3196 $this->invalidateCache();
3202 * Remove the user from the given group.
3203 * This takes immediate effect.
3204 * @param string $group Name of the group to remove
3207 public function removeGroup( $group ) {
3209 if ( !Hooks
::run( 'UserRemoveGroup', array( $this, &$group ) ) ) {
3213 $dbw = wfGetDB( DB_MASTER
);
3214 $dbw->delete( 'user_groups',
3216 'ug_user' => $this->getID(),
3217 'ug_group' => $group,
3220 // Remember that the user was in this group
3221 $dbw->insert( 'user_former_groups',
3223 'ufg_user' => $this->getID(),
3224 'ufg_group' => $group,
3230 $this->loadGroups();
3231 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
3233 // Refresh the groups caches, and clear the rights cache so it will be
3234 // refreshed on the next call to $this->getRights().
3235 $this->getEffectiveGroups( true );
3236 $this->mRights
= null;
3238 $this->invalidateCache();
3244 * Get whether the user is logged in
3247 public function isLoggedIn() {
3248 return $this->getID() != 0;
3252 * Get whether the user is anonymous
3255 public function isAnon() {
3256 return !$this->isLoggedIn();
3260 * Check if user is allowed to access a feature / make an action
3262 * @param string ... Permissions to test
3263 * @return bool True if user is allowed to perform *any* of the given actions
3265 public function isAllowedAny() {
3266 $permissions = func_get_args();
3267 foreach ( $permissions as $permission ) {
3268 if ( $this->isAllowed( $permission ) ) {
3277 * @param string ... Permissions to test
3278 * @return bool True if the user is allowed to perform *all* of the given actions
3280 public function isAllowedAll() {
3281 $permissions = func_get_args();
3282 foreach ( $permissions as $permission ) {
3283 if ( !$this->isAllowed( $permission ) ) {
3291 * Internal mechanics of testing a permission
3292 * @param string $action
3295 public function isAllowed( $action = '' ) {
3296 if ( $action === '' ) {
3297 return true; // In the spirit of DWIM
3299 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3300 // by misconfiguration: 0 == 'foo'
3301 return in_array( $action, $this->getRights(), true );
3305 * Check whether to enable recent changes patrol features for this user
3306 * @return bool True or false
3308 public function useRCPatrol() {
3309 global $wgUseRCPatrol;
3310 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3314 * Check whether to enable new pages patrol features for this user
3315 * @return bool True or false
3317 public function useNPPatrol() {
3318 global $wgUseRCPatrol, $wgUseNPPatrol;
3320 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3321 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3326 * Check whether to enable new files patrol features for this user
3327 * @return bool True or false
3329 public function useFilePatrol() {
3330 global $wgUseRCPatrol, $wgUseFilePatrol;
3332 ( $wgUseRCPatrol ||
$wgUseFilePatrol )
3333 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3338 * Get the WebRequest object to use with this object
3340 * @return WebRequest
3342 public function getRequest() {
3343 if ( $this->mRequest
) {
3344 return $this->mRequest
;
3352 * Get a WatchedItem for this user and $title.
3354 * @since 1.22 $checkRights parameter added
3355 * @param Title $title
3356 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3357 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3358 * @return WatchedItem
3360 public function getWatchedItem( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3361 $key = $checkRights . ':' . $title->getNamespace() . ':' . $title->getDBkey();
3363 if ( isset( $this->mWatchedItems
[$key] ) ) {
3364 return $this->mWatchedItems
[$key];
3367 if ( count( $this->mWatchedItems
) >= self
::MAX_WATCHED_ITEMS_CACHE
) {
3368 $this->mWatchedItems
= array();
3371 $this->mWatchedItems
[$key] = WatchedItem
::fromUserTitle( $this, $title, $checkRights );
3372 return $this->mWatchedItems
[$key];
3376 * Check the watched status of an article.
3377 * @since 1.22 $checkRights parameter added
3378 * @param Title $title Title of the article to look at
3379 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3380 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3383 public function isWatched( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3384 return $this->getWatchedItem( $title, $checkRights )->isWatched();
3389 * @since 1.22 $checkRights parameter added
3390 * @param Title $title Title of the article to look at
3391 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3392 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3394 public function addWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3395 $this->getWatchedItem( $title, $checkRights )->addWatch();
3396 $this->invalidateCache();
3400 * Stop watching an article.
3401 * @since 1.22 $checkRights parameter added
3402 * @param Title $title Title of the article to look at
3403 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3404 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3406 public function removeWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3407 $this->getWatchedItem( $title, $checkRights )->removeWatch();
3408 $this->invalidateCache();
3412 * Clear the user's notification timestamp for the given title.
3413 * If e-notif e-mails are on, they will receive notification mails on
3414 * the next change of the page if it's watched etc.
3415 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3416 * @param Title $title Title of the article to look at
3417 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3419 public function clearNotification( &$title, $oldid = 0 ) {
3420 global $wgUseEnotif, $wgShowUpdatedMarker;
3422 // Do nothing if the database is locked to writes
3423 if ( wfReadOnly() ) {
3427 // Do nothing if not allowed to edit the watchlist
3428 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3432 // If we're working on user's talk page, we should update the talk page message indicator
3433 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3434 if ( !Hooks
::run( 'UserClearNewTalkNotification', array( &$this, $oldid ) ) ) {
3439 // Try to update the DB post-send and only if needed...
3440 DeferredUpdates
::addCallableUpdate( function() use ( $that, $title, $oldid ) {
3441 if ( !$that->getNewtalk() ) {
3442 return; // no notifications to clear
3445 // Delete the last notifications (they stack up)
3446 $that->setNewtalk( false );
3448 // If there is a new, unseen, revision, use its timestamp
3450 ?
$title->getNextRevisionID( $oldid, Title
::GAID_FOR_UPDATE
)
3453 $that->setNewtalk( true, Revision
::newFromId( $nextid ) );
3458 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3462 if ( $this->isAnon() ) {
3463 // Nothing else to do...
3467 // Only update the timestamp if the page is being watched.
3468 // The query to find out if it is watched is cached both in memcached and per-invocation,
3469 // and when it does have to be executed, it can be on a slave
3470 // If this is the user's newtalk page, we always update the timestamp
3472 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3476 $this->getWatchedItem( $title )->resetNotificationTimestamp(
3482 * Resets all of the given user's page-change notification timestamps.
3483 * If e-notif e-mails are on, they will receive notification mails on
3484 * the next change of any watched page.
3485 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3487 public function clearAllNotifications() {
3488 if ( wfReadOnly() ) {
3492 // Do nothing if not allowed to edit the watchlist
3493 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3497 global $wgUseEnotif, $wgShowUpdatedMarker;
3498 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3499 $this->setNewtalk( false );
3502 $id = $this->getId();
3504 $dbw = wfGetDB( DB_MASTER
);
3505 $dbw->update( 'watchlist',
3506 array( /* SET */ 'wl_notificationtimestamp' => null ),
3507 array( /* WHERE */ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ),
3510 // We also need to clear here the "you have new message" notification for the own user_talk page;
3511 // it's cleared one page view later in WikiPage::doViewUpdates().
3516 * Set a cookie on the user's client. Wrapper for
3517 * WebResponse::setCookie
3518 * @deprecated since 1.27
3519 * @param string $name Name of the cookie to set
3520 * @param string $value Value to set
3521 * @param int $exp Expiration time, as a UNIX time value;
3522 * if 0 or not specified, use the default $wgCookieExpiration
3523 * @param bool $secure
3524 * true: Force setting the secure attribute when setting the cookie
3525 * false: Force NOT setting the secure attribute when setting the cookie
3526 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3527 * @param array $params Array of options sent passed to WebResponse::setcookie()
3528 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3531 protected function setCookie(
3532 $name, $value, $exp = 0, $secure = null, $params = array(), $request = null
3534 wfDeprecated( __METHOD__
, '1.27' );
3535 if ( $request === null ) {
3536 $request = $this->getRequest();
3538 $params['secure'] = $secure;
3539 $request->response()->setCookie( $name, $value, $exp, $params );
3543 * Clear a cookie on the user's client
3544 * @deprecated since 1.27
3545 * @param string $name Name of the cookie to clear
3546 * @param bool $secure
3547 * true: Force setting the secure attribute when setting the cookie
3548 * false: Force NOT setting the secure attribute when setting the cookie
3549 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3550 * @param array $params Array of options sent passed to WebResponse::setcookie()
3552 protected function clearCookie( $name, $secure = null, $params = array() ) {
3553 wfDeprecated( __METHOD__
, '1.27' );
3554 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3558 * Set an extended login cookie on the user's client. The expiry of the cookie
3559 * is controlled by the $wgExtendedLoginCookieExpiration configuration
3562 * @see User::setCookie
3564 * @deprecated since 1.27
3565 * @param string $name Name of the cookie to set
3566 * @param string $value Value to set
3567 * @param bool $secure
3568 * true: Force setting the secure attribute when setting the cookie
3569 * false: Force NOT setting the secure attribute when setting the cookie
3570 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3572 protected function setExtendedLoginCookie( $name, $value, $secure ) {
3573 global $wgExtendedLoginCookieExpiration, $wgCookieExpiration;
3575 wfDeprecated( __METHOD__
, '1.27' );
3578 $exp +
= $wgExtendedLoginCookieExpiration !== null
3579 ?
$wgExtendedLoginCookieExpiration
3580 : $wgCookieExpiration;
3582 $this->setCookie( $name, $value, $exp, $secure );
3586 * Persist this user's session (e.g. set cookies)
3588 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3590 * @param bool $secure Whether to force secure/insecure cookies or use default
3591 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3593 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3595 if ( 0 == $this->mId
) {
3599 $session = $this->getRequest()->getSession();
3600 if ( $request && $session->getRequest() !== $request ) {
3601 $session = $session->sessionWithRequest( $request );
3603 $delay = $session->delaySave();
3605 if ( !$session->getUser()->equals( $this ) ) {
3606 if ( !$session->canSetUser() ) {
3607 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3608 ->warning( __METHOD__
.
3609 ": Cannot save user \"$this\" to a user \"{$session->getUser()}\"'s immutable session"
3613 $session->setUser( $this );
3616 $session->setRememberUser( $rememberMe );
3617 if ( $secure !== null ) {
3618 $session->setForceHTTPS( $secure );
3621 $session->persist();
3623 ScopedCallback
::consume( $delay );
3627 * Log this user out.
3629 public function logout() {
3630 if ( Hooks
::run( 'UserLogout', array( &$this ) ) ) {
3636 * Clear the user's session, and reset the instance cache.
3639 public function doLogout() {
3640 $session = $this->getRequest()->getSession();
3641 if ( !$session->canSetUser() ) {
3642 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3643 ->warning( __METHOD__
. ": Cannot log out of an immutable session" );
3644 } elseif ( !$session->getUser()->equals( $this ) ) {
3645 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3646 ->warning( __METHOD__
.
3647 ": Cannot log user \"$this\" out of a user \"{$session->getUser()}\"'s session"
3649 // But we still may as well make this user object anon
3650 $this->clearInstanceCache( 'defaults' );
3652 $this->clearInstanceCache( 'defaults' );
3653 $delay = $session->delaySave();
3654 $session->setLoggedOutTimestamp( time() );
3655 $session->setUser( new User
);
3656 $session->set( 'wsUserID', 0 ); // Other code expects this
3657 ScopedCallback
::consume( $delay );
3662 * Save this user's settings into the database.
3663 * @todo Only rarely do all these fields need to be set!
3665 public function saveSettings() {
3666 if ( wfReadOnly() ) {
3667 // @TODO: caller should deal with this instead!
3668 // This should really just be an exception.
3669 MWExceptionHandler
::logException( new DBExpectedError(
3671 "Could not update user with ID '{$this->mId}'; DB is read-only."
3677 if ( 0 == $this->mId
) {
3681 // Get a new user_touched that is higher than the old one.
3682 // This will be used for a CAS check as a last-resort safety
3683 // check against race conditions and slave lag.
3684 $oldTouched = $this->mTouched
;
3685 $newTouched = $this->newTouchedTimestamp();
3687 $dbw = wfGetDB( DB_MASTER
);
3688 $dbw->update( 'user',
3690 'user_name' => $this->mName
,
3691 'user_real_name' => $this->mRealName
,
3692 'user_email' => $this->mEmail
,
3693 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3694 'user_touched' => $dbw->timestamp( $newTouched ),
3695 'user_token' => strval( $this->mToken
),
3696 'user_email_token' => $this->mEmailToken
,
3697 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
3698 ), array( /* WHERE */
3699 'user_id' => $this->mId
,
3700 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
3704 if ( !$dbw->affectedRows() ) {
3705 // Maybe the problem was a missed cache update; clear it to be safe
3706 $this->clearSharedCache( 'refresh' );
3707 // User was changed in the meantime or loaded with stale data
3708 $from = ( $this->queryFlagsUsed
& self
::READ_LATEST
) ?
'master' : 'slave';
3709 throw new MWException(
3710 "CAS update failed on user_touched for user ID '{$this->mId}' (read from $from);" .
3711 " the version of the user to be saved is older than the current version."
3715 $this->mTouched
= $newTouched;
3716 $this->saveOptions();
3718 Hooks
::run( 'UserSaveSettings', array( $this ) );
3719 $this->clearSharedCache();
3720 $this->getUserPage()->invalidateCache();
3724 * If only this user's username is known, and it exists, return the user ID.
3726 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
3729 public function idForName( $flags = 0 ) {
3730 $s = trim( $this->getName() );
3735 $db = ( ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
)
3736 ?
wfGetDB( DB_MASTER
)
3737 : wfGetDB( DB_SLAVE
);
3739 $options = ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
)
3740 ?
array( 'LOCK IN SHARE MODE' )
3743 $id = $db->selectField( 'user',
3744 'user_id', array( 'user_name' => $s ), __METHOD__
, $options );
3750 * Add a user to the database, return the user object
3752 * @param string $name Username to add
3753 * @param array $params Array of Strings Non-default parameters to save to
3754 * the database as user_* fields:
3755 * - email: The user's email address.
3756 * - email_authenticated: The email authentication timestamp.
3757 * - real_name: The user's real name.
3758 * - options: An associative array of non-default options.
3759 * - token: Random authentication token. Do not set.
3760 * - registration: Registration timestamp. Do not set.
3762 * @return User|null User object, or null if the username already exists.
3764 public static function createNew( $name, $params = array() ) {
3765 foreach ( array( 'password', 'newpassword', 'newpass_time', 'password_expires' ) as $field ) {
3766 if ( isset( $params[$field] ) ) {
3767 wfDeprecated( __METHOD__
. " with param '$field'", '1.27' );
3768 unset( $params[$field] );
3774 $user->setToken(); // init token
3775 if ( isset( $params['options'] ) ) {
3776 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
3777 unset( $params['options'] );
3779 $dbw = wfGetDB( DB_MASTER
);
3780 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3782 $noPass = PasswordFactory
::newInvalidPassword()->toString();
3785 'user_id' => $seqVal,
3786 'user_name' => $name,
3787 'user_password' => $noPass,
3788 'user_newpassword' => $noPass,
3789 'user_email' => $user->mEmail
,
3790 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
3791 'user_real_name' => $user->mRealName
,
3792 'user_token' => strval( $user->mToken
),
3793 'user_registration' => $dbw->timestamp( $user->mRegistration
),
3794 'user_editcount' => 0,
3795 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
3797 foreach ( $params as $name => $value ) {
3798 $fields["user_$name"] = $value;
3800 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
3801 if ( $dbw->affectedRows() ) {
3802 $newUser = User
::newFromId( $dbw->insertId() );
3810 * Add this existing user object to the database. If the user already
3811 * exists, a fatal status object is returned, and the user object is
3812 * initialised with the data from the database.
3814 * Previously, this function generated a DB error due to a key conflict
3815 * if the user already existed. Many extension callers use this function
3816 * in code along the lines of:
3818 * $user = User::newFromName( $name );
3819 * if ( !$user->isLoggedIn() ) {
3820 * $user->addToDatabase();
3822 * // do something with $user...
3824 * However, this was vulnerable to a race condition (bug 16020). By
3825 * initialising the user object if the user exists, we aim to support this
3826 * calling sequence as far as possible.
3828 * Note that if the user exists, this function will acquire a write lock,
3829 * so it is still advisable to make the call conditional on isLoggedIn(),
3830 * and to commit the transaction after calling.
3832 * @throws MWException
3835 public function addToDatabase() {
3837 if ( !$this->mToken
) {
3838 $this->setToken(); // init token
3841 $this->mTouched
= $this->newTouchedTimestamp();
3843 $noPass = PasswordFactory
::newInvalidPassword()->toString();
3845 $dbw = wfGetDB( DB_MASTER
);
3846 $inWrite = $dbw->writesOrCallbacksPending();
3847 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3848 $dbw->insert( 'user',
3850 'user_id' => $seqVal,
3851 'user_name' => $this->mName
,
3852 'user_password' => $noPass,
3853 'user_newpassword' => $noPass,
3854 'user_email' => $this->mEmail
,
3855 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3856 'user_real_name' => $this->mRealName
,
3857 'user_token' => strval( $this->mToken
),
3858 'user_registration' => $dbw->timestamp( $this->mRegistration
),
3859 'user_editcount' => 0,
3860 'user_touched' => $dbw->timestamp( $this->mTouched
),
3864 if ( !$dbw->affectedRows() ) {
3865 // The queries below cannot happen in the same REPEATABLE-READ snapshot.
3866 // Handle this by COMMIT, if possible, or by LOCK IN SHARE MODE otherwise.
3868 // Can't commit due to pending writes that may need atomicity.
3869 // This may cause some lock contention unlike the case below.
3870 $options = array( 'LOCK IN SHARE MODE' );
3871 $flags = self
::READ_LOCKING
;
3873 // Often, this case happens early in views before any writes when
3874 // using CentralAuth. It's should be OK to commit and break the snapshot.
3875 $dbw->commit( __METHOD__
, 'flush' );
3877 $flags = self
::READ_LATEST
;
3879 $this->mId
= $dbw->selectField( 'user', 'user_id',
3880 array( 'user_name' => $this->mName
), __METHOD__
, $options );
3883 if ( $this->loadFromDatabase( $flags ) ) {
3888 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
3889 "to insert user '{$this->mName}' row, but it was not present in select!" );
3891 return Status
::newFatal( 'userexists' );
3893 $this->mId
= $dbw->insertId();
3894 self
::$idCacheByName[$this->mName
] = $this->mId
;
3896 // Clear instance cache other than user table data, which is already accurate
3897 $this->clearInstanceCache();
3899 $this->saveOptions();
3900 return Status
::newGood();
3904 * If this user is logged-in and blocked,
3905 * block any IP address they've successfully logged in from.
3906 * @return bool A block was spread
3908 public function spreadAnyEditBlock() {
3909 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3910 return $this->spreadBlock();
3916 * If this (non-anonymous) user is blocked,
3917 * block the IP address they've successfully logged in from.
3918 * @return bool A block was spread
3920 protected function spreadBlock() {
3921 wfDebug( __METHOD__
. "()\n" );
3923 if ( $this->mId
== 0 ) {
3927 $userblock = Block
::newFromTarget( $this->getName() );
3928 if ( !$userblock ) {
3932 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3936 * Get whether the user is explicitly blocked from account creation.
3937 * @return bool|Block
3939 public function isBlockedFromCreateAccount() {
3940 $this->getBlockedStatus();
3941 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
3942 return $this->mBlock
;
3945 # bug 13611: if the IP address the user is trying to create an account from is
3946 # blocked with createaccount disabled, prevent new account creation there even
3947 # when the user is logged in
3948 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3949 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
3951 return $this->mBlockedFromCreateAccount
instanceof Block
3952 && $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
3953 ?
$this->mBlockedFromCreateAccount
3958 * Get whether the user is blocked from using Special:Emailuser.
3961 public function isBlockedFromEmailuser() {
3962 $this->getBlockedStatus();
3963 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
3967 * Get whether the user is allowed to create an account.
3970 public function isAllowedToCreateAccount() {
3971 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
3975 * Get this user's personal page title.
3977 * @return Title User's personal page title
3979 public function getUserPage() {
3980 return Title
::makeTitle( NS_USER
, $this->getName() );
3984 * Get this user's talk page title.
3986 * @return Title User's talk page title
3988 public function getTalkPage() {
3989 $title = $this->getUserPage();
3990 return $title->getTalkPage();
3994 * Determine whether the user is a newbie. Newbies are either
3995 * anonymous IPs, or the most recently created accounts.
3998 public function isNewbie() {
3999 return !$this->isAllowed( 'autoconfirmed' );
4003 * Check to see if the given clear-text password is one of the accepted passwords
4004 * @deprecated since 1.27. AuthManager is coming.
4005 * @param string $password User password
4006 * @return bool True if the given password is correct, otherwise False
4008 public function checkPassword( $password ) {
4009 global $wgAuth, $wgLegacyEncoding;
4013 // Some passwords will give a fatal Status, which means there is
4014 // some sort of technical or security reason for this password to
4015 // be completely invalid and should never be checked (e.g., T64685)
4016 if ( !$this->checkPasswordValidity( $password )->isOK() ) {
4020 // Certain authentication plugins do NOT want to save
4021 // domain passwords in a mysql database, so we should
4022 // check this (in case $wgAuth->strict() is false).
4023 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
4025 } elseif ( $wgAuth->strict() ) {
4026 // Auth plugin doesn't allow local authentication
4028 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
4029 // Auth plugin doesn't allow local authentication for this user name
4033 $passwordFactory = new PasswordFactory();
4034 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4035 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
4036 ?
wfGetDB( DB_MASTER
)
4037 : wfGetDB( DB_SLAVE
);
4040 $mPassword = $passwordFactory->newFromCiphertext( $db->selectField(
4041 'user', 'user_password', array( 'user_id' => $this->getId() ), __METHOD__
4043 } catch ( PasswordError
$e ) {
4044 wfDebug( 'Invalid password hash found in database.' );
4045 $mPassword = PasswordFactory
::newInvalidPassword();
4048 if ( !$mPassword->equals( $password ) ) {
4049 if ( $wgLegacyEncoding ) {
4050 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
4051 // Check for this with iconv
4052 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
4053 if ( $cp1252Password === $password ||
!$mPassword->equals( $cp1252Password ) ) {
4061 if ( $passwordFactory->needsUpdate( $mPassword ) && !wfReadOnly() ) {
4062 $this->setPasswordInternal( $password );
4069 * Check if the given clear-text password matches the temporary password
4070 * sent by e-mail for password reset operations.
4072 * @deprecated since 1.27. AuthManager is coming.
4073 * @param string $plaintext
4074 * @return bool True if matches, false otherwise
4076 public function checkTemporaryPassword( $plaintext ) {
4077 global $wgNewPasswordExpiry;
4081 $passwordFactory = new PasswordFactory();
4082 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4083 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
4084 ?
wfGetDB( DB_MASTER
)
4085 : wfGetDB( DB_SLAVE
);
4087 $row = $db->selectRow(
4089 array( 'user_newpassword', 'user_newpass_time' ),
4090 array( 'user_id' => $this->getId() ),
4094 $newPassword = $passwordFactory->newFromCiphertext( $row->user_newpassword
);
4095 } catch ( PasswordError
$e ) {
4096 wfDebug( 'Invalid password hash found in database.' );
4097 $newPassword = PasswordFactory
::newInvalidPassword();
4100 if ( $newPassword->equals( $plaintext ) ) {
4101 if ( is_null( $row->user_newpass_time
) ) {
4104 $expiry = wfTimestamp( TS_UNIX
, $row->user_newpass_time
) +
$wgNewPasswordExpiry;
4105 return ( time() < $expiry );
4112 * Initialize (if necessary) and return a session token value
4113 * which can be used in edit forms to show that the user's
4114 * login credentials aren't being hijacked with a foreign form
4118 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4119 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4120 * @return MediaWiki\\Session\\Token The new edit token
4122 public function getEditTokenObject( $salt = '', $request = null ) {
4123 if ( $this->isAnon() ) {
4124 return new LoggedOutEditToken();
4128 $request = $this->getRequest();
4130 return $request->getSession()->getToken( $salt );
4134 * Initialize (if necessary) and return a session token value
4135 * which can be used in edit forms to show that the user's
4136 * login credentials aren't being hijacked with a foreign form
4140 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4141 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4142 * @return string The new edit token
4144 public function getEditToken( $salt = '', $request = null ) {
4145 return $this->getEditTokenObject( $salt, $request )->toString();
4149 * Get the embedded timestamp from a token.
4150 * @deprecated since 1.27, use \\MediaWiki\\Session\\Token::getTimestamp instead.
4151 * @param string $val Input token
4154 public static function getEditTokenTimestamp( $val ) {
4155 wfDeprecated( __METHOD__
, '1.27' );
4156 return MediaWiki\Session\Token
::getTimestamp( $val );
4160 * Check given value against the token value stored in the session.
4161 * A match should confirm that the form was submitted from the
4162 * user's own login session, not a form submission from a third-party
4165 * @param string $val Input value to compare
4166 * @param string $salt Optional function-specific data for hashing
4167 * @param WebRequest|null $request Object to use or null to use $wgRequest
4168 * @param int $maxage Fail tokens older than this, in seconds
4169 * @return bool Whether the token matches
4171 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4172 return $this->getEditTokenObject( $salt, $request )->match( $val, $maxage );
4176 * Check given value against the token value stored in the session,
4177 * ignoring the suffix.
4179 * @param string $val Input value to compare
4180 * @param string $salt Optional function-specific data for hashing
4181 * @param WebRequest|null $request Object to use or null to use $wgRequest
4182 * @param int $maxage Fail tokens older than this, in seconds
4183 * @return bool Whether the token matches
4185 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4186 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . self
::EDIT_TOKEN_SUFFIX
;
4187 return $this->matchEditToken( $val, $salt, $request, $maxage );
4191 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4192 * mail to the user's given address.
4194 * @param string $type Message to send, either "created", "changed" or "set"
4197 public function sendConfirmationMail( $type = 'created' ) {
4199 $expiration = null; // gets passed-by-ref and defined in next line.
4200 $token = $this->confirmationToken( $expiration );
4201 $url = $this->confirmationTokenUrl( $token );
4202 $invalidateURL = $this->invalidationTokenUrl( $token );
4203 $this->saveSettings();
4205 if ( $type == 'created' ||
$type === false ) {
4206 $message = 'confirmemail_body';
4207 } elseif ( $type === true ) {
4208 $message = 'confirmemail_body_changed';
4210 // Messages: confirmemail_body_changed, confirmemail_body_set
4211 $message = 'confirmemail_body_' . $type;
4214 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4215 wfMessage( $message,
4216 $this->getRequest()->getIP(),
4219 $wgLang->userTimeAndDate( $expiration, $this ),
4221 $wgLang->userDate( $expiration, $this ),
4222 $wgLang->userTime( $expiration, $this ) )->text() );
4226 * Send an e-mail to this user's account. Does not check for
4227 * confirmed status or validity.
4229 * @param string $subject Message subject
4230 * @param string $body Message body
4231 * @param User|null $from Optional sending user; if unspecified, default
4232 * $wgPasswordSender will be used.
4233 * @param string $replyto Reply-To address
4236 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4237 global $wgPasswordSender;
4239 if ( $from instanceof User
) {
4240 $sender = MailAddress
::newFromUser( $from );
4242 $sender = new MailAddress( $wgPasswordSender,
4243 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4245 $to = MailAddress
::newFromUser( $this );
4247 return UserMailer
::send( $to, $sender, $subject, $body, array(
4248 'replyTo' => $replyto,
4253 * Generate, store, and return a new e-mail confirmation code.
4254 * A hash (unsalted, since it's used as a key) is stored.
4256 * @note Call saveSettings() after calling this function to commit
4257 * this change to the database.
4259 * @param string &$expiration Accepts the expiration time
4260 * @return string New token
4262 protected function confirmationToken( &$expiration ) {
4263 global $wgUserEmailConfirmationTokenExpiry;
4265 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4266 $expiration = wfTimestamp( TS_MW
, $expires );
4268 $token = MWCryptRand
::generateHex( 32 );
4269 $hash = md5( $token );
4270 $this->mEmailToken
= $hash;
4271 $this->mEmailTokenExpires
= $expiration;
4276 * Return a URL the user can use to confirm their email address.
4277 * @param string $token Accepts the email confirmation token
4278 * @return string New token URL
4280 protected function confirmationTokenUrl( $token ) {
4281 return $this->getTokenUrl( 'ConfirmEmail', $token );
4285 * Return a URL the user can use to invalidate their email address.
4286 * @param string $token Accepts the email confirmation token
4287 * @return string New token URL
4289 protected function invalidationTokenUrl( $token ) {
4290 return $this->getTokenUrl( 'InvalidateEmail', $token );
4294 * Internal function to format the e-mail validation/invalidation URLs.
4295 * This uses a quickie hack to use the
4296 * hardcoded English names of the Special: pages, for ASCII safety.
4298 * @note Since these URLs get dropped directly into emails, using the
4299 * short English names avoids insanely long URL-encoded links, which
4300 * also sometimes can get corrupted in some browsers/mailers
4301 * (bug 6957 with Gmail and Internet Explorer).
4303 * @param string $page Special page
4304 * @param string $token Token
4305 * @return string Formatted URL
4307 protected function getTokenUrl( $page, $token ) {
4308 // Hack to bypass localization of 'Special:'
4309 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4310 return $title->getCanonicalURL();
4314 * Mark the e-mail address confirmed.
4316 * @note Call saveSettings() after calling this function to commit the change.
4320 public function confirmEmail() {
4321 // Check if it's already confirmed, so we don't touch the database
4322 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4323 if ( !$this->isEmailConfirmed() ) {
4324 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4325 Hooks
::run( 'ConfirmEmailComplete', array( $this ) );
4331 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4332 * address if it was already confirmed.
4334 * @note Call saveSettings() after calling this function to commit the change.
4335 * @return bool Returns true
4337 public function invalidateEmail() {
4339 $this->mEmailToken
= null;
4340 $this->mEmailTokenExpires
= null;
4341 $this->setEmailAuthenticationTimestamp( null );
4343 Hooks
::run( 'InvalidateEmailComplete', array( $this ) );
4348 * Set the e-mail authentication timestamp.
4349 * @param string $timestamp TS_MW timestamp
4351 public function setEmailAuthenticationTimestamp( $timestamp ) {
4353 $this->mEmailAuthenticated
= $timestamp;
4354 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
4358 * Is this user allowed to send e-mails within limits of current
4359 * site configuration?
4362 public function canSendEmail() {
4363 global $wgEnableEmail, $wgEnableUserEmail;
4364 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4367 $canSend = $this->isEmailConfirmed();
4368 Hooks
::run( 'UserCanSendEmail', array( &$this, &$canSend ) );
4373 * Is this user allowed to receive e-mails within limits of current
4374 * site configuration?
4377 public function canReceiveEmail() {
4378 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4382 * Is this user's e-mail address valid-looking and confirmed within
4383 * limits of the current site configuration?
4385 * @note If $wgEmailAuthentication is on, this may require the user to have
4386 * confirmed their address by returning a code or using a password
4387 * sent to the address from the wiki.
4391 public function isEmailConfirmed() {
4392 global $wgEmailAuthentication;
4395 if ( Hooks
::run( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
4396 if ( $this->isAnon() ) {
4399 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4402 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4412 * Check whether there is an outstanding request for e-mail confirmation.
4415 public function isEmailConfirmationPending() {
4416 global $wgEmailAuthentication;
4417 return $wgEmailAuthentication &&
4418 !$this->isEmailConfirmed() &&
4419 $this->mEmailToken
&&
4420 $this->mEmailTokenExpires
> wfTimestamp();
4424 * Get the timestamp of account creation.
4426 * @return string|bool|null Timestamp of account creation, false for
4427 * non-existent/anonymous user accounts, or null if existing account
4428 * but information is not in database.
4430 public function getRegistration() {
4431 if ( $this->isAnon() ) {
4435 return $this->mRegistration
;
4439 * Get the timestamp of the first edit
4441 * @return string|bool Timestamp of first edit, or false for
4442 * non-existent/anonymous user accounts.
4444 public function getFirstEditTimestamp() {
4445 if ( $this->getId() == 0 ) {
4446 return false; // anons
4448 $dbr = wfGetDB( DB_SLAVE
);
4449 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4450 array( 'rev_user' => $this->getId() ),
4452 array( 'ORDER BY' => 'rev_timestamp ASC' )
4455 return false; // no edits
4457 return wfTimestamp( TS_MW
, $time );
4461 * Get the permissions associated with a given list of groups
4463 * @param array $groups Array of Strings List of internal group names
4464 * @return array Array of Strings List of permission key names for given groups combined
4466 public static function getGroupPermissions( $groups ) {
4467 global $wgGroupPermissions, $wgRevokePermissions;
4469 // grant every granted permission first
4470 foreach ( $groups as $group ) {
4471 if ( isset( $wgGroupPermissions[$group] ) ) {
4472 $rights = array_merge( $rights,
4473 // array_filter removes empty items
4474 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4477 // now revoke the revoked permissions
4478 foreach ( $groups as $group ) {
4479 if ( isset( $wgRevokePermissions[$group] ) ) {
4480 $rights = array_diff( $rights,
4481 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4484 return array_unique( $rights );
4488 * Get all the groups who have a given permission
4490 * @param string $role Role to check
4491 * @return array Array of Strings List of internal group names with the given permission
4493 public static function getGroupsWithPermission( $role ) {
4494 global $wgGroupPermissions;
4495 $allowedGroups = array();
4496 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4497 if ( self
::groupHasPermission( $group, $role ) ) {
4498 $allowedGroups[] = $group;
4501 return $allowedGroups;
4505 * Check, if the given group has the given permission
4507 * If you're wanting to check whether all users have a permission, use
4508 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4512 * @param string $group Group to check
4513 * @param string $role Role to check
4516 public static function groupHasPermission( $group, $role ) {
4517 global $wgGroupPermissions, $wgRevokePermissions;
4518 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4519 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4523 * Check if all users may be assumed to have the given permission
4525 * We generally assume so if the right is granted to '*' and isn't revoked
4526 * on any group. It doesn't attempt to take grants or other extension
4527 * limitations on rights into account in the general case, though, as that
4528 * would require it to always return false and defeat the purpose.
4529 * Specifically, session-based rights restrictions (such as OAuth or bot
4530 * passwords) are applied based on the current session.
4533 * @param string $right Right to check
4536 public static function isEveryoneAllowed( $right ) {
4537 global $wgGroupPermissions, $wgRevokePermissions;
4538 static $cache = array();
4540 // Use the cached results, except in unit tests which rely on
4541 // being able change the permission mid-request
4542 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4543 return $cache[$right];
4546 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4547 $cache[$right] = false;
4551 // If it's revoked anywhere, then everyone doesn't have it
4552 foreach ( $wgRevokePermissions as $rights ) {
4553 if ( isset( $rights[$right] ) && $rights[$right] ) {
4554 $cache[$right] = false;
4559 // Remove any rights that aren't allowed to the global-session user
4560 $allowedRights = SessionManager
::getGlobalSession()->getAllowedUserRights();
4561 if ( $allowedRights !== null && !in_array( $right, $allowedRights, true ) ) {
4562 $cache[$right] = false;
4566 // Allow extensions to say false
4567 if ( !Hooks
::run( 'UserIsEveryoneAllowed', array( $right ) ) ) {
4568 $cache[$right] = false;
4572 $cache[$right] = true;
4577 * Get the localized descriptive name for a group, if it exists
4579 * @param string $group Internal group name
4580 * @return string Localized descriptive group name
4582 public static function getGroupName( $group ) {
4583 $msg = wfMessage( "group-$group" );
4584 return $msg->isBlank() ?
$group : $msg->text();
4588 * Get the localized descriptive name for a member of a group, if it exists
4590 * @param string $group Internal group name
4591 * @param string $username Username for gender (since 1.19)
4592 * @return string Localized name for group member
4594 public static function getGroupMember( $group, $username = '#' ) {
4595 $msg = wfMessage( "group-$group-member", $username );
4596 return $msg->isBlank() ?
$group : $msg->text();
4600 * Return the set of defined explicit groups.
4601 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4602 * are not included, as they are defined automatically, not in the database.
4603 * @return array Array of internal group names
4605 public static function getAllGroups() {
4606 global $wgGroupPermissions, $wgRevokePermissions;
4608 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4609 self
::getImplicitGroups()
4614 * Get a list of all available permissions.
4615 * @return string[] Array of permission names
4617 public static function getAllRights() {
4618 if ( self
::$mAllRights === false ) {
4619 global $wgAvailableRights;
4620 if ( count( $wgAvailableRights ) ) {
4621 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
4623 self
::$mAllRights = self
::$mCoreRights;
4625 Hooks
::run( 'UserGetAllRights', array( &self
::$mAllRights ) );
4627 return self
::$mAllRights;
4631 * Get a list of implicit groups
4632 * @return array Array of Strings Array of internal group names
4634 public static function getImplicitGroups() {
4635 global $wgImplicitGroups;
4637 $groups = $wgImplicitGroups;
4638 # Deprecated, use $wgImplicitGroups instead
4639 Hooks
::run( 'UserGetImplicitGroups', array( &$groups ), '1.25' );
4645 * Get the title of a page describing a particular group
4647 * @param string $group Internal group name
4648 * @return Title|bool Title of the page if it exists, false otherwise
4650 public static function getGroupPage( $group ) {
4651 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4652 if ( $msg->exists() ) {
4653 $title = Title
::newFromText( $msg->text() );
4654 if ( is_object( $title ) ) {
4662 * Create a link to the group in HTML, if available;
4663 * else return the group name.
4665 * @param string $group Internal name of the group
4666 * @param string $text The text of the link
4667 * @return string HTML link to the group
4669 public static function makeGroupLinkHTML( $group, $text = '' ) {
4670 if ( $text == '' ) {
4671 $text = self
::getGroupName( $group );
4673 $title = self
::getGroupPage( $group );
4675 return Linker
::link( $title, htmlspecialchars( $text ) );
4677 return htmlspecialchars( $text );
4682 * Create a link to the group in Wikitext, if available;
4683 * else return the group name.
4685 * @param string $group Internal name of the group
4686 * @param string $text The text of the link
4687 * @return string Wikilink to the group
4689 public static function makeGroupLinkWiki( $group, $text = '' ) {
4690 if ( $text == '' ) {
4691 $text = self
::getGroupName( $group );
4693 $title = self
::getGroupPage( $group );
4695 $page = $title->getFullText();
4696 return "[[$page|$text]]";
4703 * Returns an array of the groups that a particular group can add/remove.
4705 * @param string $group The group to check for whether it can add/remove
4706 * @return array Array( 'add' => array( addablegroups ),
4707 * 'remove' => array( removablegroups ),
4708 * 'add-self' => array( addablegroups to self),
4709 * 'remove-self' => array( removable groups from self) )
4711 public static function changeableByGroup( $group ) {
4712 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4716 'remove' => array(),
4717 'add-self' => array(),
4718 'remove-self' => array()
4721 if ( empty( $wgAddGroups[$group] ) ) {
4722 // Don't add anything to $groups
4723 } elseif ( $wgAddGroups[$group] === true ) {
4724 // You get everything
4725 $groups['add'] = self
::getAllGroups();
4726 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4727 $groups['add'] = $wgAddGroups[$group];
4730 // Same thing for remove
4731 if ( empty( $wgRemoveGroups[$group] ) ) {
4733 } elseif ( $wgRemoveGroups[$group] === true ) {
4734 $groups['remove'] = self
::getAllGroups();
4735 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4736 $groups['remove'] = $wgRemoveGroups[$group];
4739 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4740 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4741 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4742 if ( is_int( $key ) ) {
4743 $wgGroupsAddToSelf['user'][] = $value;
4748 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
4749 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4750 if ( is_int( $key ) ) {
4751 $wgGroupsRemoveFromSelf['user'][] = $value;
4756 // Now figure out what groups the user can add to him/herself
4757 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4759 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4760 // No idea WHY this would be used, but it's there
4761 $groups['add-self'] = User
::getAllGroups();
4762 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4763 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4766 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4768 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4769 $groups['remove-self'] = User
::getAllGroups();
4770 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4771 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4778 * Returns an array of groups that this user can add and remove
4779 * @return array Array( 'add' => array( addablegroups ),
4780 * 'remove' => array( removablegroups ),
4781 * 'add-self' => array( addablegroups to self),
4782 * 'remove-self' => array( removable groups from self) )
4784 public function changeableGroups() {
4785 if ( $this->isAllowed( 'userrights' ) ) {
4786 // This group gives the right to modify everything (reverse-
4787 // compatibility with old "userrights lets you change
4789 // Using array_merge to make the groups reindexed
4790 $all = array_merge( User
::getAllGroups() );
4794 'add-self' => array(),
4795 'remove-self' => array()
4799 // Okay, it's not so simple, we will have to go through the arrays
4802 'remove' => array(),
4803 'add-self' => array(),
4804 'remove-self' => array()
4806 $addergroups = $this->getEffectiveGroups();
4808 foreach ( $addergroups as $addergroup ) {
4809 $groups = array_merge_recursive(
4810 $groups, $this->changeableByGroup( $addergroup )
4812 $groups['add'] = array_unique( $groups['add'] );
4813 $groups['remove'] = array_unique( $groups['remove'] );
4814 $groups['add-self'] = array_unique( $groups['add-self'] );
4815 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4821 * Deferred version of incEditCountImmediate()
4823 public function incEditCount() {
4825 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle( function() use ( $that ) {
4826 $that->incEditCountImmediate();
4831 * Increment the user's edit-count field.
4832 * Will have no effect for anonymous users.
4835 public function incEditCountImmediate() {
4836 if ( $this->isAnon() ) {
4840 $dbw = wfGetDB( DB_MASTER
);
4841 // No rows will be "affected" if user_editcount is NULL
4844 array( 'user_editcount=user_editcount+1' ),
4845 array( 'user_id' => $this->getId(), 'user_editcount IS NOT NULL' ),
4848 // Lazy initialization check...
4849 if ( $dbw->affectedRows() == 0 ) {
4850 // Now here's a goddamn hack...
4851 $dbr = wfGetDB( DB_SLAVE
);
4852 if ( $dbr !== $dbw ) {
4853 // If we actually have a slave server, the count is
4854 // at least one behind because the current transaction
4855 // has not been committed and replicated.
4856 $this->initEditCount( 1 );
4858 // But if DB_SLAVE is selecting the master, then the
4859 // count we just read includes the revision that was
4860 // just added in the working transaction.
4861 $this->initEditCount();
4864 // Edit count in user cache too
4865 $this->invalidateCache();
4869 * Initialize user_editcount from data out of the revision table
4871 * @param int $add Edits to add to the count from the revision table
4872 * @return int Number of edits
4874 protected function initEditCount( $add = 0 ) {
4875 // Pull from a slave to be less cruel to servers
4876 // Accuracy isn't the point anyway here
4877 $dbr = wfGetDB( DB_SLAVE
);
4878 $count = (int)$dbr->selectField(
4881 array( 'rev_user' => $this->getId() ),
4884 $count = $count +
$add;
4886 $dbw = wfGetDB( DB_MASTER
);
4889 array( 'user_editcount' => $count ),
4890 array( 'user_id' => $this->getId() ),
4898 * Get the description of a given right
4900 * @param string $right Right to query
4901 * @return string Localized description of the right
4903 public static function getRightDescription( $right ) {
4904 $key = "right-$right";
4905 $msg = wfMessage( $key );
4906 return $msg->isBlank() ?
$right : $msg->text();
4910 * Make a new-style password hash
4912 * @param string $password Plain-text password
4913 * @param bool|string $salt Optional salt, may be random or the user ID.
4914 * If unspecified or false, will generate one automatically
4915 * @return string Password hash
4916 * @deprecated since 1.24, use Password class
4918 public static function crypt( $password, $salt = false ) {
4919 wfDeprecated( __METHOD__
, '1.24' );
4920 $passwordFactory = new PasswordFactory();
4921 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4922 $hash = $passwordFactory->newFromPlaintext( $password );
4923 return $hash->toString();
4927 * Compare a password hash with a plain-text password. Requires the user
4928 * ID if there's a chance that the hash is an old-style hash.
4930 * @param string $hash Password hash
4931 * @param string $password Plain-text password to compare
4932 * @param string|bool $userId User ID for old-style password salt
4935 * @deprecated since 1.24, use Password class
4937 public static function comparePasswords( $hash, $password, $userId = false ) {
4938 wfDeprecated( __METHOD__
, '1.24' );
4940 // Check for *really* old password hashes that don't even have a type
4941 // The old hash format was just an md5 hex hash, with no type information
4942 if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) {
4943 global $wgPasswordSalt;
4944 if ( $wgPasswordSalt ) {
4945 $password = ":B:{$userId}:{$hash}";
4947 $password = ":A:{$hash}";
4951 $passwordFactory = new PasswordFactory();
4952 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4953 $hash = $passwordFactory->newFromCiphertext( $hash );
4954 return $hash->equals( $password );
4958 * Add a newuser log entry for this user.
4959 * Before 1.19 the return value was always true.
4961 * @param string|bool $action Account creation type.
4962 * - String, one of the following values:
4963 * - 'create' for an anonymous user creating an account for himself.
4964 * This will force the action's performer to be the created user itself,
4965 * no matter the value of $wgUser
4966 * - 'create2' for a logged in user creating an account for someone else
4967 * - 'byemail' when the created user will receive its password by e-mail
4968 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
4969 * - Boolean means whether the account was created by e-mail (deprecated):
4970 * - true will be converted to 'byemail'
4971 * - false will be converted to 'create' if this object is the same as
4972 * $wgUser and to 'create2' otherwise
4974 * @param string $reason User supplied reason
4976 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
4978 public function addNewUserLogEntry( $action = false, $reason = '' ) {
4979 global $wgUser, $wgNewUserLog;
4980 if ( empty( $wgNewUserLog ) ) {
4981 return true; // disabled
4984 if ( $action === true ) {
4985 $action = 'byemail';
4986 } elseif ( $action === false ) {
4987 if ( $this->equals( $wgUser ) ) {
4990 $action = 'create2';
4994 if ( $action === 'create' ||
$action === 'autocreate' ) {
4997 $performer = $wgUser;
5000 $logEntry = new ManualLogEntry( 'newusers', $action );
5001 $logEntry->setPerformer( $performer );
5002 $logEntry->setTarget( $this->getUserPage() );
5003 $logEntry->setComment( $reason );
5004 $logEntry->setParameters( array(
5005 '4::userid' => $this->getId(),
5007 $logid = $logEntry->insert();
5009 if ( $action !== 'autocreate' ) {
5010 $logEntry->publish( $logid );
5017 * Add an autocreate newuser log entry for this user
5018 * Used by things like CentralAuth and perhaps other authplugins.
5019 * Consider calling addNewUserLogEntry() directly instead.
5023 public function addNewUserLogEntryAutoCreate() {
5024 $this->addNewUserLogEntry( 'autocreate' );
5030 * Load the user options either from cache, the database or an array
5032 * @param array $data Rows for the current user out of the user_properties table
5034 protected function loadOptions( $data = null ) {
5039 if ( $this->mOptionsLoaded
) {
5043 $this->mOptions
= self
::getDefaultOptions();
5045 if ( !$this->getId() ) {
5046 // For unlogged-in users, load language/variant options from request.
5047 // There's no need to do it for logged-in users: they can set preferences,
5048 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5049 // so don't override user's choice (especially when the user chooses site default).
5050 $variant = $wgContLang->getDefaultVariant();
5051 $this->mOptions
['variant'] = $variant;
5052 $this->mOptions
['language'] = $variant;
5053 $this->mOptionsLoaded
= true;
5057 // Maybe load from the object
5058 if ( !is_null( $this->mOptionOverrides
) ) {
5059 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5060 foreach ( $this->mOptionOverrides
as $key => $value ) {
5061 $this->mOptions
[$key] = $value;
5064 if ( !is_array( $data ) ) {
5065 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5066 // Load from database
5067 $dbr = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
5068 ?
wfGetDB( DB_MASTER
)
5069 : wfGetDB( DB_SLAVE
);
5071 $res = $dbr->select(
5073 array( 'up_property', 'up_value' ),
5074 array( 'up_user' => $this->getId() ),
5078 $this->mOptionOverrides
= array();
5080 foreach ( $res as $row ) {
5081 $data[$row->up_property
] = $row->up_value
;
5084 foreach ( $data as $property => $value ) {
5085 $this->mOptionOverrides
[$property] = $value;
5086 $this->mOptions
[$property] = $value;
5090 $this->mOptionsLoaded
= true;
5092 Hooks
::run( 'UserLoadOptions', array( $this, &$this->mOptions
) );
5096 * Saves the non-default options for this user, as previously set e.g. via
5097 * setOption(), in the database's "user_properties" (preferences) table.
5098 * Usually used via saveSettings().
5100 protected function saveOptions() {
5101 $this->loadOptions();
5103 // Not using getOptions(), to keep hidden preferences in database
5104 $saveOptions = $this->mOptions
;
5106 // Allow hooks to abort, for instance to save to a global profile.
5107 // Reset options to default state before saving.
5108 if ( !Hooks
::run( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
5112 $userId = $this->getId();
5114 $insert_rows = array(); // all the new preference rows
5115 foreach ( $saveOptions as $key => $value ) {
5116 // Don't bother storing default values
5117 $defaultOption = self
::getDefaultOption( $key );
5118 if ( ( $defaultOption === null && $value !== false && $value !== null )
5119 ||
$value != $defaultOption
5121 $insert_rows[] = array(
5122 'up_user' => $userId,
5123 'up_property' => $key,
5124 'up_value' => $value,
5129 $dbw = wfGetDB( DB_MASTER
);
5131 $res = $dbw->select( 'user_properties',
5132 array( 'up_property', 'up_value' ), array( 'up_user' => $userId ), __METHOD__
);
5134 // Find prior rows that need to be removed or updated. These rows will
5135 // all be deleted (the later so that INSERT IGNORE applies the new values).
5136 $keysDelete = array();
5137 foreach ( $res as $row ) {
5138 if ( !isset( $saveOptions[$row->up_property
] )
5139 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
5141 $keysDelete[] = $row->up_property
;
5145 if ( count( $keysDelete ) ) {
5146 // Do the DELETE by PRIMARY KEY for prior rows.
5147 // In the past a very large portion of calls to this function are for setting
5148 // 'rememberpassword' for new accounts (a preference that has since been removed).
5149 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5150 // caused gap locks on [max user ID,+infinity) which caused high contention since
5151 // updates would pile up on each other as they are for higher (newer) user IDs.
5152 // It might not be necessary these days, but it shouldn't hurt either.
5153 $dbw->delete( 'user_properties',
5154 array( 'up_user' => $userId, 'up_property' => $keysDelete ), __METHOD__
);
5156 // Insert the new preference rows
5157 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, array( 'IGNORE' ) );
5161 * Lazily instantiate and return a factory object for making passwords
5163 * @deprecated since 1.27, create a PasswordFactory directly instead
5164 * @return PasswordFactory
5166 public static function getPasswordFactory() {
5167 wfDeprecated( __METHOD__
, '1.27' );
5168 $ret = new PasswordFactory();
5169 $ret->init( RequestContext
::getMain()->getConfig() );
5174 * Provide an array of HTML5 attributes to put on an input element
5175 * intended for the user to enter a new password. This may include
5176 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
5178 * Do *not* use this when asking the user to enter his current password!
5179 * Regardless of configuration, users may have invalid passwords for whatever
5180 * reason (e.g., they were set before requirements were tightened up).
5181 * Only use it when asking for a new password, like on account creation or
5184 * Obviously, you still need to do server-side checking.
5186 * NOTE: A combination of bugs in various browsers means that this function
5187 * actually just returns array() unconditionally at the moment. May as
5188 * well keep it around for when the browser bugs get fixed, though.
5190 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
5192 * @deprecated since 1.27
5193 * @return array Array of HTML attributes suitable for feeding to
5194 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
5195 * That will get confused by the boolean attribute syntax used.)
5197 public static function passwordChangeInputAttribs() {
5198 global $wgMinimalPasswordLength;
5200 if ( $wgMinimalPasswordLength == 0 ) {
5204 # Note that the pattern requirement will always be satisfied if the
5205 # input is empty, so we need required in all cases.
5207 # @todo FIXME: Bug 23769: This needs to not claim the password is required
5208 # if e-mail confirmation is being used. Since HTML5 input validation
5209 # is b0rked anyway in some browsers, just return nothing. When it's
5210 # re-enabled, fix this code to not output required for e-mail
5212 # $ret = array( 'required' );
5215 # We can't actually do this right now, because Opera 9.6 will print out
5216 # the entered password visibly in its error message! When other
5217 # browsers add support for this attribute, or Opera fixes its support,
5218 # we can add support with a version check to avoid doing this on Opera
5219 # versions where it will be a problem. Reported to Opera as
5220 # DSK-262266, but they don't have a public bug tracker for us to follow.
5222 if ( $wgMinimalPasswordLength > 1 ) {
5223 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
5224 $ret['title'] = wfMessage( 'passwordtooshort' )
5225 ->numParams( $wgMinimalPasswordLength )->text();
5233 * Return the list of user fields that should be selected to create
5234 * a new user object.
5237 public static function selectFields() {
5245 'user_email_authenticated',
5247 'user_email_token_expires',
5248 'user_registration',
5254 * Factory function for fatal permission-denied errors
5257 * @param string $permission User right required
5260 static function newFatalPermissionDeniedStatus( $permission ) {
5263 $groups = array_map(
5264 array( 'User', 'makeGroupLinkWiki' ),
5265 User
::getGroupsWithPermission( $permission )
5269 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5271 return Status
::newFatal( 'badaccess-group0' );
5276 * Get a new instance of this user that was loaded from the master via a locking read
5278 * Use this instead of the main context User when updating that user. This avoids races
5279 * where that user was loaded from a slave or even the master but without proper locks.
5281 * @return User|null Returns null if the user was not found in the DB
5284 public function getInstanceForUpdate() {
5285 if ( !$this->getId() ) {
5286 return null; // anon
5289 $user = self
::newFromId( $this->getId() );
5290 if ( !$user->loadFromId( self
::READ_EXCLUSIVE
) ) {
5298 * Checks if two user objects point to the same user.
5304 public function equals( User
$user ) {
5305 return $this->getName() === $user->getName();