3 * Implements the User class for the %MediaWiki software.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use MediaWiki\Session\SessionManager
;
26 * String Some punctuation to prevent editing from broken text-mangling proxies.
27 * @deprecated since 1.27, use \\MediaWiki\\Session\\Token::SUFFIX
30 define( 'EDIT_TOKEN_SUFFIX', MediaWiki\Session\Token
::SUFFIX
);
33 * The User object encapsulates all of the user-specific settings (user_id,
34 * name, rights, email address, options, last login time). Client
35 * classes use the getXXX() functions to access these fields. These functions
36 * do all the work of determining whether the user is logged in,
37 * whether the requested option can be satisfied from cookies or
38 * whether a database query is needed. Most of the settings needed
39 * for rendering normal pages are set in the cookie to minimize use
42 class User
implements IDBAccessObject
{
44 * @const int Number of characters in user_token field.
46 const TOKEN_LENGTH
= 32;
49 * Global constant made accessible as class constants so that autoloader
51 * @deprecated since 1.27, use \\MediaWiki\\Session\\Token::SUFFIX
53 const EDIT_TOKEN_SUFFIX
= EDIT_TOKEN_SUFFIX
;
56 * @const int Serialized record version.
61 * Maximum items in $mWatchedItems
63 const MAX_WATCHED_ITEMS_CACHE
= 100;
66 * Exclude user options that are set to their default value.
69 const GETOPTIONS_EXCLUDE_DEFAULTS
= 1;
72 * Array of Strings List of member variables which are saved to the
73 * shared cache (memcached). Any operation which changes the
74 * corresponding database fields must call a cache-clearing function.
77 protected static $mCacheVars = array(
85 'mEmailAuthenticated',
92 // user_properties table
97 * Array of Strings Core rights.
98 * Each of these should have a corresponding message of the form
102 protected static $mCoreRights = array(
132 'editusercssjs', # deprecated
145 'move-categorypages',
146 'move-rootuserpages',
150 'override-export-depth',
173 'userrights-interwiki',
181 * String Cached results of getAllRights()
183 protected static $mAllRights = false;
185 /** Cache variables */
195 /** @var string TS_MW timestamp from the DB */
197 /** @var string TS_MW timestamp from cache */
198 protected $mQuickTouched;
202 public $mEmailAuthenticated;
204 protected $mEmailToken;
206 protected $mEmailTokenExpires;
208 protected $mRegistration;
210 protected $mEditCount;
214 protected $mOptionOverrides;
218 * Bool Whether the cache variables have been loaded.
221 public $mOptionsLoaded;
224 * Array with already loaded items or true if all items have been loaded.
226 protected $mLoadedItems = array();
230 * String Initialization data source if mLoadedItems!==true. May be one of:
231 * - 'defaults' anonymous user initialised from class defaults
232 * - 'name' initialise from mName
233 * - 'id' initialise from mId
234 * - 'session' log in from session if possible
236 * Use the User::newFrom*() family of functions to set this.
241 * Lazy-initialized variables, invalidated with clearInstanceCache
245 protected $mDatePreference;
253 protected $mBlockreason;
255 protected $mEffectiveGroups;
257 protected $mImplicitGroups;
259 protected $mFormerGroups;
261 protected $mBlockedGlobally;
278 protected $mAllowUsertalk;
281 private $mBlockedFromCreateAccount = false;
284 private $mWatchedItems = array();
286 /** @var integer User::READ_* constant bitfield used to load data */
287 protected $queryFlagsUsed = self
::READ_NORMAL
;
289 public static $idCacheByName = array();
292 * Lightweight constructor for an anonymous user.
293 * Use the User::newFrom* factory functions for other kinds of users.
297 * @see newFromConfirmationCode()
298 * @see newFromSession()
301 public function __construct() {
302 $this->clearInstanceCache( 'defaults' );
308 public function __toString() {
309 return $this->getName();
313 * Load the user table data for this object from the source given by mFrom.
315 * @param integer $flags User::READ_* constant bitfield
317 public function load( $flags = self
::READ_NORMAL
) {
318 global $wgFullyInitialised;
320 if ( $this->mLoadedItems
=== true ) {
324 // Set it now to avoid infinite recursion in accessors
325 $oldLoadedItems = $this->mLoadedItems
;
326 $this->mLoadedItems
= true;
327 $this->queryFlagsUsed
= $flags;
329 // If this is called too early, things are likely to break.
330 if ( $this->mFrom
=== 'session' && empty( $wgFullyInitialised ) ) {
331 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
332 ->warning( 'User::loadFromSession called before the end of Setup.php', array(
333 'exception' => new Exception( 'User::loadFromSession called before the end of Setup.php' ),
335 $this->loadDefaults();
336 $this->mLoadedItems
= $oldLoadedItems;
340 switch ( $this->mFrom
) {
342 $this->loadDefaults();
345 // Make sure this thread sees its own changes
346 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
347 $flags |
= self
::READ_LATEST
;
348 $this->queryFlagsUsed
= $flags;
351 $this->mId
= self
::idFromName( $this->mName
, $flags );
353 // Nonexistent user placeholder object
354 $this->loadDefaults( $this->mName
);
356 $this->loadFromId( $flags );
360 $this->loadFromId( $flags );
363 if ( !$this->loadFromSession() ) {
364 // Loading from session failed. Load defaults.
365 $this->loadDefaults();
367 Hooks
::run( 'UserLoadAfterLoadFromSession', array( $this ) );
370 throw new UnexpectedValueException(
371 "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
376 * Load user table data, given mId has already been set.
377 * @param integer $flags User::READ_* constant bitfield
378 * @return bool False if the ID does not exist, true otherwise
380 public function loadFromId( $flags = self
::READ_NORMAL
) {
381 if ( $this->mId
== 0 ) {
382 $this->loadDefaults();
386 // Try cache (unless this needs data from the master DB).
387 // NOTE: if this thread called saveSettings(), the cache was cleared.
388 $latest = DBAccessObjectUtils
::hasFlags( $flags, self
::READ_LATEST
);
389 if ( $latest ||
!$this->loadFromCache() ) {
390 wfDebug( "User: cache miss for user {$this->mId}\n" );
391 // Load from DB (make sure this thread sees its own changes)
392 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
393 $flags |
= self
::READ_LATEST
;
395 if ( !$this->loadFromDatabase( $flags ) ) {
396 // Can't load from ID, user is anonymous
399 $this->saveToCache();
402 $this->mLoadedItems
= true;
403 $this->queryFlagsUsed
= $flags;
410 * @param string $wikiId
411 * @param integer $userId
413 public static function purge( $wikiId, $userId ) {
414 $cache = ObjectCache
::getMainWANInstance();
415 $cache->delete( $cache->makeGlobalKey( 'user', 'id', $wikiId, $userId ) );
420 * @param WANObjectCache $cache
423 protected function getCacheKey( WANObjectCache
$cache ) {
424 return $cache->makeGlobalKey( 'user', 'id', wfWikiID(), $this->mId
);
428 * Load user data from shared cache, given mId has already been set.
430 * @return bool false if the ID does not exist or data is invalid, true otherwise
433 protected function loadFromCache() {
434 if ( $this->mId
== 0 ) {
435 $this->loadDefaults();
439 $cache = ObjectCache
::getMainWANInstance();
440 $data = $cache->get( $this->getCacheKey( $cache ) );
441 if ( !is_array( $data ) ||
$data['mVersion'] < self
::VERSION
) {
446 wfDebug( "User: got user {$this->mId} from cache\n" );
448 // Restore from cache
449 foreach ( self
::$mCacheVars as $name ) {
450 $this->$name = $data[$name];
457 * Save user data to the shared cache
459 * This method should not be called outside the User class
461 public function saveToCache() {
464 $this->loadOptions();
466 if ( $this->isAnon() ) {
467 // Anonymous users are uncached
472 foreach ( self
::$mCacheVars as $name ) {
473 $data[$name] = $this->$name;
475 $data['mVersion'] = self
::VERSION
;
476 $opts = Database
::getCacheSetOptions( wfGetDB( DB_SLAVE
) );
478 $cache = ObjectCache
::getMainWANInstance();
479 $key = $this->getCacheKey( $cache );
480 $cache->set( $key, $data, $cache::TTL_HOUR
, $opts );
483 /** @name newFrom*() static factory methods */
487 * Static factory method for creation from username.
489 * This is slightly less efficient than newFromId(), so use newFromId() if
490 * you have both an ID and a name handy.
492 * @param string $name Username, validated by Title::newFromText()
493 * @param string|bool $validate Validate username. Takes the same parameters as
494 * User::getCanonicalName(), except that true is accepted as an alias
495 * for 'valid', for BC.
497 * @return User|bool User object, or false if the username is invalid
498 * (e.g. if it contains illegal characters or is an IP address). If the
499 * username is not present in the database, the result will be a user object
500 * with a name, zero user ID and default settings.
502 public static function newFromName( $name, $validate = 'valid' ) {
503 if ( $validate === true ) {
506 $name = self
::getCanonicalName( $name, $validate );
507 if ( $name === false ) {
510 // Create unloaded user object
514 $u->setItemLoaded( 'name' );
520 * Static factory method for creation from a given user ID.
522 * @param int $id Valid user ID
523 * @return User The corresponding User object
525 public static function newFromId( $id ) {
529 $u->setItemLoaded( 'id' );
534 * Factory method to fetch whichever user has a given email confirmation code.
535 * This code is generated when an account is created or its e-mail address
538 * If the code is invalid or has expired, returns NULL.
540 * @param string $code Confirmation code
541 * @param int $flags User::READ_* bitfield
544 public static function newFromConfirmationCode( $code, $flags = 0 ) {
545 $db = ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
546 ?
wfGetDB( DB_MASTER
)
547 : wfGetDB( DB_SLAVE
);
549 $id = $db->selectField(
553 'user_email_token' => md5( $code ),
554 'user_email_token_expires > ' . $db->addQuotes( $db->timestamp() ),
558 return $id ? User
::newFromId( $id ) : null;
562 * Create a new user object using data from session. If the login
563 * credentials are invalid, the result is an anonymous user.
565 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
568 public static function newFromSession( WebRequest
$request = null ) {
570 $user->mFrom
= 'session';
571 $user->mRequest
= $request;
576 * Create a new user object from a user row.
577 * The row should have the following fields from the user table in it:
578 * - either user_name or user_id to load further data if needed (or both)
580 * - all other fields (email, etc.)
581 * It is useless to provide the remaining fields if either user_id,
582 * user_name and user_real_name are not provided because the whole row
583 * will be loaded once more from the database when accessing them.
585 * @param stdClass $row A row from the user table
586 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
589 public static function newFromRow( $row, $data = null ) {
591 $user->loadFromRow( $row, $data );
596 * Static factory method for creation of a "system" user from username.
598 * A "system" user is an account that's used to attribute logged actions
599 * taken by MediaWiki itself, as opposed to a bot or human user. Examples
600 * might include the 'Maintenance script' or 'Conversion script' accounts
601 * used by various scripts in the maintenance/ directory or accounts such
602 * as 'MediaWiki message delivery' used by the MassMessage extension.
604 * This can optionally create the user if it doesn't exist, and "steal" the
605 * account if it does exist.
607 * @param string $name Username
608 * @param array $options Options are:
609 * - validate: As for User::getCanonicalName(), default 'valid'
610 * - create: Whether to create the user if it doesn't already exist, default true
611 * - steal: Whether to reset the account's password and email if it
612 * already exists, default false
615 public static function newSystemUser( $name, $options = array() ) {
617 'validate' => 'valid',
622 $name = self
::getCanonicalName( $name, $options['validate'] );
623 if ( $name === false ) {
627 $dbw = wfGetDB( DB_MASTER
);
628 $row = $dbw->selectRow(
631 self
::selectFields(),
632 array( 'user_password', 'user_newpassword' )
634 array( 'user_name' => $name ),
638 // No user. Create it?
639 return $options['create'] ? self
::createNew( $name ) : null;
641 $user = self
::newFromRow( $row );
643 // A user is considered to exist as a non-system user if it has a
644 // password set, or a temporary password set, or an email set.
645 $passwordFactory = new PasswordFactory();
646 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
648 $password = $passwordFactory->newFromCiphertext( $row->user_password
);
649 } catch ( PasswordError
$e ) {
650 wfDebug( 'Invalid password hash found in database.' );
651 $password = PasswordFactory
::newInvalidPassword();
654 $newpassword = $passwordFactory->newFromCiphertext( $row->user_newpassword
);
655 } catch ( PasswordError
$e ) {
656 wfDebug( 'Invalid password hash found in database.' );
657 $newpassword = PasswordFactory
::newInvalidPassword();
659 if ( !$password instanceof InvalidPassword ||
!$newpassword instanceof InvalidPassword
662 // User exists. Steal it?
663 if ( !$options['steal'] ) {
667 $nopass = PasswordFactory
::newInvalidPassword()->toString();
672 'user_password' => $nopass,
673 'user_newpassword' => $nopass,
674 'user_newpass_time' => null,
676 array( 'user_id' => $user->getId() ),
679 $user->invalidateEmail();
680 $user->saveSettings();
683 SessionManager
::singleton()->preventSessionsForUser( $user->getName() );
691 * Get the username corresponding to a given user ID
692 * @param int $id User ID
693 * @return string|bool The corresponding username
695 public static function whoIs( $id ) {
696 return UserCache
::singleton()->getProp( $id, 'name' );
700 * Get the real name of a user given their user ID
702 * @param int $id User ID
703 * @return string|bool The corresponding user's real name
705 public static function whoIsReal( $id ) {
706 return UserCache
::singleton()->getProp( $id, 'real_name' );
710 * Get database id given a user name
711 * @param string $name Username
712 * @param integer $flags User::READ_* constant bitfield
713 * @return int|null The corresponding user's ID, or null if user is nonexistent
715 public static function idFromName( $name, $flags = self
::READ_NORMAL
) {
716 $nt = Title
::makeTitleSafe( NS_USER
, $name );
717 if ( is_null( $nt ) ) {
722 if ( !( $flags & self
::READ_LATEST
) && isset( self
::$idCacheByName[$name] ) ) {
723 return self
::$idCacheByName[$name];
726 $db = ( $flags & self
::READ_LATEST
)
727 ?
wfGetDB( DB_MASTER
)
728 : wfGetDB( DB_SLAVE
);
733 array( 'user_name' => $nt->getText() ),
737 if ( $s === false ) {
740 $result = $s->user_id
;
743 self
::$idCacheByName[$name] = $result;
745 if ( count( self
::$idCacheByName ) > 1000 ) {
746 self
::$idCacheByName = array();
753 * Reset the cache used in idFromName(). For use in tests.
755 public static function resetIdByNameCache() {
756 self
::$idCacheByName = array();
760 * Does the string match an anonymous IPv4 address?
762 * This function exists for username validation, in order to reject
763 * usernames which are similar in form to IP addresses. Strings such
764 * as 300.300.300.300 will return true because it looks like an IP
765 * address, despite not being strictly valid.
767 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
768 * address because the usemod software would "cloak" anonymous IP
769 * addresses like this, if we allowed accounts like this to be created
770 * new users could get the old edits of these anonymous users.
772 * @param string $name Name to match
775 public static function isIP( $name ) {
776 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
777 || IP
::isIPv6( $name );
781 * Is the input a valid username?
783 * Checks if the input is a valid username, we don't want an empty string,
784 * an IP address, anything that contains slashes (would mess up subpages),
785 * is longer than the maximum allowed username size or doesn't begin with
788 * @param string $name Name to match
791 public static function isValidUserName( $name ) {
792 global $wgContLang, $wgMaxNameChars;
795 || User
::isIP( $name )
796 ||
strpos( $name, '/' ) !== false
797 ||
strlen( $name ) > $wgMaxNameChars
798 ||
$name != $wgContLang->ucfirst( $name )
800 wfDebugLog( 'username', __METHOD__
.
801 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
805 // Ensure that the name can't be misresolved as a different title,
806 // such as with extra namespace keys at the start.
807 $parsed = Title
::newFromText( $name );
808 if ( is_null( $parsed )
809 ||
$parsed->getNamespace()
810 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
811 wfDebugLog( 'username', __METHOD__
.
812 ": '$name' invalid due to ambiguous prefixes" );
816 // Check an additional blacklist of troublemaker characters.
817 // Should these be merged into the title char list?
818 $unicodeBlacklist = '/[' .
819 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
820 '\x{00a0}' . # non-breaking space
821 '\x{2000}-\x{200f}' . # various whitespace
822 '\x{2028}-\x{202f}' . # breaks and control chars
823 '\x{3000}' . # ideographic space
824 '\x{e000}-\x{f8ff}' . # private use
826 if ( preg_match( $unicodeBlacklist, $name ) ) {
827 wfDebugLog( 'username', __METHOD__
.
828 ": '$name' invalid due to blacklisted characters" );
836 * Usernames which fail to pass this function will be blocked
837 * from user login and new account registrations, but may be used
838 * internally by batch processes.
840 * If an account already exists in this form, login will be blocked
841 * by a failure to pass this function.
843 * @param string $name Name to match
846 public static function isUsableName( $name ) {
847 global $wgReservedUsernames;
848 // Must be a valid username, obviously ;)
849 if ( !self
::isValidUserName( $name ) ) {
853 static $reservedUsernames = false;
854 if ( !$reservedUsernames ) {
855 $reservedUsernames = $wgReservedUsernames;
856 Hooks
::run( 'UserGetReservedNames', array( &$reservedUsernames ) );
859 // Certain names may be reserved for batch processes.
860 foreach ( $reservedUsernames as $reserved ) {
861 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
862 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
864 if ( $reserved == $name ) {
872 * Usernames which fail to pass this function will be blocked
873 * from new account registrations, but may be used internally
874 * either by batch processes or by user accounts which have
875 * already been created.
877 * Additional blacklisting may be added here rather than in
878 * isValidUserName() to avoid disrupting existing accounts.
880 * @param string $name String to match
883 public static function isCreatableName( $name ) {
884 global $wgInvalidUsernameCharacters;
886 // Ensure that the username isn't longer than 235 bytes, so that
887 // (at least for the builtin skins) user javascript and css files
888 // will work. (bug 23080)
889 if ( strlen( $name ) > 235 ) {
890 wfDebugLog( 'username', __METHOD__
.
891 ": '$name' invalid due to length" );
895 // Preg yells if you try to give it an empty string
896 if ( $wgInvalidUsernameCharacters !== '' ) {
897 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
898 wfDebugLog( 'username', __METHOD__
.
899 ": '$name' invalid due to wgInvalidUsernameCharacters" );
904 return self
::isUsableName( $name );
908 * Is the input a valid password for this user?
910 * @param string $password Desired password
913 public function isValidPassword( $password ) {
914 // simple boolean wrapper for getPasswordValidity
915 return $this->getPasswordValidity( $password ) === true;
919 * Given unvalidated password input, return error message on failure.
921 * @param string $password Desired password
922 * @return bool|string|array True on success, string or array of error message on failure
924 public function getPasswordValidity( $password ) {
925 $result = $this->checkPasswordValidity( $password );
926 if ( $result->isGood() ) {
930 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
931 $messages[] = $error['message'];
933 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
934 $messages[] = $warning['message'];
936 if ( count( $messages ) === 1 ) {
944 * Check if this is a valid password for this user
946 * Create a Status object based on the password's validity.
947 * The Status should be set to fatal if the user should not
948 * be allowed to log in, and should have any errors that
949 * would block changing the password.
951 * If the return value of this is not OK, the password
952 * should not be checked. If the return value is not Good,
953 * the password can be checked, but the user should not be
954 * able to set their password to this.
956 * @param string $password Desired password
957 * @param string $purpose one of 'login', 'create', 'reset'
961 public function checkPasswordValidity( $password, $purpose = 'login' ) {
962 global $wgPasswordPolicy;
964 $upp = new UserPasswordPolicy(
965 $wgPasswordPolicy['policies'],
966 $wgPasswordPolicy['checks']
969 $status = Status
::newGood();
970 $result = false; // init $result to false for the internal checks
972 if ( !Hooks
::run( 'isValidPassword', array( $password, &$result, $this ) ) ) {
973 $status->error( $result );
977 if ( $result === false ) {
978 $status->merge( $upp->checkUserPassword( $this, $password, $purpose ) );
980 } elseif ( $result === true ) {
983 $status->error( $result );
984 return $status; // the isValidPassword hook set a string $result and returned true
989 * Given unvalidated user input, return a canonical username, or false if
990 * the username is invalid.
991 * @param string $name User input
992 * @param string|bool $validate Type of validation to use:
993 * - false No validation
994 * - 'valid' Valid for batch processes
995 * - 'usable' Valid for batch processes and login
996 * - 'creatable' Valid for batch processes, login and account creation
998 * @throws InvalidArgumentException
999 * @return bool|string
1001 public static function getCanonicalName( $name, $validate = 'valid' ) {
1002 // Force usernames to capital
1004 $name = $wgContLang->ucfirst( $name );
1006 # Reject names containing '#'; these will be cleaned up
1007 # with title normalisation, but then it's too late to
1009 if ( strpos( $name, '#' ) !== false ) {
1013 // Clean up name according to title rules,
1014 // but only when validation is requested (bug 12654)
1015 $t = ( $validate !== false ) ?
1016 Title
::newFromText( $name ) : Title
::makeTitle( NS_USER
, $name );
1017 // Check for invalid titles
1018 if ( is_null( $t ) ) {
1022 // Reject various classes of invalid names
1024 $name = $wgAuth->getCanonicalName( $t->getText() );
1026 switch ( $validate ) {
1030 if ( !User
::isValidUserName( $name ) ) {
1035 if ( !User
::isUsableName( $name ) ) {
1040 if ( !User
::isCreatableName( $name ) ) {
1045 throw new InvalidArgumentException(
1046 'Invalid parameter value for $validate in ' . __METHOD__
);
1052 * Count the number of edits of a user
1054 * @param int $uid User ID to check
1055 * @return int The user's edit count
1057 * @deprecated since 1.21 in favour of User::getEditCount
1059 public static function edits( $uid ) {
1060 wfDeprecated( __METHOD__
, '1.21' );
1061 $user = self
::newFromId( $uid );
1062 return $user->getEditCount();
1066 * Return a random password.
1068 * @deprecated since 1.27, use PasswordFactory::generateRandomPasswordString()
1069 * @return string New random password
1071 public static function randomPassword() {
1072 global $wgMinimalPasswordLength;
1073 return PasswordFactory
::generateRandomPasswordString( $wgMinimalPasswordLength );
1077 * Set cached properties to default.
1079 * @note This no longer clears uncached lazy-initialised properties;
1080 * the constructor does that instead.
1082 * @param string|bool $name
1084 public function loadDefaults( $name = false ) {
1086 $this->mName
= $name;
1087 $this->mRealName
= '';
1089 $this->mOptionOverrides
= null;
1090 $this->mOptionsLoaded
= false;
1092 $loggedOut = $this->mRequest ?
$this->mRequest
->getSession()->getLoggedOutTimestamp() : 0;
1093 if ( $loggedOut !== 0 ) {
1094 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1096 $this->mTouched
= '1'; # Allow any pages to be cached
1099 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1100 $this->mEmailAuthenticated
= null;
1101 $this->mEmailToken
= '';
1102 $this->mEmailTokenExpires
= null;
1103 $this->mRegistration
= wfTimestamp( TS_MW
);
1104 $this->mGroups
= array();
1106 Hooks
::run( 'UserLoadDefaults', array( $this, $name ) );
1110 * Return whether an item has been loaded.
1112 * @param string $item Item to check. Current possibilities:
1116 * @param string $all 'all' to check if the whole object has been loaded
1117 * or any other string to check if only the item is available (e.g.
1121 public function isItemLoaded( $item, $all = 'all' ) {
1122 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1123 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1127 * Set that an item has been loaded
1129 * @param string $item
1131 protected function setItemLoaded( $item ) {
1132 if ( is_array( $this->mLoadedItems
) ) {
1133 $this->mLoadedItems
[$item] = true;
1138 * Load user data from the session.
1140 * @return bool True if the user is logged in, false otherwise.
1142 private function loadFromSession() {
1145 Hooks
::run( 'UserLoadFromSession', array( $this, &$result ), '1.27' );
1146 if ( $result !== null ) {
1150 // MediaWiki\Session\Session already did the necessary authentication of the user
1151 // returned here, so just use it if applicable.
1152 $session = $this->getRequest()->getSession();
1153 $user = $session->getUser();
1154 if ( $user->isLoggedIn() ) {
1155 $this->loadFromUserObject( $user );
1156 // Other code expects these to be set in the session, so set them.
1157 $session->set( 'wsUserID', $this->getId() );
1158 $session->set( 'wsUserName', $this->getName() );
1159 $session->set( 'wsToken', $this->getToken() );
1167 * Load user and user_group data from the database.
1168 * $this->mId must be set, this is how the user is identified.
1170 * @param integer $flags User::READ_* constant bitfield
1171 * @return bool True if the user exists, false if the user is anonymous
1173 public function loadFromDatabase( $flags = self
::READ_LATEST
) {
1175 $this->mId
= intval( $this->mId
);
1178 if ( !$this->mId
) {
1179 $this->loadDefaults();
1183 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
1184 $db = wfGetDB( $index );
1186 $s = $db->selectRow(
1188 self
::selectFields(),
1189 array( 'user_id' => $this->mId
),
1194 $this->queryFlagsUsed
= $flags;
1195 Hooks
::run( 'UserLoadFromDatabase', array( $this, &$s ) );
1197 if ( $s !== false ) {
1198 // Initialise user table data
1199 $this->loadFromRow( $s );
1200 $this->mGroups
= null; // deferred
1201 $this->getEditCount(); // revalidation for nulls
1206 $this->loadDefaults();
1212 * Initialize this object from a row from the user table.
1214 * @param stdClass $row Row from the user table to load.
1215 * @param array $data Further user data to load into the object
1217 * user_groups Array with groups out of the user_groups table
1218 * user_properties Array with properties out of the user_properties table
1220 protected function loadFromRow( $row, $data = null ) {
1223 $this->mGroups
= null; // deferred
1225 if ( isset( $row->user_name
) ) {
1226 $this->mName
= $row->user_name
;
1227 $this->mFrom
= 'name';
1228 $this->setItemLoaded( 'name' );
1233 if ( isset( $row->user_real_name
) ) {
1234 $this->mRealName
= $row->user_real_name
;
1235 $this->setItemLoaded( 'realname' );
1240 if ( isset( $row->user_id
) ) {
1241 $this->mId
= intval( $row->user_id
);
1242 $this->mFrom
= 'id';
1243 $this->setItemLoaded( 'id' );
1248 if ( isset( $row->user_id
) && isset( $row->user_name
) ) {
1249 self
::$idCacheByName[$row->user_name
] = $row->user_id
;
1252 if ( isset( $row->user_editcount
) ) {
1253 $this->mEditCount
= $row->user_editcount
;
1258 if ( isset( $row->user_touched
) ) {
1259 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1264 if ( isset( $row->user_token
) ) {
1265 // The definition for the column is binary(32), so trim the NULs
1266 // that appends. The previous definition was char(32), so trim
1268 $this->mToken
= rtrim( $row->user_token
, " \0" );
1269 if ( $this->mToken
=== '' ) {
1270 $this->mToken
= null;
1276 if ( isset( $row->user_email
) ) {
1277 $this->mEmail
= $row->user_email
;
1278 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1279 $this->mEmailToken
= $row->user_email_token
;
1280 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1281 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1287 $this->mLoadedItems
= true;
1290 if ( is_array( $data ) ) {
1291 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1292 $this->mGroups
= $data['user_groups'];
1294 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1295 $this->loadOptions( $data['user_properties'] );
1301 * Load the data for this user object from another user object.
1305 protected function loadFromUserObject( $user ) {
1307 $user->loadGroups();
1308 $user->loadOptions();
1309 foreach ( self
::$mCacheVars as $var ) {
1310 $this->$var = $user->$var;
1315 * Load the groups from the database if they aren't already loaded.
1317 private function loadGroups() {
1318 if ( is_null( $this->mGroups
) ) {
1319 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
1320 ?
wfGetDB( DB_MASTER
)
1321 : wfGetDB( DB_SLAVE
);
1322 $res = $db->select( 'user_groups',
1323 array( 'ug_group' ),
1324 array( 'ug_user' => $this->mId
),
1326 $this->mGroups
= array();
1327 foreach ( $res as $row ) {
1328 $this->mGroups
[] = $row->ug_group
;
1334 * Add the user to the group if he/she meets given criteria.
1336 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1337 * possible to remove manually via Special:UserRights. In such case it
1338 * will not be re-added automatically. The user will also not lose the
1339 * group if they no longer meet the criteria.
1341 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1343 * @return array Array of groups the user has been promoted to.
1345 * @see $wgAutopromoteOnce
1347 public function addAutopromoteOnceGroups( $event ) {
1348 global $wgAutopromoteOnceLogInRC, $wgAuth;
1350 if ( wfReadOnly() ||
!$this->getId() ) {
1354 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1355 if ( !count( $toPromote ) ) {
1359 if ( !$this->checkAndSetTouched() ) {
1360 return array(); // raced out (bug T48834)
1363 $oldGroups = $this->getGroups(); // previous groups
1364 foreach ( $toPromote as $group ) {
1365 $this->addGroup( $group );
1367 // update groups in external authentication database
1368 Hooks
::run( 'UserGroupsChanged', array( $this, $toPromote, array(), false ) );
1369 $wgAuth->updateExternalDBGroups( $this, $toPromote );
1371 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1373 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1374 $logEntry->setPerformer( $this );
1375 $logEntry->setTarget( $this->getUserPage() );
1376 $logEntry->setParameters( array(
1377 '4::oldgroups' => $oldGroups,
1378 '5::newgroups' => $newGroups,
1380 $logid = $logEntry->insert();
1381 if ( $wgAutopromoteOnceLogInRC ) {
1382 $logEntry->publish( $logid );
1389 * Bump user_touched if it didn't change since this object was loaded
1391 * On success, the mTouched field is updated.
1392 * The user serialization cache is always cleared.
1394 * @return bool Whether user_touched was actually updated
1397 protected function checkAndSetTouched() {
1400 if ( !$this->mId
) {
1401 return false; // anon
1404 // Get a new user_touched that is higher than the old one
1405 $oldTouched = $this->mTouched
;
1406 $newTouched = $this->newTouchedTimestamp();
1408 $dbw = wfGetDB( DB_MASTER
);
1409 $dbw->update( 'user',
1410 array( 'user_touched' => $dbw->timestamp( $newTouched ) ),
1412 'user_id' => $this->mId
,
1413 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
1417 $success = ( $dbw->affectedRows() > 0 );
1420 $this->mTouched
= $newTouched;
1421 $this->clearSharedCache();
1423 // Clears on failure too since that is desired if the cache is stale
1424 $this->clearSharedCache( 'refresh' );
1431 * Clear various cached data stored in this object. The cache of the user table
1432 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1434 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1435 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1437 public function clearInstanceCache( $reloadFrom = false ) {
1438 $this->mNewtalk
= -1;
1439 $this->mDatePreference
= null;
1440 $this->mBlockedby
= -1; # Unset
1441 $this->mHash
= false;
1442 $this->mRights
= null;
1443 $this->mEffectiveGroups
= null;
1444 $this->mImplicitGroups
= null;
1445 $this->mGroups
= null;
1446 $this->mOptions
= null;
1447 $this->mOptionsLoaded
= false;
1448 $this->mEditCount
= null;
1450 if ( $reloadFrom ) {
1451 $this->mLoadedItems
= array();
1452 $this->mFrom
= $reloadFrom;
1457 * Combine the language default options with any site-specific options
1458 * and add the default language variants.
1460 * @return array Array of String options
1462 public static function getDefaultOptions() {
1463 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1465 static $defOpt = null;
1466 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1467 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1468 // mid-request and see that change reflected in the return value of this function.
1469 // Which is insane and would never happen during normal MW operation
1473 $defOpt = $wgDefaultUserOptions;
1474 // Default language setting
1475 $defOpt['language'] = $wgContLang->getCode();
1476 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1477 $defOpt[$langCode == $wgContLang->getCode() ?
'variant' : "variant-$langCode"] = $langCode;
1479 foreach ( SearchEngine
::searchableNamespaces() as $nsnum => $nsname ) {
1480 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1482 $defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1484 Hooks
::run( 'UserGetDefaultOptions', array( &$defOpt ) );
1490 * Get a given default option value.
1492 * @param string $opt Name of option to retrieve
1493 * @return string Default option value
1495 public static function getDefaultOption( $opt ) {
1496 $defOpts = self
::getDefaultOptions();
1497 if ( isset( $defOpts[$opt] ) ) {
1498 return $defOpts[$opt];
1505 * Get blocking information
1506 * @param bool $bFromSlave Whether to check the slave database first.
1507 * To improve performance, non-critical checks are done against slaves.
1508 * Check when actually saving should be done against master.
1510 private function getBlockedStatus( $bFromSlave = true ) {
1511 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1513 if ( -1 != $this->mBlockedby
) {
1517 wfDebug( __METHOD__
. ": checking...\n" );
1519 // Initialize data...
1520 // Otherwise something ends up stomping on $this->mBlockedby when
1521 // things get lazy-loaded later, causing false positive block hits
1522 // due to -1 !== 0. Probably session-related... Nothing should be
1523 // overwriting mBlockedby, surely?
1526 # We only need to worry about passing the IP address to the Block generator if the
1527 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1528 # know which IP address they're actually coming from
1529 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->equals( $wgUser ) ) {
1530 $ip = $this->getRequest()->getIP();
1536 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1539 if ( !$block instanceof Block
&& $ip !== null && !in_array( $ip, $wgProxyWhitelist ) ) {
1541 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1543 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1544 $block->mReason
= wfMessage( 'proxyblockreason' )->text();
1545 $block->setTarget( $ip );
1546 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1548 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1549 $block->mReason
= wfMessage( 'sorbsreason' )->text();
1550 $block->setTarget( $ip );
1554 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1555 if ( !$block instanceof Block
1556 && $wgApplyIpBlocksToXff
1558 && !in_array( $ip, $wgProxyWhitelist )
1560 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1561 $xff = array_map( 'trim', explode( ',', $xff ) );
1562 $xff = array_diff( $xff, array( $ip ) );
1563 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1564 $block = Block
::chooseBlock( $xffblocks, $xff );
1565 if ( $block instanceof Block
) {
1566 # Mangle the reason to alert the user that the block
1567 # originated from matching the X-Forwarded-For header.
1568 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->text();
1572 if ( $block instanceof Block
) {
1573 wfDebug( __METHOD__
. ": Found block.\n" );
1574 $this->mBlock
= $block;
1575 $this->mBlockedby
= $block->getByName();
1576 $this->mBlockreason
= $block->mReason
;
1577 $this->mHideName
= $block->mHideName
;
1578 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1580 $this->mBlockedby
= '';
1581 $this->mHideName
= 0;
1582 $this->mAllowUsertalk
= false;
1586 Hooks
::run( 'GetBlockedStatus', array( &$this ) );
1591 * Whether the given IP is in a DNS blacklist.
1593 * @param string $ip IP to check
1594 * @param bool $checkWhitelist Whether to check the whitelist first
1595 * @return bool True if blacklisted.
1597 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1598 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1600 if ( !$wgEnableDnsBlacklist ) {
1604 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1608 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1612 * Whether the given IP is in a given DNS blacklist.
1614 * @param string $ip IP to check
1615 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1616 * @return bool True if blacklisted.
1618 public function inDnsBlacklist( $ip, $bases ) {
1621 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1622 if ( IP
::isIPv4( $ip ) ) {
1623 // Reverse IP, bug 21255
1624 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1626 foreach ( (array)$bases as $base ) {
1628 // If we have an access key, use that too (ProjectHoneypot, etc.)
1630 if ( is_array( $base ) ) {
1631 if ( count( $base ) >= 2 ) {
1632 // Access key is 1, base URL is 0
1633 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1635 $host = "$ipReversed.{$base[0]}";
1637 $basename = $base[0];
1639 $host = "$ipReversed.$base";
1643 $ipList = gethostbynamel( $host );
1646 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
1650 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
1659 * Check if an IP address is in the local proxy list
1665 public static function isLocallyBlockedProxy( $ip ) {
1666 global $wgProxyList;
1668 if ( !$wgProxyList ) {
1672 if ( !is_array( $wgProxyList ) ) {
1673 // Load from the specified file
1674 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1677 if ( !is_array( $wgProxyList ) ) {
1679 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1681 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1682 // Old-style flipped proxy list
1691 * Is this user subject to rate limiting?
1693 * @return bool True if rate limited
1695 public function isPingLimitable() {
1696 global $wgRateLimitsExcludedIPs;
1697 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1698 // No other good way currently to disable rate limits
1699 // for specific IPs. :P
1700 // But this is a crappy hack and should die.
1703 return !$this->isAllowed( 'noratelimit' );
1707 * Primitive rate limits: enforce maximum actions per time period
1708 * to put a brake on flooding.
1710 * The method generates both a generic profiling point and a per action one
1711 * (suffix being "-$action".
1713 * @note When using a shared cache like memcached, IP-address
1714 * last-hit counters will be shared across wikis.
1716 * @param string $action Action to enforce; 'edit' if unspecified
1717 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1718 * @return bool True if a rate limiter was tripped
1720 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1721 // Call the 'PingLimiter' hook
1723 if ( !Hooks
::run( 'PingLimiter', array( &$this, $action, &$result, $incrBy ) ) ) {
1727 global $wgRateLimits;
1728 if ( !isset( $wgRateLimits[$action] ) ) {
1732 // Some groups shouldn't trigger the ping limiter, ever
1733 if ( !$this->isPingLimitable() ) {
1737 $limits = $wgRateLimits[$action];
1739 $id = $this->getId();
1742 if ( isset( $limits['anon'] ) && $id == 0 ) {
1743 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1746 if ( isset( $limits['user'] ) && $id != 0 ) {
1747 $userLimit = $limits['user'];
1749 if ( $this->isNewbie() ) {
1750 if ( isset( $limits['newbie'] ) && $id != 0 ) {
1751 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1753 if ( isset( $limits['ip'] ) ) {
1754 $ip = $this->getRequest()->getIP();
1755 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1757 if ( isset( $limits['subnet'] ) ) {
1758 $ip = $this->getRequest()->getIP();
1761 if ( IP
::isIPv6( $ip ) ) {
1762 $parts = IP
::parseRange( "$ip/64" );
1763 $subnet = $parts[0];
1764 } elseif ( preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1766 $subnet = $matches[1];
1768 if ( $subnet !== false ) {
1769 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1773 // Check for group-specific permissions
1774 // If more than one group applies, use the group with the highest limit
1775 foreach ( $this->getGroups() as $group ) {
1776 if ( isset( $limits[$group] ) ) {
1777 if ( $userLimit === false
1778 ||
$limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1780 $userLimit = $limits[$group];
1784 // Set the user limit key
1785 if ( $userLimit !== false ) {
1786 list( $max, $period ) = $userLimit;
1787 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
1788 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1791 $cache = ObjectCache
::getLocalClusterInstance();
1794 foreach ( $keys as $key => $limit ) {
1795 list( $max, $period ) = $limit;
1796 $summary = "(limit $max in {$period}s)";
1797 $count = $cache->get( $key );
1800 if ( $count >= $max ) {
1801 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1802 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1805 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1808 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1809 if ( $incrBy > 0 ) {
1810 $cache->add( $key, 0, intval( $period ) ); // first ping
1813 if ( $incrBy > 0 ) {
1814 $cache->incr( $key, $incrBy );
1822 * Check if user is blocked
1824 * @param bool $bFromSlave Whether to check the slave database instead of
1825 * the master. Hacked from false due to horrible probs on site.
1826 * @return bool True if blocked, false otherwise
1828 public function isBlocked( $bFromSlave = true ) {
1829 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
1833 * Get the block affecting the user, or null if the user is not blocked
1835 * @param bool $bFromSlave Whether to check the slave database instead of the master
1836 * @return Block|null
1838 public function getBlock( $bFromSlave = true ) {
1839 $this->getBlockedStatus( $bFromSlave );
1840 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
1844 * Check if user is blocked from editing a particular article
1846 * @param Title $title Title to check
1847 * @param bool $bFromSlave Whether to check the slave database instead of the master
1850 public function isBlockedFrom( $title, $bFromSlave = false ) {
1851 global $wgBlockAllowsUTEdit;
1853 $blocked = $this->isBlocked( $bFromSlave );
1854 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
1855 // If a user's name is suppressed, they cannot make edits anywhere
1856 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName()
1857 && $title->getNamespace() == NS_USER_TALK
) {
1859 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
1862 Hooks
::run( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1868 * If user is blocked, return the name of the user who placed the block
1869 * @return string Name of blocker
1871 public function blockedBy() {
1872 $this->getBlockedStatus();
1873 return $this->mBlockedby
;
1877 * If user is blocked, return the specified reason for the block
1878 * @return string Blocking reason
1880 public function blockedFor() {
1881 $this->getBlockedStatus();
1882 return $this->mBlockreason
;
1886 * If user is blocked, return the ID for the block
1887 * @return int Block ID
1889 public function getBlockId() {
1890 $this->getBlockedStatus();
1891 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
1895 * Check if user is blocked on all wikis.
1896 * Do not use for actual edit permission checks!
1897 * This is intended for quick UI checks.
1899 * @param string $ip IP address, uses current client if none given
1900 * @return bool True if blocked, false otherwise
1902 public function isBlockedGlobally( $ip = '' ) {
1903 if ( $this->mBlockedGlobally
!== null ) {
1904 return $this->mBlockedGlobally
;
1906 // User is already an IP?
1907 if ( IP
::isIPAddress( $this->getName() ) ) {
1908 $ip = $this->getName();
1910 $ip = $this->getRequest()->getIP();
1913 Hooks
::run( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1914 $this->mBlockedGlobally
= (bool)$blocked;
1915 return $this->mBlockedGlobally
;
1919 * Check if user account is locked
1921 * @return bool True if locked, false otherwise
1923 public function isLocked() {
1924 if ( $this->mLocked
!== null ) {
1925 return $this->mLocked
;
1928 $authUser = $wgAuth->getUserInstance( $this );
1929 $this->mLocked
= (bool)$authUser->isLocked();
1930 Hooks
::run( 'UserIsLocked', array( $this, &$this->mLocked
) );
1931 return $this->mLocked
;
1935 * Check if user account is hidden
1937 * @return bool True if hidden, false otherwise
1939 public function isHidden() {
1940 if ( $this->mHideName
!== null ) {
1941 return $this->mHideName
;
1943 $this->getBlockedStatus();
1944 if ( !$this->mHideName
) {
1946 $authUser = $wgAuth->getUserInstance( $this );
1947 $this->mHideName
= (bool)$authUser->isHidden();
1948 Hooks
::run( 'UserIsHidden', array( $this, &$this->mHideName
) );
1950 return $this->mHideName
;
1954 * Get the user's ID.
1955 * @return int The user's ID; 0 if the user is anonymous or nonexistent
1957 public function getId() {
1958 if ( $this->mId
=== null && $this->mName
!== null && User
::isIP( $this->mName
) ) {
1959 // Special case, we know the user is anonymous
1961 } elseif ( !$this->isItemLoaded( 'id' ) ) {
1962 // Don't load if this was initialized from an ID
1969 * Set the user and reload all fields according to a given ID
1970 * @param int $v User ID to reload
1972 public function setId( $v ) {
1974 $this->clearInstanceCache( 'id' );
1978 * Get the user name, or the IP of an anonymous user
1979 * @return string User's name or IP address
1981 public function getName() {
1982 if ( $this->isItemLoaded( 'name', 'only' ) ) {
1983 // Special case optimisation
1984 return $this->mName
;
1987 if ( $this->mName
=== false ) {
1989 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
1991 return $this->mName
;
1996 * Set the user name.
1998 * This does not reload fields from the database according to the given
1999 * name. Rather, it is used to create a temporary "nonexistent user" for
2000 * later addition to the database. It can also be used to set the IP
2001 * address for an anonymous user to something other than the current
2004 * @note User::newFromName() has roughly the same function, when the named user
2006 * @param string $str New user name to set
2008 public function setName( $str ) {
2010 $this->mName
= $str;
2014 * Get the user's name escaped by underscores.
2015 * @return string Username escaped by underscores.
2017 public function getTitleKey() {
2018 return str_replace( ' ', '_', $this->getName() );
2022 * Check if the user has new messages.
2023 * @return bool True if the user has new messages
2025 public function getNewtalk() {
2028 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2029 if ( $this->mNewtalk
=== -1 ) {
2030 $this->mNewtalk
= false; # reset talk page status
2032 // Check memcached separately for anons, who have no
2033 // entire User object stored in there.
2034 if ( !$this->mId
) {
2035 global $wgDisableAnonTalk;
2036 if ( $wgDisableAnonTalk ) {
2037 // Anon newtalk disabled by configuration.
2038 $this->mNewtalk
= false;
2040 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
2043 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2047 return (bool)$this->mNewtalk
;
2051 * Return the data needed to construct links for new talk page message
2052 * alerts. If there are new messages, this will return an associative array
2053 * with the following data:
2054 * wiki: The database name of the wiki
2055 * link: Root-relative link to the user's talk page
2056 * rev: The last talk page revision that the user has seen or null. This
2057 * is useful for building diff links.
2058 * If there are no new messages, it returns an empty array.
2059 * @note This function was designed to accomodate multiple talk pages, but
2060 * currently only returns a single link and revision.
2063 public function getNewMessageLinks() {
2065 if ( !Hooks
::run( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) ) {
2067 } elseif ( !$this->getNewtalk() ) {
2070 $utp = $this->getTalkPage();
2071 $dbr = wfGetDB( DB_SLAVE
);
2072 // Get the "last viewed rev" timestamp from the oldest message notification
2073 $timestamp = $dbr->selectField( 'user_newtalk',
2074 'MIN(user_last_timestamp)',
2075 $this->isAnon() ?
array( 'user_ip' => $this->getName() ) : array( 'user_id' => $this->getID() ),
2077 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2078 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ) );
2082 * Get the revision ID for the last talk page revision viewed by the talk
2084 * @return int|null Revision ID or null
2086 public function getNewMessageRevisionId() {
2087 $newMessageRevisionId = null;
2088 $newMessageLinks = $this->getNewMessageLinks();
2089 if ( $newMessageLinks ) {
2090 // Note: getNewMessageLinks() never returns more than a single link
2091 // and it is always for the same wiki, but we double-check here in
2092 // case that changes some time in the future.
2093 if ( count( $newMessageLinks ) === 1
2094 && $newMessageLinks[0]['wiki'] === wfWikiID()
2095 && $newMessageLinks[0]['rev']
2097 /** @var Revision $newMessageRevision */
2098 $newMessageRevision = $newMessageLinks[0]['rev'];
2099 $newMessageRevisionId = $newMessageRevision->getId();
2102 return $newMessageRevisionId;
2106 * Internal uncached check for new messages
2109 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2110 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2111 * @return bool True if the user has new messages
2113 protected function checkNewtalk( $field, $id ) {
2114 $dbr = wfGetDB( DB_SLAVE
);
2116 $ok = $dbr->selectField( 'user_newtalk', $field, array( $field => $id ), __METHOD__
);
2118 return $ok !== false;
2122 * Add or update the new messages flag
2123 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2124 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2125 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2126 * @return bool True if successful, false otherwise
2128 protected function updateNewtalk( $field, $id, $curRev = null ) {
2129 // Get timestamp of the talk page revision prior to the current one
2130 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2131 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2132 // Mark the user as having new messages since this revision
2133 $dbw = wfGetDB( DB_MASTER
);
2134 $dbw->insert( 'user_newtalk',
2135 array( $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ),
2138 if ( $dbw->affectedRows() ) {
2139 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2142 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2148 * Clear the new messages flag for the given user
2149 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2150 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2151 * @return bool True if successful, false otherwise
2153 protected function deleteNewtalk( $field, $id ) {
2154 $dbw = wfGetDB( DB_MASTER
);
2155 $dbw->delete( 'user_newtalk',
2156 array( $field => $id ),
2158 if ( $dbw->affectedRows() ) {
2159 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2162 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2168 * Update the 'You have new messages!' status.
2169 * @param bool $val Whether the user has new messages
2170 * @param Revision $curRev New, as yet unseen revision of the user talk
2171 * page. Ignored if null or !$val.
2173 public function setNewtalk( $val, $curRev = null ) {
2174 if ( wfReadOnly() ) {
2179 $this->mNewtalk
= $val;
2181 if ( $this->isAnon() ) {
2183 $id = $this->getName();
2186 $id = $this->getId();
2190 $changed = $this->updateNewtalk( $field, $id, $curRev );
2192 $changed = $this->deleteNewtalk( $field, $id );
2196 $this->invalidateCache();
2201 * Generate a current or new-future timestamp to be stored in the
2202 * user_touched field when we update things.
2203 * @return string Timestamp in TS_MW format
2205 private function newTouchedTimestamp() {
2206 global $wgClockSkewFudge;
2208 $time = wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2209 if ( $this->mTouched
&& $time <= $this->mTouched
) {
2210 $time = wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $this->mTouched
) +
1 );
2217 * Clear user data from memcached
2219 * Use after applying updates to the database; caller's
2220 * responsibility to update user_touched if appropriate.
2222 * Called implicitly from invalidateCache() and saveSettings().
2224 * @param string $mode Use 'refresh' to clear now; otherwise before DB commit
2226 public function clearSharedCache( $mode = 'changed' ) {
2227 if ( !$this->getId() ) {
2231 $cache = ObjectCache
::getMainWANInstance();
2232 $key = $this->getCacheKey( $cache );
2233 if ( $mode === 'refresh' ) {
2234 $cache->delete( $key, 1 );
2236 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle( function() use ( $cache, $key ) {
2237 $cache->delete( $key );
2243 * Immediately touch the user data cache for this account
2245 * Calls touch() and removes account data from memcached
2247 public function invalidateCache() {
2249 $this->clearSharedCache();
2253 * Update the "touched" timestamp for the user
2255 * This is useful on various login/logout events when making sure that
2256 * a browser or proxy that has multiple tenants does not suffer cache
2257 * pollution where the new user sees the old users content. The value
2258 * of getTouched() is checked when determining 304 vs 200 responses.
2259 * Unlike invalidateCache(), this preserves the User object cache and
2260 * avoids database writes.
2264 public function touch() {
2265 $id = $this->getId();
2267 $key = wfMemcKey( 'user-quicktouched', 'id', $id );
2268 ObjectCache
::getMainWANInstance()->touchCheckKey( $key );
2269 $this->mQuickTouched
= null;
2274 * Validate the cache for this account.
2275 * @param string $timestamp A timestamp in TS_MW format
2278 public function validateCache( $timestamp ) {
2279 return ( $timestamp >= $this->getTouched() );
2283 * Get the user touched timestamp
2285 * Use this value only to validate caches via inequalities
2286 * such as in the case of HTTP If-Modified-Since response logic
2288 * @return string TS_MW Timestamp
2290 public function getTouched() {
2294 if ( $this->mQuickTouched
=== null ) {
2295 $key = wfMemcKey( 'user-quicktouched', 'id', $this->mId
);
2296 $cache = ObjectCache
::getMainWANInstance();
2298 $this->mQuickTouched
= wfTimestamp( TS_MW
, $cache->getCheckKeyTime( $key ) );
2301 return max( $this->mTouched
, $this->mQuickTouched
);
2304 return $this->mTouched
;
2308 * Get the user_touched timestamp field (time of last DB updates)
2309 * @return string TS_MW Timestamp
2312 public function getDBTouched() {
2315 return $this->mTouched
;
2319 * @deprecated Removed in 1.27.
2323 public function getPassword() {
2324 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2328 * @deprecated Removed in 1.27.
2332 public function getTemporaryPassword() {
2333 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2337 * Set the password and reset the random token.
2338 * Calls through to authentication plugin if necessary;
2339 * will have no effect if the auth plugin refuses to
2340 * pass the change through or if the legal password
2343 * As a special case, setting the password to null
2344 * wipes it, so the account cannot be logged in until
2345 * a new password is set, for instance via e-mail.
2347 * @deprecated since 1.27. AuthManager is coming.
2348 * @param string $str New password to set
2349 * @throws PasswordError On failure
2352 public function setPassword( $str ) {
2355 if ( $str !== null ) {
2356 if ( !$wgAuth->allowPasswordChange() ) {
2357 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2360 $status = $this->checkPasswordValidity( $str );
2361 if ( !$status->isGood() ) {
2362 throw new PasswordError( $status->getMessage()->text() );
2366 if ( !$wgAuth->setPassword( $this, $str ) ) {
2367 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2371 $this->setOption( 'watchlisttoken', false );
2372 $this->setPasswordInternal( $str );
2378 * Set the password and reset the random token unconditionally.
2380 * @deprecated since 1.27. AuthManager is coming.
2381 * @param string|null $str New password to set or null to set an invalid
2382 * password hash meaning that the user will not be able to log in
2383 * through the web interface.
2385 public function setInternalPassword( $str ) {
2388 if ( $wgAuth->allowSetLocalPassword() ) {
2390 $this->setOption( 'watchlisttoken', false );
2391 $this->setPasswordInternal( $str );
2396 * Actually set the password and such
2397 * @since 1.27 cannot set a password for a user not in the database
2398 * @param string|null $str New password to set or null to set an invalid
2399 * password hash meaning that the user will not be able to log in
2400 * through the web interface.
2402 private function setPasswordInternal( $str ) {
2403 $id = self
::idFromName( $this->getName(), self
::READ_LATEST
);
2405 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2408 $passwordFactory = new PasswordFactory();
2409 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
2410 $dbw = wfGetDB( DB_MASTER
);
2414 'user_password' => $passwordFactory->newFromPlaintext( $str )->toString(),
2415 'user_newpassword' => PasswordFactory
::newInvalidPassword()->toString(),
2416 'user_newpass_time' => $dbw->timestampOrNull( null ),
2424 // When the main password is changed, invalidate all bot passwords too
2425 BotPassword
::invalidateAllPasswordsForUser( $this->getName() );
2429 * Get the user's current token.
2430 * @param bool $forceCreation Force the generation of a new token if the
2431 * user doesn't have one (default=true for backwards compatibility).
2432 * @return string|null Token
2434 public function getToken( $forceCreation = true ) {
2435 global $wgAuthenticationTokenVersion;
2438 if ( !$this->mToken
&& $forceCreation ) {
2442 // If the user doesn't have a token, return null to indicate that.
2443 // Otherwise, hmac the version with the secret if we have a version.
2444 if ( !$this->mToken
) {
2446 } elseif ( $wgAuthenticationTokenVersion === null ) {
2447 return $this->mToken
;
2449 $ret = MWCryptHash
::hmac( $wgAuthenticationTokenVersion, $this->mToken
, false );
2451 // The raw hash can be overly long. Shorten it up.
2452 $len = max( 32, self
::TOKEN_LENGTH
);
2453 if ( strlen( $ret ) < $len ) {
2454 // Should never happen, even md5 is 128 bits
2455 throw new \
UnexpectedValueException( 'Hmac returned less than 128 bits' );
2457 return substr( $ret, -$len );
2462 * Set the random token (used for persistent authentication)
2463 * Called from loadDefaults() among other places.
2465 * @param string|bool $token If specified, set the token to this value
2467 public function setToken( $token = false ) {
2470 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2472 $this->mToken
= $token;
2477 * Set the password for a password reminder or new account email
2479 * @deprecated since 1.27, AuthManager is coming
2480 * @param string $str New password to set or null to set an invalid
2481 * password hash meaning that the user will not be able to use it
2482 * @param bool $throttle If true, reset the throttle timestamp to the present
2484 public function setNewpassword( $str, $throttle = true ) {
2485 $id = $this->getId();
2487 throw new LogicException( 'Cannot set new password for a user that is not in the database.' );
2490 $dbw = wfGetDB( DB_MASTER
);
2492 $passwordFactory = new PasswordFactory();
2493 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
2495 'user_newpassword' => $passwordFactory->newFromPlaintext( $str )->toString(),
2498 if ( $str === null ) {
2499 $update['user_newpass_time'] = null;
2500 } elseif ( $throttle ) {
2501 $update['user_newpass_time'] = $dbw->timestamp();
2504 $dbw->update( 'user', $update, array( 'user_id' => $id ), __METHOD__
);
2508 * Has password reminder email been sent within the last
2509 * $wgPasswordReminderResendTime hours?
2512 public function isPasswordReminderThrottled() {
2513 global $wgPasswordReminderResendTime;
2515 if ( !$wgPasswordReminderResendTime ) {
2521 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
2522 ?
wfGetDB( DB_MASTER
)
2523 : wfGetDB( DB_SLAVE
);
2524 $newpassTime = $db->selectField(
2526 'user_newpass_time',
2527 array( 'user_id' => $this->getId() ),
2531 if ( $newpassTime === null ) {
2534 $expiry = wfTimestamp( TS_UNIX
, $newpassTime ) +
$wgPasswordReminderResendTime * 3600;
2535 return time() < $expiry;
2539 * Get the user's e-mail address
2540 * @return string User's email address
2542 public function getEmail() {
2544 Hooks
::run( 'UserGetEmail', array( $this, &$this->mEmail
) );
2545 return $this->mEmail
;
2549 * Get the timestamp of the user's e-mail authentication
2550 * @return string TS_MW timestamp
2552 public function getEmailAuthenticationTimestamp() {
2554 Hooks
::run( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
2555 return $this->mEmailAuthenticated
;
2559 * Set the user's e-mail address
2560 * @param string $str New e-mail address
2562 public function setEmail( $str ) {
2564 if ( $str == $this->mEmail
) {
2567 $this->invalidateEmail();
2568 $this->mEmail
= $str;
2569 Hooks
::run( 'UserSetEmail', array( $this, &$this->mEmail
) );
2573 * Set the user's e-mail address and a confirmation mail if needed.
2576 * @param string $str New e-mail address
2579 public function setEmailWithConfirmation( $str ) {
2580 global $wgEnableEmail, $wgEmailAuthentication;
2582 if ( !$wgEnableEmail ) {
2583 return Status
::newFatal( 'emaildisabled' );
2586 $oldaddr = $this->getEmail();
2587 if ( $str === $oldaddr ) {
2588 return Status
::newGood( true );
2591 $this->setEmail( $str );
2593 if ( $str !== '' && $wgEmailAuthentication ) {
2594 // Send a confirmation request to the new address if needed
2595 $type = $oldaddr != '' ?
'changed' : 'set';
2596 $result = $this->sendConfirmationMail( $type );
2597 if ( $result->isGood() ) {
2598 // Say to the caller that a confirmation mail has been sent
2599 $result->value
= 'eauth';
2602 $result = Status
::newGood( true );
2609 * Get the user's real name
2610 * @return string User's real name
2612 public function getRealName() {
2613 if ( !$this->isItemLoaded( 'realname' ) ) {
2617 return $this->mRealName
;
2621 * Set the user's real name
2622 * @param string $str New real name
2624 public function setRealName( $str ) {
2626 $this->mRealName
= $str;
2630 * Get the user's current setting for a given option.
2632 * @param string $oname The option to check
2633 * @param string $defaultOverride A default value returned if the option does not exist
2634 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2635 * @return string User's current value for the option
2636 * @see getBoolOption()
2637 * @see getIntOption()
2639 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2640 global $wgHiddenPrefs;
2641 $this->loadOptions();
2643 # We want 'disabled' preferences to always behave as the default value for
2644 # users, even if they have set the option explicitly in their settings (ie they
2645 # set it, and then it was disabled removing their ability to change it). But
2646 # we don't want to erase the preferences in the database in case the preference
2647 # is re-enabled again. So don't touch $mOptions, just override the returned value
2648 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2649 return self
::getDefaultOption( $oname );
2652 if ( array_key_exists( $oname, $this->mOptions
) ) {
2653 return $this->mOptions
[$oname];
2655 return $defaultOverride;
2660 * Get all user's options
2662 * @param int $flags Bitwise combination of:
2663 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2664 * to the default value. (Since 1.25)
2667 public function getOptions( $flags = 0 ) {
2668 global $wgHiddenPrefs;
2669 $this->loadOptions();
2670 $options = $this->mOptions
;
2672 # We want 'disabled' preferences to always behave as the default value for
2673 # users, even if they have set the option explicitly in their settings (ie they
2674 # set it, and then it was disabled removing their ability to change it). But
2675 # we don't want to erase the preferences in the database in case the preference
2676 # is re-enabled again. So don't touch $mOptions, just override the returned value
2677 foreach ( $wgHiddenPrefs as $pref ) {
2678 $default = self
::getDefaultOption( $pref );
2679 if ( $default !== null ) {
2680 $options[$pref] = $default;
2684 if ( $flags & self
::GETOPTIONS_EXCLUDE_DEFAULTS
) {
2685 $options = array_diff_assoc( $options, self
::getDefaultOptions() );
2692 * Get the user's current setting for a given option, as a boolean value.
2694 * @param string $oname The option to check
2695 * @return bool User's current value for the option
2698 public function getBoolOption( $oname ) {
2699 return (bool)$this->getOption( $oname );
2703 * Get the user's current setting for a given option, as an integer value.
2705 * @param string $oname The option to check
2706 * @param int $defaultOverride A default value returned if the option does not exist
2707 * @return int User's current value for the option
2710 public function getIntOption( $oname, $defaultOverride = 0 ) {
2711 $val = $this->getOption( $oname );
2713 $val = $defaultOverride;
2715 return intval( $val );
2719 * Set the given option for a user.
2721 * You need to call saveSettings() to actually write to the database.
2723 * @param string $oname The option to set
2724 * @param mixed $val New value to set
2726 public function setOption( $oname, $val ) {
2727 $this->loadOptions();
2729 // Explicitly NULL values should refer to defaults
2730 if ( is_null( $val ) ) {
2731 $val = self
::getDefaultOption( $oname );
2734 $this->mOptions
[$oname] = $val;
2738 * Get a token stored in the preferences (like the watchlist one),
2739 * resetting it if it's empty (and saving changes).
2741 * @param string $oname The option name to retrieve the token from
2742 * @return string|bool User's current value for the option, or false if this option is disabled.
2743 * @see resetTokenFromOption()
2745 * @deprecated 1.26 Applications should use the OAuth extension
2747 public function getTokenFromOption( $oname ) {
2748 global $wgHiddenPrefs;
2750 $id = $this->getId();
2751 if ( !$id ||
in_array( $oname, $wgHiddenPrefs ) ) {
2755 $token = $this->getOption( $oname );
2757 // Default to a value based on the user token to avoid space
2758 // wasted on storing tokens for all users. When this option
2759 // is set manually by the user, only then is it stored.
2760 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
2767 * Reset a token stored in the preferences (like the watchlist one).
2768 * *Does not* save user's preferences (similarly to setOption()).
2770 * @param string $oname The option name to reset the token in
2771 * @return string|bool New token value, or false if this option is disabled.
2772 * @see getTokenFromOption()
2775 public function resetTokenFromOption( $oname ) {
2776 global $wgHiddenPrefs;
2777 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2781 $token = MWCryptRand
::generateHex( 40 );
2782 $this->setOption( $oname, $token );
2787 * Return a list of the types of user options currently returned by
2788 * User::getOptionKinds().
2790 * Currently, the option kinds are:
2791 * - 'registered' - preferences which are registered in core MediaWiki or
2792 * by extensions using the UserGetDefaultOptions hook.
2793 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2794 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2795 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2796 * be used by user scripts.
2797 * - 'special' - "preferences" that are not accessible via User::getOptions
2798 * or User::setOptions.
2799 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2800 * These are usually legacy options, removed in newer versions.
2802 * The API (and possibly others) use this function to determine the possible
2803 * option types for validation purposes, so make sure to update this when a
2804 * new option kind is added.
2806 * @see User::getOptionKinds
2807 * @return array Option kinds
2809 public static function listOptionKinds() {
2812 'registered-multiselect',
2813 'registered-checkmatrix',
2821 * Return an associative array mapping preferences keys to the kind of a preference they're
2822 * used for. Different kinds are handled differently when setting or reading preferences.
2824 * See User::listOptionKinds for the list of valid option types that can be provided.
2826 * @see User::listOptionKinds
2827 * @param IContextSource $context
2828 * @param array $options Assoc. array with options keys to check as keys.
2829 * Defaults to $this->mOptions.
2830 * @return array The key => kind mapping data
2832 public function getOptionKinds( IContextSource
$context, $options = null ) {
2833 $this->loadOptions();
2834 if ( $options === null ) {
2835 $options = $this->mOptions
;
2838 $prefs = Preferences
::getPreferences( $this, $context );
2841 // Pull out the "special" options, so they don't get converted as
2842 // multiselect or checkmatrix.
2843 $specialOptions = array_fill_keys( Preferences
::getSaveBlacklist(), true );
2844 foreach ( $specialOptions as $name => $value ) {
2845 unset( $prefs[$name] );
2848 // Multiselect and checkmatrix options are stored in the database with
2849 // one key per option, each having a boolean value. Extract those keys.
2850 $multiselectOptions = array();
2851 foreach ( $prefs as $name => $info ) {
2852 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2853 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2854 $opts = HTMLFormField
::flattenOptions( $info['options'] );
2855 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2857 foreach ( $opts as $value ) {
2858 $multiselectOptions["$prefix$value"] = true;
2861 unset( $prefs[$name] );
2864 $checkmatrixOptions = array();
2865 foreach ( $prefs as $name => $info ) {
2866 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2867 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2868 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
2869 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
2870 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2872 foreach ( $columns as $column ) {
2873 foreach ( $rows as $row ) {
2874 $checkmatrixOptions["$prefix$column-$row"] = true;
2878 unset( $prefs[$name] );
2882 // $value is ignored
2883 foreach ( $options as $key => $value ) {
2884 if ( isset( $prefs[$key] ) ) {
2885 $mapping[$key] = 'registered';
2886 } elseif ( isset( $multiselectOptions[$key] ) ) {
2887 $mapping[$key] = 'registered-multiselect';
2888 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2889 $mapping[$key] = 'registered-checkmatrix';
2890 } elseif ( isset( $specialOptions[$key] ) ) {
2891 $mapping[$key] = 'special';
2892 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2893 $mapping[$key] = 'userjs';
2895 $mapping[$key] = 'unused';
2903 * Reset certain (or all) options to the site defaults
2905 * The optional parameter determines which kinds of preferences will be reset.
2906 * Supported values are everything that can be reported by getOptionKinds()
2907 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2909 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
2910 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2911 * for backwards-compatibility.
2912 * @param IContextSource|null $context Context source used when $resetKinds
2913 * does not contain 'all', passed to getOptionKinds().
2914 * Defaults to RequestContext::getMain() when null.
2916 public function resetOptions(
2917 $resetKinds = array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ),
2918 IContextSource
$context = null
2921 $defaultOptions = self
::getDefaultOptions();
2923 if ( !is_array( $resetKinds ) ) {
2924 $resetKinds = array( $resetKinds );
2927 if ( in_array( 'all', $resetKinds ) ) {
2928 $newOptions = $defaultOptions;
2930 if ( $context === null ) {
2931 $context = RequestContext
::getMain();
2934 $optionKinds = $this->getOptionKinds( $context );
2935 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
2936 $newOptions = array();
2938 // Use default values for the options that should be deleted, and
2939 // copy old values for the ones that shouldn't.
2940 foreach ( $this->mOptions
as $key => $value ) {
2941 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
2942 if ( array_key_exists( $key, $defaultOptions ) ) {
2943 $newOptions[$key] = $defaultOptions[$key];
2946 $newOptions[$key] = $value;
2951 Hooks
::run( 'UserResetAllOptions', array( $this, &$newOptions, $this->mOptions
, $resetKinds ) );
2953 $this->mOptions
= $newOptions;
2954 $this->mOptionsLoaded
= true;
2958 * Get the user's preferred date format.
2959 * @return string User's preferred date format
2961 public function getDatePreference() {
2962 // Important migration for old data rows
2963 if ( is_null( $this->mDatePreference
) ) {
2965 $value = $this->getOption( 'date' );
2966 $map = $wgLang->getDatePreferenceMigrationMap();
2967 if ( isset( $map[$value] ) ) {
2968 $value = $map[$value];
2970 $this->mDatePreference
= $value;
2972 return $this->mDatePreference
;
2976 * Determine based on the wiki configuration and the user's options,
2977 * whether this user must be over HTTPS no matter what.
2981 public function requiresHTTPS() {
2982 global $wgSecureLogin;
2983 if ( !$wgSecureLogin ) {
2986 $https = $this->getBoolOption( 'prefershttps' );
2987 Hooks
::run( 'UserRequiresHTTPS', array( $this, &$https ) );
2989 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
2996 * Get the user preferred stub threshold
3000 public function getStubThreshold() {
3001 global $wgMaxArticleSize; # Maximum article size, in Kb
3002 $threshold = $this->getIntOption( 'stubthreshold' );
3003 if ( $threshold > $wgMaxArticleSize * 1024 ) {
3004 // If they have set an impossible value, disable the preference
3005 // so we can use the parser cache again.
3012 * Get the permissions this user has.
3013 * @return array Array of String permission names
3015 public function getRights() {
3016 if ( is_null( $this->mRights
) ) {
3017 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
3019 $allowedRights = $this->getRequest()->getSession()->getAllowedUserRights();
3020 if ( $allowedRights !== null ) {
3021 $this->mRights
= array_intersect( $this->mRights
, $allowedRights );
3024 Hooks
::run( 'UserGetRights', array( $this, &$this->mRights
) );
3025 // Force reindexation of rights when a hook has unset one of them
3026 $this->mRights
= array_values( array_unique( $this->mRights
) );
3028 return $this->mRights
;
3032 * Get the list of explicit group memberships this user has.
3033 * The implicit * and user groups are not included.
3034 * @return array Array of String internal group names
3036 public function getGroups() {
3038 $this->loadGroups();
3039 return $this->mGroups
;
3043 * Get the list of implicit group memberships this user has.
3044 * This includes all explicit groups, plus 'user' if logged in,
3045 * '*' for all accounts, and autopromoted groups
3046 * @param bool $recache Whether to avoid the cache
3047 * @return array Array of String internal group names
3049 public function getEffectiveGroups( $recache = false ) {
3050 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
3051 $this->mEffectiveGroups
= array_unique( array_merge(
3052 $this->getGroups(), // explicit groups
3053 $this->getAutomaticGroups( $recache ) // implicit groups
3055 // Hook for additional groups
3056 Hooks
::run( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
3057 // Force reindexation of groups when a hook has unset one of them
3058 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
3060 return $this->mEffectiveGroups
;
3064 * Get the list of implicit group memberships this user has.
3065 * This includes 'user' if logged in, '*' for all accounts,
3066 * and autopromoted groups
3067 * @param bool $recache Whether to avoid the cache
3068 * @return array Array of String internal group names
3070 public function getAutomaticGroups( $recache = false ) {
3071 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
3072 $this->mImplicitGroups
= array( '*' );
3073 if ( $this->getId() ) {
3074 $this->mImplicitGroups
[] = 'user';
3076 $this->mImplicitGroups
= array_unique( array_merge(
3077 $this->mImplicitGroups
,
3078 Autopromote
::getAutopromoteGroups( $this )
3082 // Assure data consistency with rights/groups,
3083 // as getEffectiveGroups() depends on this function
3084 $this->mEffectiveGroups
= null;
3087 return $this->mImplicitGroups
;
3091 * Returns the groups the user has belonged to.
3093 * The user may still belong to the returned groups. Compare with getGroups().
3095 * The function will not return groups the user had belonged to before MW 1.17
3097 * @return array Names of the groups the user has belonged to.
3099 public function getFormerGroups() {
3102 if ( is_null( $this->mFormerGroups
) ) {
3103 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3104 ?
wfGetDB( DB_MASTER
)
3105 : wfGetDB( DB_SLAVE
);
3106 $res = $db->select( 'user_former_groups',
3107 array( 'ufg_group' ),
3108 array( 'ufg_user' => $this->mId
),
3110 $this->mFormerGroups
= array();
3111 foreach ( $res as $row ) {
3112 $this->mFormerGroups
[] = $row->ufg_group
;
3116 return $this->mFormerGroups
;
3120 * Get the user's edit count.
3121 * @return int|null Null for anonymous users
3123 public function getEditCount() {
3124 if ( !$this->getId() ) {
3128 if ( $this->mEditCount
=== null ) {
3129 /* Populate the count, if it has not been populated yet */
3130 $dbr = wfGetDB( DB_SLAVE
);
3131 // check if the user_editcount field has been initialized
3132 $count = $dbr->selectField(
3133 'user', 'user_editcount',
3134 array( 'user_id' => $this->mId
),
3138 if ( $count === null ) {
3139 // it has not been initialized. do so.
3140 $count = $this->initEditCount();
3142 $this->mEditCount
= $count;
3144 return (int)$this->mEditCount
;
3148 * Add the user to the given group.
3149 * This takes immediate effect.
3150 * @param string $group Name of the group to add
3153 public function addGroup( $group ) {
3156 if ( !Hooks
::run( 'UserAddGroup', array( $this, &$group ) ) ) {
3160 $dbw = wfGetDB( DB_MASTER
);
3161 if ( $this->getId() ) {
3162 $dbw->insert( 'user_groups',
3164 'ug_user' => $this->getID(),
3165 'ug_group' => $group,
3168 array( 'IGNORE' ) );
3171 $this->loadGroups();
3172 $this->mGroups
[] = $group;
3173 // In case loadGroups was not called before, we now have the right twice.
3174 // Get rid of the duplicate.
3175 $this->mGroups
= array_unique( $this->mGroups
);
3177 // Refresh the groups caches, and clear the rights cache so it will be
3178 // refreshed on the next call to $this->getRights().
3179 $this->getEffectiveGroups( true );
3180 $this->mRights
= null;
3182 $this->invalidateCache();
3188 * Remove the user from the given group.
3189 * This takes immediate effect.
3190 * @param string $group Name of the group to remove
3193 public function removeGroup( $group ) {
3195 if ( !Hooks
::run( 'UserRemoveGroup', array( $this, &$group ) ) ) {
3199 $dbw = wfGetDB( DB_MASTER
);
3200 $dbw->delete( 'user_groups',
3202 'ug_user' => $this->getID(),
3203 'ug_group' => $group,
3206 // Remember that the user was in this group
3207 $dbw->insert( 'user_former_groups',
3209 'ufg_user' => $this->getID(),
3210 'ufg_group' => $group,
3216 $this->loadGroups();
3217 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
3219 // Refresh the groups caches, and clear the rights cache so it will be
3220 // refreshed on the next call to $this->getRights().
3221 $this->getEffectiveGroups( true );
3222 $this->mRights
= null;
3224 $this->invalidateCache();
3230 * Get whether the user is logged in
3233 public function isLoggedIn() {
3234 return $this->getID() != 0;
3238 * Get whether the user is anonymous
3241 public function isAnon() {
3242 return !$this->isLoggedIn();
3246 * Check if user is allowed to access a feature / make an action
3248 * @param string ... Permissions to test
3249 * @return bool True if user is allowed to perform *any* of the given actions
3251 public function isAllowedAny() {
3252 $permissions = func_get_args();
3253 foreach ( $permissions as $permission ) {
3254 if ( $this->isAllowed( $permission ) ) {
3263 * @param string ... Permissions to test
3264 * @return bool True if the user is allowed to perform *all* of the given actions
3266 public function isAllowedAll() {
3267 $permissions = func_get_args();
3268 foreach ( $permissions as $permission ) {
3269 if ( !$this->isAllowed( $permission ) ) {
3277 * Internal mechanics of testing a permission
3278 * @param string $action
3281 public function isAllowed( $action = '' ) {
3282 if ( $action === '' ) {
3283 return true; // In the spirit of DWIM
3285 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3286 // by misconfiguration: 0 == 'foo'
3287 return in_array( $action, $this->getRights(), true );
3291 * Check whether to enable recent changes patrol features for this user
3292 * @return bool True or false
3294 public function useRCPatrol() {
3295 global $wgUseRCPatrol;
3296 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3300 * Check whether to enable new pages patrol features for this user
3301 * @return bool True or false
3303 public function useNPPatrol() {
3304 global $wgUseRCPatrol, $wgUseNPPatrol;
3306 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3307 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3312 * Check whether to enable new files patrol features for this user
3313 * @return bool True or false
3315 public function useFilePatrol() {
3316 global $wgUseRCPatrol, $wgUseFilePatrol;
3318 ( $wgUseRCPatrol ||
$wgUseFilePatrol )
3319 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3324 * Get the WebRequest object to use with this object
3326 * @return WebRequest
3328 public function getRequest() {
3329 if ( $this->mRequest
) {
3330 return $this->mRequest
;
3338 * Get a WatchedItem for this user and $title.
3340 * @since 1.22 $checkRights parameter added
3341 * @param Title $title
3342 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3343 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3344 * @return WatchedItem
3346 public function getWatchedItem( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3347 $key = $checkRights . ':' . $title->getNamespace() . ':' . $title->getDBkey();
3349 if ( isset( $this->mWatchedItems
[$key] ) ) {
3350 return $this->mWatchedItems
[$key];
3353 if ( count( $this->mWatchedItems
) >= self
::MAX_WATCHED_ITEMS_CACHE
) {
3354 $this->mWatchedItems
= array();
3357 $this->mWatchedItems
[$key] = WatchedItem
::fromUserTitle( $this, $title, $checkRights );
3358 return $this->mWatchedItems
[$key];
3362 * Check the watched status of an article.
3363 * @since 1.22 $checkRights parameter added
3364 * @param Title $title Title of the article to look at
3365 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3366 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3369 public function isWatched( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3370 return $this->getWatchedItem( $title, $checkRights )->isWatched();
3375 * @since 1.22 $checkRights parameter added
3376 * @param Title $title Title of the article to look at
3377 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3378 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3380 public function addWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3381 $this->getWatchedItem( $title, $checkRights )->addWatch();
3382 $this->invalidateCache();
3386 * Stop watching an article.
3387 * @since 1.22 $checkRights parameter added
3388 * @param Title $title Title of the article to look at
3389 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3390 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3392 public function removeWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3393 $this->getWatchedItem( $title, $checkRights )->removeWatch();
3394 $this->invalidateCache();
3398 * Clear the user's notification timestamp for the given title.
3399 * If e-notif e-mails are on, they will receive notification mails on
3400 * the next change of the page if it's watched etc.
3401 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3402 * @param Title $title Title of the article to look at
3403 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3405 public function clearNotification( &$title, $oldid = 0 ) {
3406 global $wgUseEnotif, $wgShowUpdatedMarker;
3408 // Do nothing if the database is locked to writes
3409 if ( wfReadOnly() ) {
3413 // Do nothing if not allowed to edit the watchlist
3414 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3418 // If we're working on user's talk page, we should update the talk page message indicator
3419 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3420 if ( !Hooks
::run( 'UserClearNewTalkNotification', array( &$this, $oldid ) ) ) {
3425 // Try to update the DB post-send and only if needed...
3426 DeferredUpdates
::addCallableUpdate( function() use ( $that, $title, $oldid ) {
3427 if ( !$that->getNewtalk() ) {
3428 return; // no notifications to clear
3431 // Delete the last notifications (they stack up)
3432 $that->setNewtalk( false );
3434 // If there is a new, unseen, revision, use its timestamp
3436 ?
$title->getNextRevisionID( $oldid, Title
::GAID_FOR_UPDATE
)
3439 $that->setNewtalk( true, Revision
::newFromId( $nextid ) );
3444 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3448 if ( $this->isAnon() ) {
3449 // Nothing else to do...
3453 // Only update the timestamp if the page is being watched.
3454 // The query to find out if it is watched is cached both in memcached and per-invocation,
3455 // and when it does have to be executed, it can be on a slave
3456 // If this is the user's newtalk page, we always update the timestamp
3458 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3462 $this->getWatchedItem( $title )->resetNotificationTimestamp(
3468 * Resets all of the given user's page-change notification timestamps.
3469 * If e-notif e-mails are on, they will receive notification mails on
3470 * the next change of any watched page.
3471 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3473 public function clearAllNotifications() {
3474 if ( wfReadOnly() ) {
3478 // Do nothing if not allowed to edit the watchlist
3479 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3483 global $wgUseEnotif, $wgShowUpdatedMarker;
3484 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3485 $this->setNewtalk( false );
3488 $id = $this->getId();
3490 $dbw = wfGetDB( DB_MASTER
);
3491 $dbw->update( 'watchlist',
3492 array( /* SET */ 'wl_notificationtimestamp' => null ),
3493 array( /* WHERE */ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ),
3496 // We also need to clear here the "you have new message" notification for the own user_talk page;
3497 // it's cleared one page view later in WikiPage::doViewUpdates().
3502 * Set a cookie on the user's client. Wrapper for
3503 * WebResponse::setCookie
3504 * @deprecated since 1.27
3505 * @param string $name Name of the cookie to set
3506 * @param string $value Value to set
3507 * @param int $exp Expiration time, as a UNIX time value;
3508 * if 0 or not specified, use the default $wgCookieExpiration
3509 * @param bool $secure
3510 * true: Force setting the secure attribute when setting the cookie
3511 * false: Force NOT setting the secure attribute when setting the cookie
3512 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3513 * @param array $params Array of options sent passed to WebResponse::setcookie()
3514 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3517 protected function setCookie(
3518 $name, $value, $exp = 0, $secure = null, $params = array(), $request = null
3520 wfDeprecated( __METHOD__
, '1.27' );
3521 if ( $request === null ) {
3522 $request = $this->getRequest();
3524 $params['secure'] = $secure;
3525 $request->response()->setCookie( $name, $value, $exp, $params );
3529 * Clear a cookie on the user's client
3530 * @deprecated since 1.27
3531 * @param string $name Name of the cookie to clear
3532 * @param bool $secure
3533 * true: Force setting the secure attribute when setting the cookie
3534 * false: Force NOT setting the secure attribute when setting the cookie
3535 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3536 * @param array $params Array of options sent passed to WebResponse::setcookie()
3538 protected function clearCookie( $name, $secure = null, $params = array() ) {
3539 wfDeprecated( __METHOD__
, '1.27' );
3540 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3544 * Set an extended login cookie on the user's client. The expiry of the cookie
3545 * is controlled by the $wgExtendedLoginCookieExpiration configuration
3548 * @see User::setCookie
3550 * @deprecated since 1.27
3551 * @param string $name Name of the cookie to set
3552 * @param string $value Value to set
3553 * @param bool $secure
3554 * true: Force setting the secure attribute when setting the cookie
3555 * false: Force NOT setting the secure attribute when setting the cookie
3556 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3558 protected function setExtendedLoginCookie( $name, $value, $secure ) {
3559 global $wgExtendedLoginCookieExpiration, $wgCookieExpiration;
3561 wfDeprecated( __METHOD__
, '1.27' );
3564 $exp +
= $wgExtendedLoginCookieExpiration !== null
3565 ?
$wgExtendedLoginCookieExpiration
3566 : $wgCookieExpiration;
3568 $this->setCookie( $name, $value, $exp, $secure );
3572 * Persist this user's session (e.g. set cookies)
3574 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3576 * @param bool $secure Whether to force secure/insecure cookies or use default
3577 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3579 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3581 if ( 0 == $this->mId
) {
3585 $session = $this->getRequest()->getSession();
3586 if ( $request && $session->getRequest() !== $request ) {
3587 $session = $session->sessionWithRequest( $request );
3589 $delay = $session->delaySave();
3591 if ( !$session->getUser()->equals( $this ) ) {
3592 if ( !$session->canSetUser() ) {
3593 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3594 ->warning( __METHOD__
.
3595 ": Cannot save user \"$this\" to a user \"{$session->getUser()}\"'s immutable session"
3599 $session->setUser( $this );
3602 $session->setRememberUser( $rememberMe );
3603 if ( $secure !== null ) {
3604 $session->setForceHTTPS( $secure );
3607 $session->persist();
3609 ScopedCallback
::consume( $delay );
3613 * Log this user out.
3615 public function logout() {
3616 if ( Hooks
::run( 'UserLogout', array( &$this ) ) ) {
3622 * Clear the user's session, and reset the instance cache.
3625 public function doLogout() {
3626 $session = $this->getRequest()->getSession();
3627 if ( !$session->canSetUser() ) {
3628 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3629 ->warning( __METHOD__
. ": Cannot log out of an immutable session" );
3630 } elseif ( !$session->getUser()->equals( $this ) ) {
3631 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3632 ->warning( __METHOD__
.
3633 ": Cannot log user \"$this\" out of a user \"{$session->getUser()}\"'s session"
3635 // But we still may as well make this user object anon
3636 $this->clearInstanceCache( 'defaults' );
3638 $this->clearInstanceCache( 'defaults' );
3639 $delay = $session->delaySave();
3640 $session->setLoggedOutTimestamp( time() );
3641 $session->setUser( new User
);
3642 $session->set( 'wsUserID', 0 ); // Other code expects this
3643 ScopedCallback
::consume( $delay );
3648 * Save this user's settings into the database.
3649 * @todo Only rarely do all these fields need to be set!
3651 public function saveSettings() {
3652 if ( wfReadOnly() ) {
3653 // @TODO: caller should deal with this instead!
3654 // This should really just be an exception.
3655 MWExceptionHandler
::logException( new DBExpectedError(
3657 "Could not update user with ID '{$this->mId}'; DB is read-only."
3663 if ( 0 == $this->mId
) {
3667 // Get a new user_touched that is higher than the old one.
3668 // This will be used for a CAS check as a last-resort safety
3669 // check against race conditions and slave lag.
3670 $oldTouched = $this->mTouched
;
3671 $newTouched = $this->newTouchedTimestamp();
3673 $dbw = wfGetDB( DB_MASTER
);
3674 $dbw->update( 'user',
3676 'user_name' => $this->mName
,
3677 'user_real_name' => $this->mRealName
,
3678 'user_email' => $this->mEmail
,
3679 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3680 'user_touched' => $dbw->timestamp( $newTouched ),
3681 'user_token' => strval( $this->mToken
),
3682 'user_email_token' => $this->mEmailToken
,
3683 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
3684 ), array( /* WHERE */
3685 'user_id' => $this->mId
,
3686 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
3690 if ( !$dbw->affectedRows() ) {
3691 // Maybe the problem was a missed cache update; clear it to be safe
3692 $this->clearSharedCache( 'refresh' );
3693 // User was changed in the meantime or loaded with stale data
3694 $from = ( $this->queryFlagsUsed
& self
::READ_LATEST
) ?
'master' : 'slave';
3695 throw new MWException(
3696 "CAS update failed on user_touched for user ID '{$this->mId}' (read from $from);" .
3697 " the version of the user to be saved is older than the current version."
3701 $this->mTouched
= $newTouched;
3702 $this->saveOptions();
3704 Hooks
::run( 'UserSaveSettings', array( $this ) );
3705 $this->clearSharedCache();
3706 $this->getUserPage()->invalidateCache();
3710 * If only this user's username is known, and it exists, return the user ID.
3712 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
3715 public function idForName( $flags = 0 ) {
3716 $s = trim( $this->getName() );
3721 $db = ( ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
)
3722 ?
wfGetDB( DB_MASTER
)
3723 : wfGetDB( DB_SLAVE
);
3725 $options = ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
)
3726 ?
array( 'LOCK IN SHARE MODE' )
3729 $id = $db->selectField( 'user',
3730 'user_id', array( 'user_name' => $s ), __METHOD__
, $options );
3736 * Add a user to the database, return the user object
3738 * @param string $name Username to add
3739 * @param array $params Array of Strings Non-default parameters to save to
3740 * the database as user_* fields:
3741 * - email: The user's email address.
3742 * - email_authenticated: The email authentication timestamp.
3743 * - real_name: The user's real name.
3744 * - options: An associative array of non-default options.
3745 * - token: Random authentication token. Do not set.
3746 * - registration: Registration timestamp. Do not set.
3748 * @return User|null User object, or null if the username already exists.
3750 public static function createNew( $name, $params = array() ) {
3751 foreach ( array( 'password', 'newpassword', 'newpass_time', 'password_expires' ) as $field ) {
3752 if ( isset( $params[$field] ) ) {
3753 wfDeprecated( __METHOD__
. " with param '$field'", '1.27' );
3754 unset( $params[$field] );
3760 $user->setToken(); // init token
3761 if ( isset( $params['options'] ) ) {
3762 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
3763 unset( $params['options'] );
3765 $dbw = wfGetDB( DB_MASTER
);
3766 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3768 $noPass = PasswordFactory
::newInvalidPassword()->toString();
3771 'user_id' => $seqVal,
3772 'user_name' => $name,
3773 'user_password' => $noPass,
3774 'user_newpassword' => $noPass,
3775 'user_email' => $user->mEmail
,
3776 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
3777 'user_real_name' => $user->mRealName
,
3778 'user_token' => strval( $user->mToken
),
3779 'user_registration' => $dbw->timestamp( $user->mRegistration
),
3780 'user_editcount' => 0,
3781 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
3783 foreach ( $params as $name => $value ) {
3784 $fields["user_$name"] = $value;
3786 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
3787 if ( $dbw->affectedRows() ) {
3788 $newUser = User
::newFromId( $dbw->insertId() );
3796 * Add this existing user object to the database. If the user already
3797 * exists, a fatal status object is returned, and the user object is
3798 * initialised with the data from the database.
3800 * Previously, this function generated a DB error due to a key conflict
3801 * if the user already existed. Many extension callers use this function
3802 * in code along the lines of:
3804 * $user = User::newFromName( $name );
3805 * if ( !$user->isLoggedIn() ) {
3806 * $user->addToDatabase();
3808 * // do something with $user...
3810 * However, this was vulnerable to a race condition (bug 16020). By
3811 * initialising the user object if the user exists, we aim to support this
3812 * calling sequence as far as possible.
3814 * Note that if the user exists, this function will acquire a write lock,
3815 * so it is still advisable to make the call conditional on isLoggedIn(),
3816 * and to commit the transaction after calling.
3818 * @throws MWException
3821 public function addToDatabase() {
3823 if ( !$this->mToken
) {
3824 $this->setToken(); // init token
3827 $this->mTouched
= $this->newTouchedTimestamp();
3829 $noPass = PasswordFactory
::newInvalidPassword()->toString();
3831 $dbw = wfGetDB( DB_MASTER
);
3832 $inWrite = $dbw->writesOrCallbacksPending();
3833 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3834 $dbw->insert( 'user',
3836 'user_id' => $seqVal,
3837 'user_name' => $this->mName
,
3838 'user_password' => $noPass,
3839 'user_newpassword' => $noPass,
3840 'user_email' => $this->mEmail
,
3841 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3842 'user_real_name' => $this->mRealName
,
3843 'user_token' => strval( $this->mToken
),
3844 'user_registration' => $dbw->timestamp( $this->mRegistration
),
3845 'user_editcount' => 0,
3846 'user_touched' => $dbw->timestamp( $this->mTouched
),
3850 if ( !$dbw->affectedRows() ) {
3851 // The queries below cannot happen in the same REPEATABLE-READ snapshot.
3852 // Handle this by COMMIT, if possible, or by LOCK IN SHARE MODE otherwise.
3854 // Can't commit due to pending writes that may need atomicity.
3855 // This may cause some lock contention unlike the case below.
3856 $options = array( 'LOCK IN SHARE MODE' );
3857 $flags = self
::READ_LOCKING
;
3859 // Often, this case happens early in views before any writes when
3860 // using CentralAuth. It's should be OK to commit and break the snapshot.
3861 $dbw->commit( __METHOD__
, 'flush' );
3863 $flags = self
::READ_LATEST
;
3865 $this->mId
= $dbw->selectField( 'user', 'user_id',
3866 array( 'user_name' => $this->mName
), __METHOD__
, $options );
3869 if ( $this->loadFromDatabase( $flags ) ) {
3874 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
3875 "to insert user '{$this->mName}' row, but it was not present in select!" );
3877 return Status
::newFatal( 'userexists' );
3879 $this->mId
= $dbw->insertId();
3880 self
::$idCacheByName[$this->mName
] = $this->mId
;
3882 // Clear instance cache other than user table data, which is already accurate
3883 $this->clearInstanceCache();
3885 $this->saveOptions();
3886 return Status
::newGood();
3890 * If this user is logged-in and blocked,
3891 * block any IP address they've successfully logged in from.
3892 * @return bool A block was spread
3894 public function spreadAnyEditBlock() {
3895 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3896 return $this->spreadBlock();
3902 * If this (non-anonymous) user is blocked,
3903 * block the IP address they've successfully logged in from.
3904 * @return bool A block was spread
3906 protected function spreadBlock() {
3907 wfDebug( __METHOD__
. "()\n" );
3909 if ( $this->mId
== 0 ) {
3913 $userblock = Block
::newFromTarget( $this->getName() );
3914 if ( !$userblock ) {
3918 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3922 * Get whether the user is explicitly blocked from account creation.
3923 * @return bool|Block
3925 public function isBlockedFromCreateAccount() {
3926 $this->getBlockedStatus();
3927 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
3928 return $this->mBlock
;
3931 # bug 13611: if the IP address the user is trying to create an account from is
3932 # blocked with createaccount disabled, prevent new account creation there even
3933 # when the user is logged in
3934 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3935 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
3937 return $this->mBlockedFromCreateAccount
instanceof Block
3938 && $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
3939 ?
$this->mBlockedFromCreateAccount
3944 * Get whether the user is blocked from using Special:Emailuser.
3947 public function isBlockedFromEmailuser() {
3948 $this->getBlockedStatus();
3949 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
3953 * Get whether the user is allowed to create an account.
3956 public function isAllowedToCreateAccount() {
3957 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
3961 * Get this user's personal page title.
3963 * @return Title User's personal page title
3965 public function getUserPage() {
3966 return Title
::makeTitle( NS_USER
, $this->getName() );
3970 * Get this user's talk page title.
3972 * @return Title User's talk page title
3974 public function getTalkPage() {
3975 $title = $this->getUserPage();
3976 return $title->getTalkPage();
3980 * Determine whether the user is a newbie. Newbies are either
3981 * anonymous IPs, or the most recently created accounts.
3984 public function isNewbie() {
3985 return !$this->isAllowed( 'autoconfirmed' );
3989 * Check to see if the given clear-text password is one of the accepted passwords
3990 * @deprecated since 1.27. AuthManager is coming.
3991 * @param string $password User password
3992 * @return bool True if the given password is correct, otherwise False
3994 public function checkPassword( $password ) {
3995 global $wgAuth, $wgLegacyEncoding;
3999 // Some passwords will give a fatal Status, which means there is
4000 // some sort of technical or security reason for this password to
4001 // be completely invalid and should never be checked (e.g., T64685)
4002 if ( !$this->checkPasswordValidity( $password )->isOK() ) {
4006 // Certain authentication plugins do NOT want to save
4007 // domain passwords in a mysql database, so we should
4008 // check this (in case $wgAuth->strict() is false).
4009 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
4011 } elseif ( $wgAuth->strict() ) {
4012 // Auth plugin doesn't allow local authentication
4014 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
4015 // Auth plugin doesn't allow local authentication for this user name
4019 $passwordFactory = new PasswordFactory();
4020 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4021 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
4022 ?
wfGetDB( DB_MASTER
)
4023 : wfGetDB( DB_SLAVE
);
4026 $mPassword = $passwordFactory->newFromCiphertext( $db->selectField(
4027 'user', 'user_password', array( 'user_id' => $this->getId() ), __METHOD__
4029 } catch ( PasswordError
$e ) {
4030 wfDebug( 'Invalid password hash found in database.' );
4031 $mPassword = PasswordFactory
::newInvalidPassword();
4034 if ( !$mPassword->equals( $password ) ) {
4035 if ( $wgLegacyEncoding ) {
4036 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
4037 // Check for this with iconv
4038 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
4039 if ( $cp1252Password === $password ||
!$mPassword->equals( $cp1252Password ) ) {
4047 if ( $passwordFactory->needsUpdate( $mPassword ) && !wfReadOnly() ) {
4048 $this->setPasswordInternal( $password );
4055 * Check if the given clear-text password matches the temporary password
4056 * sent by e-mail for password reset operations.
4058 * @deprecated since 1.27. AuthManager is coming.
4059 * @param string $plaintext
4060 * @return bool True if matches, false otherwise
4062 public function checkTemporaryPassword( $plaintext ) {
4063 global $wgNewPasswordExpiry;
4067 $passwordFactory = new PasswordFactory();
4068 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4069 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
4070 ?
wfGetDB( DB_MASTER
)
4071 : wfGetDB( DB_SLAVE
);
4073 $row = $db->selectRow(
4075 array( 'user_newpassword', 'user_newpass_time' ),
4076 array( 'user_id' => $this->getId() ),
4080 $newPassword = $passwordFactory->newFromCiphertext( $row->user_newpassword
);
4081 } catch ( PasswordError
$e ) {
4082 wfDebug( 'Invalid password hash found in database.' );
4083 $newPassword = PasswordFactory
::newInvalidPassword();
4086 if ( $newPassword->equals( $plaintext ) ) {
4087 if ( is_null( $row->user_newpass_time
) ) {
4090 $expiry = wfTimestamp( TS_UNIX
, $row->user_newpass_time
) +
$wgNewPasswordExpiry;
4091 return ( time() < $expiry );
4098 * Initialize (if necessary) and return a session token value
4099 * which can be used in edit forms to show that the user's
4100 * login credentials aren't being hijacked with a foreign form
4104 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4105 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4106 * @return MediaWiki\\Session\\Token The new edit token
4108 public function getEditTokenObject( $salt = '', $request = null ) {
4109 if ( $this->isAnon() ) {
4110 return new LoggedOutEditToken();
4114 $request = $this->getRequest();
4116 return $request->getSession()->getToken( $salt );
4120 * Initialize (if necessary) and return a session token value
4121 * which can be used in edit forms to show that the user's
4122 * login credentials aren't being hijacked with a foreign form
4126 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4127 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4128 * @return string The new edit token
4130 public function getEditToken( $salt = '', $request = null ) {
4131 return $this->getEditTokenObject( $salt, $request )->toString();
4135 * Get the embedded timestamp from a token.
4136 * @deprecated since 1.27, use \\MediaWiki\\Session\\Token::getTimestamp instead.
4137 * @param string $val Input token
4140 public static function getEditTokenTimestamp( $val ) {
4141 wfDeprecated( __METHOD__
, '1.27' );
4142 return MediaWiki\Session\Token
::getTimestamp( $val );
4146 * Check given value against the token value stored in the session.
4147 * A match should confirm that the form was submitted from the
4148 * user's own login session, not a form submission from a third-party
4151 * @param string $val Input value to compare
4152 * @param string $salt Optional function-specific data for hashing
4153 * @param WebRequest|null $request Object to use or null to use $wgRequest
4154 * @param int $maxage Fail tokens older than this, in seconds
4155 * @return bool Whether the token matches
4157 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4158 return $this->getEditTokenObject( $salt, $request )->match( $val, $maxage );
4162 * Check given value against the token value stored in the session,
4163 * ignoring the suffix.
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 matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4172 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . self
::EDIT_TOKEN_SUFFIX
;
4173 return $this->matchEditToken( $val, $salt, $request, $maxage );
4177 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4178 * mail to the user's given address.
4180 * @param string $type Message to send, either "created", "changed" or "set"
4183 public function sendConfirmationMail( $type = 'created' ) {
4185 $expiration = null; // gets passed-by-ref and defined in next line.
4186 $token = $this->confirmationToken( $expiration );
4187 $url = $this->confirmationTokenUrl( $token );
4188 $invalidateURL = $this->invalidationTokenUrl( $token );
4189 $this->saveSettings();
4191 if ( $type == 'created' ||
$type === false ) {
4192 $message = 'confirmemail_body';
4193 } elseif ( $type === true ) {
4194 $message = 'confirmemail_body_changed';
4196 // Messages: confirmemail_body_changed, confirmemail_body_set
4197 $message = 'confirmemail_body_' . $type;
4200 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4201 wfMessage( $message,
4202 $this->getRequest()->getIP(),
4205 $wgLang->userTimeAndDate( $expiration, $this ),
4207 $wgLang->userDate( $expiration, $this ),
4208 $wgLang->userTime( $expiration, $this ) )->text() );
4212 * Send an e-mail to this user's account. Does not check for
4213 * confirmed status or validity.
4215 * @param string $subject Message subject
4216 * @param string $body Message body
4217 * @param User|null $from Optional sending user; if unspecified, default
4218 * $wgPasswordSender will be used.
4219 * @param string $replyto Reply-To address
4222 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4223 global $wgPasswordSender;
4225 if ( $from instanceof User
) {
4226 $sender = MailAddress
::newFromUser( $from );
4228 $sender = new MailAddress( $wgPasswordSender,
4229 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4231 $to = MailAddress
::newFromUser( $this );
4233 return UserMailer
::send( $to, $sender, $subject, $body, array(
4234 'replyTo' => $replyto,
4239 * Generate, store, and return a new e-mail confirmation code.
4240 * A hash (unsalted, since it's used as a key) is stored.
4242 * @note Call saveSettings() after calling this function to commit
4243 * this change to the database.
4245 * @param string &$expiration Accepts the expiration time
4246 * @return string New token
4248 protected function confirmationToken( &$expiration ) {
4249 global $wgUserEmailConfirmationTokenExpiry;
4251 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4252 $expiration = wfTimestamp( TS_MW
, $expires );
4254 $token = MWCryptRand
::generateHex( 32 );
4255 $hash = md5( $token );
4256 $this->mEmailToken
= $hash;
4257 $this->mEmailTokenExpires
= $expiration;
4262 * Return a URL the user can use to confirm their email address.
4263 * @param string $token Accepts the email confirmation token
4264 * @return string New token URL
4266 protected function confirmationTokenUrl( $token ) {
4267 return $this->getTokenUrl( 'ConfirmEmail', $token );
4271 * Return a URL the user can use to invalidate their email address.
4272 * @param string $token Accepts the email confirmation token
4273 * @return string New token URL
4275 protected function invalidationTokenUrl( $token ) {
4276 return $this->getTokenUrl( 'InvalidateEmail', $token );
4280 * Internal function to format the e-mail validation/invalidation URLs.
4281 * This uses a quickie hack to use the
4282 * hardcoded English names of the Special: pages, for ASCII safety.
4284 * @note Since these URLs get dropped directly into emails, using the
4285 * short English names avoids insanely long URL-encoded links, which
4286 * also sometimes can get corrupted in some browsers/mailers
4287 * (bug 6957 with Gmail and Internet Explorer).
4289 * @param string $page Special page
4290 * @param string $token Token
4291 * @return string Formatted URL
4293 protected function getTokenUrl( $page, $token ) {
4294 // Hack to bypass localization of 'Special:'
4295 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4296 return $title->getCanonicalURL();
4300 * Mark the e-mail address confirmed.
4302 * @note Call saveSettings() after calling this function to commit the change.
4306 public function confirmEmail() {
4307 // Check if it's already confirmed, so we don't touch the database
4308 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4309 if ( !$this->isEmailConfirmed() ) {
4310 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4311 Hooks
::run( 'ConfirmEmailComplete', array( $this ) );
4317 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4318 * address if it was already confirmed.
4320 * @note Call saveSettings() after calling this function to commit the change.
4321 * @return bool Returns true
4323 public function invalidateEmail() {
4325 $this->mEmailToken
= null;
4326 $this->mEmailTokenExpires
= null;
4327 $this->setEmailAuthenticationTimestamp( null );
4329 Hooks
::run( 'InvalidateEmailComplete', array( $this ) );
4334 * Set the e-mail authentication timestamp.
4335 * @param string $timestamp TS_MW timestamp
4337 public function setEmailAuthenticationTimestamp( $timestamp ) {
4339 $this->mEmailAuthenticated
= $timestamp;
4340 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
4344 * Is this user allowed to send e-mails within limits of current
4345 * site configuration?
4348 public function canSendEmail() {
4349 global $wgEnableEmail, $wgEnableUserEmail;
4350 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4353 $canSend = $this->isEmailConfirmed();
4354 Hooks
::run( 'UserCanSendEmail', array( &$this, &$canSend ) );
4359 * Is this user allowed to receive e-mails within limits of current
4360 * site configuration?
4363 public function canReceiveEmail() {
4364 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4368 * Is this user's e-mail address valid-looking and confirmed within
4369 * limits of the current site configuration?
4371 * @note If $wgEmailAuthentication is on, this may require the user to have
4372 * confirmed their address by returning a code or using a password
4373 * sent to the address from the wiki.
4377 public function isEmailConfirmed() {
4378 global $wgEmailAuthentication;
4381 if ( Hooks
::run( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
4382 if ( $this->isAnon() ) {
4385 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4388 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4398 * Check whether there is an outstanding request for e-mail confirmation.
4401 public function isEmailConfirmationPending() {
4402 global $wgEmailAuthentication;
4403 return $wgEmailAuthentication &&
4404 !$this->isEmailConfirmed() &&
4405 $this->mEmailToken
&&
4406 $this->mEmailTokenExpires
> wfTimestamp();
4410 * Get the timestamp of account creation.
4412 * @return string|bool|null Timestamp of account creation, false for
4413 * non-existent/anonymous user accounts, or null if existing account
4414 * but information is not in database.
4416 public function getRegistration() {
4417 if ( $this->isAnon() ) {
4421 return $this->mRegistration
;
4425 * Get the timestamp of the first edit
4427 * @return string|bool Timestamp of first edit, or false for
4428 * non-existent/anonymous user accounts.
4430 public function getFirstEditTimestamp() {
4431 if ( $this->getId() == 0 ) {
4432 return false; // anons
4434 $dbr = wfGetDB( DB_SLAVE
);
4435 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4436 array( 'rev_user' => $this->getId() ),
4438 array( 'ORDER BY' => 'rev_timestamp ASC' )
4441 return false; // no edits
4443 return wfTimestamp( TS_MW
, $time );
4447 * Get the permissions associated with a given list of groups
4449 * @param array $groups Array of Strings List of internal group names
4450 * @return array Array of Strings List of permission key names for given groups combined
4452 public static function getGroupPermissions( $groups ) {
4453 global $wgGroupPermissions, $wgRevokePermissions;
4455 // grant every granted permission first
4456 foreach ( $groups as $group ) {
4457 if ( isset( $wgGroupPermissions[$group] ) ) {
4458 $rights = array_merge( $rights,
4459 // array_filter removes empty items
4460 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4463 // now revoke the revoked permissions
4464 foreach ( $groups as $group ) {
4465 if ( isset( $wgRevokePermissions[$group] ) ) {
4466 $rights = array_diff( $rights,
4467 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4470 return array_unique( $rights );
4474 * Get all the groups who have a given permission
4476 * @param string $role Role to check
4477 * @return array Array of Strings List of internal group names with the given permission
4479 public static function getGroupsWithPermission( $role ) {
4480 global $wgGroupPermissions;
4481 $allowedGroups = array();
4482 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4483 if ( self
::groupHasPermission( $group, $role ) ) {
4484 $allowedGroups[] = $group;
4487 return $allowedGroups;
4491 * Check, if the given group has the given permission
4493 * If you're wanting to check whether all users have a permission, use
4494 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4498 * @param string $group Group to check
4499 * @param string $role Role to check
4502 public static function groupHasPermission( $group, $role ) {
4503 global $wgGroupPermissions, $wgRevokePermissions;
4504 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4505 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4509 * Check if all users may be assumed to have the given permission
4511 * We generally assume so if the right is granted to '*' and isn't revoked
4512 * on any group. It doesn't attempt to take grants or other extension
4513 * limitations on rights into account in the general case, though, as that
4514 * would require it to always return false and defeat the purpose.
4515 * Specifically, session-based rights restrictions (such as OAuth or bot
4516 * passwords) are applied based on the current session.
4519 * @param string $right Right to check
4522 public static function isEveryoneAllowed( $right ) {
4523 global $wgGroupPermissions, $wgRevokePermissions;
4524 static $cache = array();
4526 // Use the cached results, except in unit tests which rely on
4527 // being able change the permission mid-request
4528 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4529 return $cache[$right];
4532 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4533 $cache[$right] = false;
4537 // If it's revoked anywhere, then everyone doesn't have it
4538 foreach ( $wgRevokePermissions as $rights ) {
4539 if ( isset( $rights[$right] ) && $rights[$right] ) {
4540 $cache[$right] = false;
4545 // Remove any rights that aren't allowed to the global-session user
4546 $allowedRights = SessionManager
::getGlobalSession()->getAllowedUserRights();
4547 if ( $allowedRights !== null && !in_array( $right, $allowedRights, true ) ) {
4548 $cache[$right] = false;
4552 // Allow extensions to say false
4553 if ( !Hooks
::run( 'UserIsEveryoneAllowed', array( $right ) ) ) {
4554 $cache[$right] = false;
4558 $cache[$right] = true;
4563 * Get the localized descriptive name for a group, if it exists
4565 * @param string $group Internal group name
4566 * @return string Localized descriptive group name
4568 public static function getGroupName( $group ) {
4569 $msg = wfMessage( "group-$group" );
4570 return $msg->isBlank() ?
$group : $msg->text();
4574 * Get the localized descriptive name for a member of a group, if it exists
4576 * @param string $group Internal group name
4577 * @param string $username Username for gender (since 1.19)
4578 * @return string Localized name for group member
4580 public static function getGroupMember( $group, $username = '#' ) {
4581 $msg = wfMessage( "group-$group-member", $username );
4582 return $msg->isBlank() ?
$group : $msg->text();
4586 * Return the set of defined explicit groups.
4587 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4588 * are not included, as they are defined automatically, not in the database.
4589 * @return array Array of internal group names
4591 public static function getAllGroups() {
4592 global $wgGroupPermissions, $wgRevokePermissions;
4594 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4595 self
::getImplicitGroups()
4600 * Get a list of all available permissions.
4601 * @return string[] Array of permission names
4603 public static function getAllRights() {
4604 if ( self
::$mAllRights === false ) {
4605 global $wgAvailableRights;
4606 if ( count( $wgAvailableRights ) ) {
4607 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
4609 self
::$mAllRights = self
::$mCoreRights;
4611 Hooks
::run( 'UserGetAllRights', array( &self
::$mAllRights ) );
4613 return self
::$mAllRights;
4617 * Get a list of implicit groups
4618 * @return array Array of Strings Array of internal group names
4620 public static function getImplicitGroups() {
4621 global $wgImplicitGroups;
4623 $groups = $wgImplicitGroups;
4624 # Deprecated, use $wgImplicitGroups instead
4625 Hooks
::run( 'UserGetImplicitGroups', array( &$groups ), '1.25' );
4631 * Get the title of a page describing a particular group
4633 * @param string $group Internal group name
4634 * @return Title|bool Title of the page if it exists, false otherwise
4636 public static function getGroupPage( $group ) {
4637 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4638 if ( $msg->exists() ) {
4639 $title = Title
::newFromText( $msg->text() );
4640 if ( is_object( $title ) ) {
4648 * Create a link to the group in HTML, if available;
4649 * else return the group name.
4651 * @param string $group Internal name of the group
4652 * @param string $text The text of the link
4653 * @return string HTML link to the group
4655 public static function makeGroupLinkHTML( $group, $text = '' ) {
4656 if ( $text == '' ) {
4657 $text = self
::getGroupName( $group );
4659 $title = self
::getGroupPage( $group );
4661 return Linker
::link( $title, htmlspecialchars( $text ) );
4663 return htmlspecialchars( $text );
4668 * Create a link to the group in Wikitext, if available;
4669 * else return the group name.
4671 * @param string $group Internal name of the group
4672 * @param string $text The text of the link
4673 * @return string Wikilink to the group
4675 public static function makeGroupLinkWiki( $group, $text = '' ) {
4676 if ( $text == '' ) {
4677 $text = self
::getGroupName( $group );
4679 $title = self
::getGroupPage( $group );
4681 $page = $title->getFullText();
4682 return "[[$page|$text]]";
4689 * Returns an array of the groups that a particular group can add/remove.
4691 * @param string $group The group to check for whether it can add/remove
4692 * @return array Array( 'add' => array( addablegroups ),
4693 * 'remove' => array( removablegroups ),
4694 * 'add-self' => array( addablegroups to self),
4695 * 'remove-self' => array( removable groups from self) )
4697 public static function changeableByGroup( $group ) {
4698 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4702 'remove' => array(),
4703 'add-self' => array(),
4704 'remove-self' => array()
4707 if ( empty( $wgAddGroups[$group] ) ) {
4708 // Don't add anything to $groups
4709 } elseif ( $wgAddGroups[$group] === true ) {
4710 // You get everything
4711 $groups['add'] = self
::getAllGroups();
4712 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4713 $groups['add'] = $wgAddGroups[$group];
4716 // Same thing for remove
4717 if ( empty( $wgRemoveGroups[$group] ) ) {
4719 } elseif ( $wgRemoveGroups[$group] === true ) {
4720 $groups['remove'] = self
::getAllGroups();
4721 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4722 $groups['remove'] = $wgRemoveGroups[$group];
4725 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4726 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4727 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4728 if ( is_int( $key ) ) {
4729 $wgGroupsAddToSelf['user'][] = $value;
4734 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
4735 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4736 if ( is_int( $key ) ) {
4737 $wgGroupsRemoveFromSelf['user'][] = $value;
4742 // Now figure out what groups the user can add to him/herself
4743 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4745 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4746 // No idea WHY this would be used, but it's there
4747 $groups['add-self'] = User
::getAllGroups();
4748 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4749 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4752 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4754 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4755 $groups['remove-self'] = User
::getAllGroups();
4756 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4757 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4764 * Returns an array of groups that this user can add and remove
4765 * @return array Array( 'add' => array( addablegroups ),
4766 * 'remove' => array( removablegroups ),
4767 * 'add-self' => array( addablegroups to self),
4768 * 'remove-self' => array( removable groups from self) )
4770 public function changeableGroups() {
4771 if ( $this->isAllowed( 'userrights' ) ) {
4772 // This group gives the right to modify everything (reverse-
4773 // compatibility with old "userrights lets you change
4775 // Using array_merge to make the groups reindexed
4776 $all = array_merge( User
::getAllGroups() );
4780 'add-self' => array(),
4781 'remove-self' => array()
4785 // Okay, it's not so simple, we will have to go through the arrays
4788 'remove' => array(),
4789 'add-self' => array(),
4790 'remove-self' => array()
4792 $addergroups = $this->getEffectiveGroups();
4794 foreach ( $addergroups as $addergroup ) {
4795 $groups = array_merge_recursive(
4796 $groups, $this->changeableByGroup( $addergroup )
4798 $groups['add'] = array_unique( $groups['add'] );
4799 $groups['remove'] = array_unique( $groups['remove'] );
4800 $groups['add-self'] = array_unique( $groups['add-self'] );
4801 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4807 * Deferred version of incEditCountImmediate()
4809 public function incEditCount() {
4811 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle( function() use ( $that ) {
4812 $that->incEditCountImmediate();
4817 * Increment the user's edit-count field.
4818 * Will have no effect for anonymous users.
4821 public function incEditCountImmediate() {
4822 if ( $this->isAnon() ) {
4826 $dbw = wfGetDB( DB_MASTER
);
4827 // No rows will be "affected" if user_editcount is NULL
4830 array( 'user_editcount=user_editcount+1' ),
4831 array( 'user_id' => $this->getId(), 'user_editcount IS NOT NULL' ),
4834 // Lazy initialization check...
4835 if ( $dbw->affectedRows() == 0 ) {
4836 // Now here's a goddamn hack...
4837 $dbr = wfGetDB( DB_SLAVE
);
4838 if ( $dbr !== $dbw ) {
4839 // If we actually have a slave server, the count is
4840 // at least one behind because the current transaction
4841 // has not been committed and replicated.
4842 $this->initEditCount( 1 );
4844 // But if DB_SLAVE is selecting the master, then the
4845 // count we just read includes the revision that was
4846 // just added in the working transaction.
4847 $this->initEditCount();
4850 // Edit count in user cache too
4851 $this->invalidateCache();
4855 * Initialize user_editcount from data out of the revision table
4857 * @param int $add Edits to add to the count from the revision table
4858 * @return int Number of edits
4860 protected function initEditCount( $add = 0 ) {
4861 // Pull from a slave to be less cruel to servers
4862 // Accuracy isn't the point anyway here
4863 $dbr = wfGetDB( DB_SLAVE
);
4864 $count = (int)$dbr->selectField(
4867 array( 'rev_user' => $this->getId() ),
4870 $count = $count +
$add;
4872 $dbw = wfGetDB( DB_MASTER
);
4875 array( 'user_editcount' => $count ),
4876 array( 'user_id' => $this->getId() ),
4884 * Get the description of a given right
4886 * @param string $right Right to query
4887 * @return string Localized description of the right
4889 public static function getRightDescription( $right ) {
4890 $key = "right-$right";
4891 $msg = wfMessage( $key );
4892 return $msg->isBlank() ?
$right : $msg->text();
4896 * Make a new-style password hash
4898 * @param string $password Plain-text password
4899 * @param bool|string $salt Optional salt, may be random or the user ID.
4900 * If unspecified or false, will generate one automatically
4901 * @return string Password hash
4902 * @deprecated since 1.24, use Password class
4904 public static function crypt( $password, $salt = false ) {
4905 wfDeprecated( __METHOD__
, '1.24' );
4906 $passwordFactory = new PasswordFactory();
4907 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4908 $hash = $passwordFactory->newFromPlaintext( $password );
4909 return $hash->toString();
4913 * Compare a password hash with a plain-text password. Requires the user
4914 * ID if there's a chance that the hash is an old-style hash.
4916 * @param string $hash Password hash
4917 * @param string $password Plain-text password to compare
4918 * @param string|bool $userId User ID for old-style password salt
4921 * @deprecated since 1.24, use Password class
4923 public static function comparePasswords( $hash, $password, $userId = false ) {
4924 wfDeprecated( __METHOD__
, '1.24' );
4926 // Check for *really* old password hashes that don't even have a type
4927 // The old hash format was just an md5 hex hash, with no type information
4928 if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) {
4929 global $wgPasswordSalt;
4930 if ( $wgPasswordSalt ) {
4931 $password = ":B:{$userId}:{$hash}";
4933 $password = ":A:{$hash}";
4937 $passwordFactory = new PasswordFactory();
4938 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4939 $hash = $passwordFactory->newFromCiphertext( $hash );
4940 return $hash->equals( $password );
4944 * Add a newuser log entry for this user.
4945 * Before 1.19 the return value was always true.
4947 * @param string|bool $action Account creation type.
4948 * - String, one of the following values:
4949 * - 'create' for an anonymous user creating an account for himself.
4950 * This will force the action's performer to be the created user itself,
4951 * no matter the value of $wgUser
4952 * - 'create2' for a logged in user creating an account for someone else
4953 * - 'byemail' when the created user will receive its password by e-mail
4954 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
4955 * - Boolean means whether the account was created by e-mail (deprecated):
4956 * - true will be converted to 'byemail'
4957 * - false will be converted to 'create' if this object is the same as
4958 * $wgUser and to 'create2' otherwise
4960 * @param string $reason User supplied reason
4962 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
4964 public function addNewUserLogEntry( $action = false, $reason = '' ) {
4965 global $wgUser, $wgNewUserLog;
4966 if ( empty( $wgNewUserLog ) ) {
4967 return true; // disabled
4970 if ( $action === true ) {
4971 $action = 'byemail';
4972 } elseif ( $action === false ) {
4973 if ( $this->equals( $wgUser ) ) {
4976 $action = 'create2';
4980 if ( $action === 'create' ||
$action === 'autocreate' ) {
4983 $performer = $wgUser;
4986 $logEntry = new ManualLogEntry( 'newusers', $action );
4987 $logEntry->setPerformer( $performer );
4988 $logEntry->setTarget( $this->getUserPage() );
4989 $logEntry->setComment( $reason );
4990 $logEntry->setParameters( array(
4991 '4::userid' => $this->getId(),
4993 $logid = $logEntry->insert();
4995 if ( $action !== 'autocreate' ) {
4996 $logEntry->publish( $logid );
5003 * Add an autocreate newuser log entry for this user
5004 * Used by things like CentralAuth and perhaps other authplugins.
5005 * Consider calling addNewUserLogEntry() directly instead.
5009 public function addNewUserLogEntryAutoCreate() {
5010 $this->addNewUserLogEntry( 'autocreate' );
5016 * Load the user options either from cache, the database or an array
5018 * @param array $data Rows for the current user out of the user_properties table
5020 protected function loadOptions( $data = null ) {
5025 if ( $this->mOptionsLoaded
) {
5029 $this->mOptions
= self
::getDefaultOptions();
5031 if ( !$this->getId() ) {
5032 // For unlogged-in users, load language/variant options from request.
5033 // There's no need to do it for logged-in users: they can set preferences,
5034 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5035 // so don't override user's choice (especially when the user chooses site default).
5036 $variant = $wgContLang->getDefaultVariant();
5037 $this->mOptions
['variant'] = $variant;
5038 $this->mOptions
['language'] = $variant;
5039 $this->mOptionsLoaded
= true;
5043 // Maybe load from the object
5044 if ( !is_null( $this->mOptionOverrides
) ) {
5045 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5046 foreach ( $this->mOptionOverrides
as $key => $value ) {
5047 $this->mOptions
[$key] = $value;
5050 if ( !is_array( $data ) ) {
5051 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5052 // Load from database
5053 $dbr = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
5054 ?
wfGetDB( DB_MASTER
)
5055 : wfGetDB( DB_SLAVE
);
5057 $res = $dbr->select(
5059 array( 'up_property', 'up_value' ),
5060 array( 'up_user' => $this->getId() ),
5064 $this->mOptionOverrides
= array();
5066 foreach ( $res as $row ) {
5067 $data[$row->up_property
] = $row->up_value
;
5070 foreach ( $data as $property => $value ) {
5071 $this->mOptionOverrides
[$property] = $value;
5072 $this->mOptions
[$property] = $value;
5076 $this->mOptionsLoaded
= true;
5078 Hooks
::run( 'UserLoadOptions', array( $this, &$this->mOptions
) );
5082 * Saves the non-default options for this user, as previously set e.g. via
5083 * setOption(), in the database's "user_properties" (preferences) table.
5084 * Usually used via saveSettings().
5086 protected function saveOptions() {
5087 $this->loadOptions();
5089 // Not using getOptions(), to keep hidden preferences in database
5090 $saveOptions = $this->mOptions
;
5092 // Allow hooks to abort, for instance to save to a global profile.
5093 // Reset options to default state before saving.
5094 if ( !Hooks
::run( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
5098 $userId = $this->getId();
5100 $insert_rows = array(); // all the new preference rows
5101 foreach ( $saveOptions as $key => $value ) {
5102 // Don't bother storing default values
5103 $defaultOption = self
::getDefaultOption( $key );
5104 if ( ( $defaultOption === null && $value !== false && $value !== null )
5105 ||
$value != $defaultOption
5107 $insert_rows[] = array(
5108 'up_user' => $userId,
5109 'up_property' => $key,
5110 'up_value' => $value,
5115 $dbw = wfGetDB( DB_MASTER
);
5117 $res = $dbw->select( 'user_properties',
5118 array( 'up_property', 'up_value' ), array( 'up_user' => $userId ), __METHOD__
);
5120 // Find prior rows that need to be removed or updated. These rows will
5121 // all be deleted (the later so that INSERT IGNORE applies the new values).
5122 $keysDelete = array();
5123 foreach ( $res as $row ) {
5124 if ( !isset( $saveOptions[$row->up_property
] )
5125 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
5127 $keysDelete[] = $row->up_property
;
5131 if ( count( $keysDelete ) ) {
5132 // Do the DELETE by PRIMARY KEY for prior rows.
5133 // In the past a very large portion of calls to this function are for setting
5134 // 'rememberpassword' for new accounts (a preference that has since been removed).
5135 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5136 // caused gap locks on [max user ID,+infinity) which caused high contention since
5137 // updates would pile up on each other as they are for higher (newer) user IDs.
5138 // It might not be necessary these days, but it shouldn't hurt either.
5139 $dbw->delete( 'user_properties',
5140 array( 'up_user' => $userId, 'up_property' => $keysDelete ), __METHOD__
);
5142 // Insert the new preference rows
5143 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, array( 'IGNORE' ) );
5147 * Lazily instantiate and return a factory object for making passwords
5149 * @deprecated since 1.27, create a PasswordFactory directly instead
5150 * @return PasswordFactory
5152 public static function getPasswordFactory() {
5153 wfDeprecated( __METHOD__
, '1.27' );
5154 $ret = new PasswordFactory();
5155 $ret->init( RequestContext
::getMain()->getConfig() );
5160 * Provide an array of HTML5 attributes to put on an input element
5161 * intended for the user to enter a new password. This may include
5162 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
5164 * Do *not* use this when asking the user to enter his current password!
5165 * Regardless of configuration, users may have invalid passwords for whatever
5166 * reason (e.g., they were set before requirements were tightened up).
5167 * Only use it when asking for a new password, like on account creation or
5170 * Obviously, you still need to do server-side checking.
5172 * NOTE: A combination of bugs in various browsers means that this function
5173 * actually just returns array() unconditionally at the moment. May as
5174 * well keep it around for when the browser bugs get fixed, though.
5176 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
5178 * @deprecated since 1.27
5179 * @return array Array of HTML attributes suitable for feeding to
5180 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
5181 * That will get confused by the boolean attribute syntax used.)
5183 public static function passwordChangeInputAttribs() {
5184 global $wgMinimalPasswordLength;
5186 if ( $wgMinimalPasswordLength == 0 ) {
5190 # Note that the pattern requirement will always be satisfied if the
5191 # input is empty, so we need required in all cases.
5193 # @todo FIXME: Bug 23769: This needs to not claim the password is required
5194 # if e-mail confirmation is being used. Since HTML5 input validation
5195 # is b0rked anyway in some browsers, just return nothing. When it's
5196 # re-enabled, fix this code to not output required for e-mail
5198 # $ret = array( 'required' );
5201 # We can't actually do this right now, because Opera 9.6 will print out
5202 # the entered password visibly in its error message! When other
5203 # browsers add support for this attribute, or Opera fixes its support,
5204 # we can add support with a version check to avoid doing this on Opera
5205 # versions where it will be a problem. Reported to Opera as
5206 # DSK-262266, but they don't have a public bug tracker for us to follow.
5208 if ( $wgMinimalPasswordLength > 1 ) {
5209 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
5210 $ret['title'] = wfMessage( 'passwordtooshort' )
5211 ->numParams( $wgMinimalPasswordLength )->text();
5219 * Return the list of user fields that should be selected to create
5220 * a new user object.
5223 public static function selectFields() {
5231 'user_email_authenticated',
5233 'user_email_token_expires',
5234 'user_registration',
5240 * Factory function for fatal permission-denied errors
5243 * @param string $permission User right required
5246 static function newFatalPermissionDeniedStatus( $permission ) {
5249 $groups = array_map(
5250 array( 'User', 'makeGroupLinkWiki' ),
5251 User
::getGroupsWithPermission( $permission )
5255 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5257 return Status
::newFatal( 'badaccess-group0' );
5262 * Get a new instance of this user that was loaded from the master via a locking read
5264 * Use this instead of the main context User when updating that user. This avoids races
5265 * where that user was loaded from a slave or even the master but without proper locks.
5267 * @return User|null Returns null if the user was not found in the DB
5270 public function getInstanceForUpdate() {
5271 if ( !$this->getId() ) {
5272 return null; // anon
5275 $user = self
::newFromId( $this->getId() );
5276 if ( !$user->loadFromId( self
::READ_EXCLUSIVE
) ) {
5284 * Checks if two user objects point to the same user.
5290 public function equals( User
$user ) {
5291 return $this->getName() === $user->getName();