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 * Test if it's safe to load this User object. You should typically check this before using
314 * $wgUser or RequestContext::getUser in a method that might be called before the system has
315 * been fully initialized. If the object is unsafe, you should use an anonymous user:
317 * $user = $wgUser->isSafeToLoad() ? $wgUser : new User;
323 public function isSafeToLoad() {
324 global $wgFullyInitialised;
325 return $wgFullyInitialised ||
$this->mLoadedItems
=== true ||
$this->mFrom
!== 'session';
329 * Load the user table data for this object from the source given by mFrom.
331 * @param integer $flags User::READ_* constant bitfield
333 public function load( $flags = self
::READ_NORMAL
) {
334 global $wgFullyInitialised;
336 if ( $this->mLoadedItems
=== true ) {
340 // Set it now to avoid infinite recursion in accessors
341 $oldLoadedItems = $this->mLoadedItems
;
342 $this->mLoadedItems
= true;
343 $this->queryFlagsUsed
= $flags;
345 // If this is called too early, things are likely to break.
346 if ( !$wgFullyInitialised && $this->mFrom
=== 'session' ) {
347 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
348 ->warning( 'User::loadFromSession called before the end of Setup.php', array(
349 'exception' => new Exception( 'User::loadFromSession called before the end of Setup.php' ),
351 $this->loadDefaults();
352 $this->mLoadedItems
= $oldLoadedItems;
356 switch ( $this->mFrom
) {
358 $this->loadDefaults();
361 // Make sure this thread sees its own changes
362 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
363 $flags |
= self
::READ_LATEST
;
364 $this->queryFlagsUsed
= $flags;
367 $this->mId
= self
::idFromName( $this->mName
, $flags );
369 // Nonexistent user placeholder object
370 $this->loadDefaults( $this->mName
);
372 $this->loadFromId( $flags );
376 $this->loadFromId( $flags );
379 if ( !$this->loadFromSession() ) {
380 // Loading from session failed. Load defaults.
381 $this->loadDefaults();
383 Hooks
::run( 'UserLoadAfterLoadFromSession', array( $this ) );
386 throw new UnexpectedValueException(
387 "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
392 * Load user table data, given mId has already been set.
393 * @param integer $flags User::READ_* constant bitfield
394 * @return bool False if the ID does not exist, true otherwise
396 public function loadFromId( $flags = self
::READ_NORMAL
) {
397 if ( $this->mId
== 0 ) {
398 $this->loadDefaults();
402 // Try cache (unless this needs data from the master DB).
403 // NOTE: if this thread called saveSettings(), the cache was cleared.
404 $latest = DBAccessObjectUtils
::hasFlags( $flags, self
::READ_LATEST
);
405 if ( $latest ||
!$this->loadFromCache() ) {
406 wfDebug( "User: cache miss for user {$this->mId}\n" );
407 // Load from DB (make sure this thread sees its own changes)
408 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
409 $flags |
= self
::READ_LATEST
;
411 if ( !$this->loadFromDatabase( $flags ) ) {
412 // Can't load from ID, user is anonymous
415 $this->saveToCache();
418 $this->mLoadedItems
= true;
419 $this->queryFlagsUsed
= $flags;
426 * @param string $wikiId
427 * @param integer $userId
429 public static function purge( $wikiId, $userId ) {
430 $cache = ObjectCache
::getMainWANInstance();
431 $cache->delete( $cache->makeGlobalKey( 'user', 'id', $wikiId, $userId ) );
436 * @param WANObjectCache $cache
439 protected function getCacheKey( WANObjectCache
$cache ) {
440 return $cache->makeGlobalKey( 'user', 'id', wfWikiID(), $this->mId
);
444 * Load user data from shared cache, given mId has already been set.
446 * @return bool false if the ID does not exist or data is invalid, true otherwise
449 protected function loadFromCache() {
450 if ( $this->mId
== 0 ) {
451 $this->loadDefaults();
455 $cache = ObjectCache
::getMainWANInstance();
456 $data = $cache->get( $this->getCacheKey( $cache ) );
457 if ( !is_array( $data ) ||
$data['mVersion'] < self
::VERSION
) {
462 wfDebug( "User: got user {$this->mId} from cache\n" );
464 // Restore from cache
465 foreach ( self
::$mCacheVars as $name ) {
466 $this->$name = $data[$name];
473 * Save user data to the shared cache
475 * This method should not be called outside the User class
477 public function saveToCache() {
480 $this->loadOptions();
482 if ( $this->isAnon() ) {
483 // Anonymous users are uncached
488 foreach ( self
::$mCacheVars as $name ) {
489 $data[$name] = $this->$name;
491 $data['mVersion'] = self
::VERSION
;
492 $opts = Database
::getCacheSetOptions( wfGetDB( DB_SLAVE
) );
494 $cache = ObjectCache
::getMainWANInstance();
495 $key = $this->getCacheKey( $cache );
496 $cache->set( $key, $data, $cache::TTL_HOUR
, $opts );
499 /** @name newFrom*() static factory methods */
503 * Static factory method for creation from username.
505 * This is slightly less efficient than newFromId(), so use newFromId() if
506 * you have both an ID and a name handy.
508 * @param string $name Username, validated by Title::newFromText()
509 * @param string|bool $validate Validate username. Takes the same parameters as
510 * User::getCanonicalName(), except that true is accepted as an alias
511 * for 'valid', for BC.
513 * @return User|bool User object, or false if the username is invalid
514 * (e.g. if it contains illegal characters or is an IP address). If the
515 * username is not present in the database, the result will be a user object
516 * with a name, zero user ID and default settings.
518 public static function newFromName( $name, $validate = 'valid' ) {
519 if ( $validate === true ) {
522 $name = self
::getCanonicalName( $name, $validate );
523 if ( $name === false ) {
526 // Create unloaded user object
530 $u->setItemLoaded( 'name' );
536 * Static factory method for creation from a given user ID.
538 * @param int $id Valid user ID
539 * @return User The corresponding User object
541 public static function newFromId( $id ) {
545 $u->setItemLoaded( 'id' );
550 * Factory method to fetch whichever user has a given email confirmation code.
551 * This code is generated when an account is created or its e-mail address
554 * If the code is invalid or has expired, returns NULL.
556 * @param string $code Confirmation code
557 * @param int $flags User::READ_* bitfield
560 public static function newFromConfirmationCode( $code, $flags = 0 ) {
561 $db = ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
562 ?
wfGetDB( DB_MASTER
)
563 : wfGetDB( DB_SLAVE
);
565 $id = $db->selectField(
569 'user_email_token' => md5( $code ),
570 'user_email_token_expires > ' . $db->addQuotes( $db->timestamp() ),
574 return $id ? User
::newFromId( $id ) : null;
578 * Create a new user object using data from session. If the login
579 * credentials are invalid, the result is an anonymous user.
581 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
584 public static function newFromSession( WebRequest
$request = null ) {
586 $user->mFrom
= 'session';
587 $user->mRequest
= $request;
592 * Create a new user object from a user row.
593 * The row should have the following fields from the user table in it:
594 * - either user_name or user_id to load further data if needed (or both)
596 * - all other fields (email, etc.)
597 * It is useless to provide the remaining fields if either user_id,
598 * user_name and user_real_name are not provided because the whole row
599 * will be loaded once more from the database when accessing them.
601 * @param stdClass $row A row from the user table
602 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
605 public static function newFromRow( $row, $data = null ) {
607 $user->loadFromRow( $row, $data );
612 * Static factory method for creation of a "system" user from username.
614 * A "system" user is an account that's used to attribute logged actions
615 * taken by MediaWiki itself, as opposed to a bot or human user. Examples
616 * might include the 'Maintenance script' or 'Conversion script' accounts
617 * used by various scripts in the maintenance/ directory or accounts such
618 * as 'MediaWiki message delivery' used by the MassMessage extension.
620 * This can optionally create the user if it doesn't exist, and "steal" the
621 * account if it does exist.
623 * @param string $name Username
624 * @param array $options Options are:
625 * - validate: As for User::getCanonicalName(), default 'valid'
626 * - create: Whether to create the user if it doesn't already exist, default true
627 * - steal: Whether to reset the account's password and email if it
628 * already exists, default false
631 public static function newSystemUser( $name, $options = array() ) {
633 'validate' => 'valid',
638 $name = self
::getCanonicalName( $name, $options['validate'] );
639 if ( $name === false ) {
643 $dbw = wfGetDB( DB_MASTER
);
644 $row = $dbw->selectRow(
647 self
::selectFields(),
648 array( 'user_password', 'user_newpassword' )
650 array( 'user_name' => $name ),
654 // No user. Create it?
655 return $options['create'] ? self
::createNew( $name ) : null;
657 $user = self
::newFromRow( $row );
659 // A user is considered to exist as a non-system user if it has a
660 // password set, or a temporary password set, or an email set.
661 $passwordFactory = new PasswordFactory();
662 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
664 $password = $passwordFactory->newFromCiphertext( $row->user_password
);
665 } catch ( PasswordError
$e ) {
666 wfDebug( 'Invalid password hash found in database.' );
667 $password = PasswordFactory
::newInvalidPassword();
670 $newpassword = $passwordFactory->newFromCiphertext( $row->user_newpassword
);
671 } catch ( PasswordError
$e ) {
672 wfDebug( 'Invalid password hash found in database.' );
673 $newpassword = PasswordFactory
::newInvalidPassword();
675 if ( !$password instanceof InvalidPassword ||
!$newpassword instanceof InvalidPassword
678 // User exists. Steal it?
679 if ( !$options['steal'] ) {
683 $nopass = PasswordFactory
::newInvalidPassword()->toString();
688 'user_password' => $nopass,
689 'user_newpassword' => $nopass,
690 'user_newpass_time' => null,
692 array( 'user_id' => $user->getId() ),
695 $user->invalidateEmail();
696 $user->saveSettings();
699 SessionManager
::singleton()->preventSessionsForUser( $user->getName() );
707 * Get the username corresponding to a given user ID
708 * @param int $id User ID
709 * @return string|bool The corresponding username
711 public static function whoIs( $id ) {
712 return UserCache
::singleton()->getProp( $id, 'name' );
716 * Get the real name of a user given their user ID
718 * @param int $id User ID
719 * @return string|bool The corresponding user's real name
721 public static function whoIsReal( $id ) {
722 return UserCache
::singleton()->getProp( $id, 'real_name' );
726 * Get database id given a user name
727 * @param string $name Username
728 * @param integer $flags User::READ_* constant bitfield
729 * @return int|null The corresponding user's ID, or null if user is nonexistent
731 public static function idFromName( $name, $flags = self
::READ_NORMAL
) {
732 $nt = Title
::makeTitleSafe( NS_USER
, $name );
733 if ( is_null( $nt ) ) {
738 if ( !( $flags & self
::READ_LATEST
) && isset( self
::$idCacheByName[$name] ) ) {
739 return self
::$idCacheByName[$name];
742 $db = ( $flags & self
::READ_LATEST
)
743 ?
wfGetDB( DB_MASTER
)
744 : wfGetDB( DB_SLAVE
);
749 array( 'user_name' => $nt->getText() ),
753 if ( $s === false ) {
756 $result = $s->user_id
;
759 self
::$idCacheByName[$name] = $result;
761 if ( count( self
::$idCacheByName ) > 1000 ) {
762 self
::$idCacheByName = array();
769 * Reset the cache used in idFromName(). For use in tests.
771 public static function resetIdByNameCache() {
772 self
::$idCacheByName = array();
776 * Does the string match an anonymous IPv4 address?
778 * This function exists for username validation, in order to reject
779 * usernames which are similar in form to IP addresses. Strings such
780 * as 300.300.300.300 will return true because it looks like an IP
781 * address, despite not being strictly valid.
783 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
784 * address because the usemod software would "cloak" anonymous IP
785 * addresses like this, if we allowed accounts like this to be created
786 * new users could get the old edits of these anonymous users.
788 * @param string $name Name to match
791 public static function isIP( $name ) {
792 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
793 || IP
::isIPv6( $name );
797 * Is the input a valid username?
799 * Checks if the input is a valid username, we don't want an empty string,
800 * an IP address, anything that contains slashes (would mess up subpages),
801 * is longer than the maximum allowed username size or doesn't begin with
804 * @param string $name Name to match
807 public static function isValidUserName( $name ) {
808 global $wgContLang, $wgMaxNameChars;
811 || User
::isIP( $name )
812 ||
strpos( $name, '/' ) !== false
813 ||
strlen( $name ) > $wgMaxNameChars
814 ||
$name != $wgContLang->ucfirst( $name )
816 wfDebugLog( 'username', __METHOD__
.
817 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
821 // Ensure that the name can't be misresolved as a different title,
822 // such as with extra namespace keys at the start.
823 $parsed = Title
::newFromText( $name );
824 if ( is_null( $parsed )
825 ||
$parsed->getNamespace()
826 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
827 wfDebugLog( 'username', __METHOD__
.
828 ": '$name' invalid due to ambiguous prefixes" );
832 // Check an additional blacklist of troublemaker characters.
833 // Should these be merged into the title char list?
834 $unicodeBlacklist = '/[' .
835 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
836 '\x{00a0}' . # non-breaking space
837 '\x{2000}-\x{200f}' . # various whitespace
838 '\x{2028}-\x{202f}' . # breaks and control chars
839 '\x{3000}' . # ideographic space
840 '\x{e000}-\x{f8ff}' . # private use
842 if ( preg_match( $unicodeBlacklist, $name ) ) {
843 wfDebugLog( 'username', __METHOD__
.
844 ": '$name' invalid due to blacklisted characters" );
852 * Usernames which fail to pass this function will be blocked
853 * from user login and new account registrations, but may be used
854 * internally by batch processes.
856 * If an account already exists in this form, login will be blocked
857 * by a failure to pass this function.
859 * @param string $name Name to match
862 public static function isUsableName( $name ) {
863 global $wgReservedUsernames;
864 // Must be a valid username, obviously ;)
865 if ( !self
::isValidUserName( $name ) ) {
869 static $reservedUsernames = false;
870 if ( !$reservedUsernames ) {
871 $reservedUsernames = $wgReservedUsernames;
872 Hooks
::run( 'UserGetReservedNames', array( &$reservedUsernames ) );
875 // Certain names may be reserved for batch processes.
876 foreach ( $reservedUsernames as $reserved ) {
877 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
878 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
880 if ( $reserved == $name ) {
888 * Usernames which fail to pass this function will be blocked
889 * from new account registrations, but may be used internally
890 * either by batch processes or by user accounts which have
891 * already been created.
893 * Additional blacklisting may be added here rather than in
894 * isValidUserName() to avoid disrupting existing accounts.
896 * @param string $name String to match
899 public static function isCreatableName( $name ) {
900 global $wgInvalidUsernameCharacters;
902 // Ensure that the username isn't longer than 235 bytes, so that
903 // (at least for the builtin skins) user javascript and css files
904 // will work. (bug 23080)
905 if ( strlen( $name ) > 235 ) {
906 wfDebugLog( 'username', __METHOD__
.
907 ": '$name' invalid due to length" );
911 // Preg yells if you try to give it an empty string
912 if ( $wgInvalidUsernameCharacters !== '' ) {
913 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
914 wfDebugLog( 'username', __METHOD__
.
915 ": '$name' invalid due to wgInvalidUsernameCharacters" );
920 return self
::isUsableName( $name );
924 * Is the input a valid password for this user?
926 * @param string $password Desired password
929 public function isValidPassword( $password ) {
930 // simple boolean wrapper for getPasswordValidity
931 return $this->getPasswordValidity( $password ) === true;
935 * Given unvalidated password input, return error message on failure.
937 * @param string $password Desired password
938 * @return bool|string|array True on success, string or array of error message on failure
940 public function getPasswordValidity( $password ) {
941 $result = $this->checkPasswordValidity( $password );
942 if ( $result->isGood() ) {
946 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
947 $messages[] = $error['message'];
949 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
950 $messages[] = $warning['message'];
952 if ( count( $messages ) === 1 ) {
960 * Check if this is a valid password for this user
962 * Create a Status object based on the password's validity.
963 * The Status should be set to fatal if the user should not
964 * be allowed to log in, and should have any errors that
965 * would block changing the password.
967 * If the return value of this is not OK, the password
968 * should not be checked. If the return value is not Good,
969 * the password can be checked, but the user should not be
970 * able to set their password to this.
972 * @param string $password Desired password
973 * @param string $purpose one of 'login', 'create', 'reset'
977 public function checkPasswordValidity( $password, $purpose = 'login' ) {
978 global $wgPasswordPolicy;
980 $upp = new UserPasswordPolicy(
981 $wgPasswordPolicy['policies'],
982 $wgPasswordPolicy['checks']
985 $status = Status
::newGood();
986 $result = false; // init $result to false for the internal checks
988 if ( !Hooks
::run( 'isValidPassword', array( $password, &$result, $this ) ) ) {
989 $status->error( $result );
993 if ( $result === false ) {
994 $status->merge( $upp->checkUserPassword( $this, $password, $purpose ) );
996 } elseif ( $result === true ) {
999 $status->error( $result );
1000 return $status; // the isValidPassword hook set a string $result and returned true
1005 * Given unvalidated user input, return a canonical username, or false if
1006 * the username is invalid.
1007 * @param string $name User input
1008 * @param string|bool $validate Type of validation to use:
1009 * - false No validation
1010 * - 'valid' Valid for batch processes
1011 * - 'usable' Valid for batch processes and login
1012 * - 'creatable' Valid for batch processes, login and account creation
1014 * @throws InvalidArgumentException
1015 * @return bool|string
1017 public static function getCanonicalName( $name, $validate = 'valid' ) {
1018 // Force usernames to capital
1020 $name = $wgContLang->ucfirst( $name );
1022 # Reject names containing '#'; these will be cleaned up
1023 # with title normalisation, but then it's too late to
1025 if ( strpos( $name, '#' ) !== false ) {
1029 // Clean up name according to title rules,
1030 // but only when validation is requested (bug 12654)
1031 $t = ( $validate !== false ) ?
1032 Title
::newFromText( $name ) : Title
::makeTitle( NS_USER
, $name );
1033 // Check for invalid titles
1034 if ( is_null( $t ) ) {
1038 // Reject various classes of invalid names
1040 $name = $wgAuth->getCanonicalName( $t->getText() );
1042 switch ( $validate ) {
1046 if ( !User
::isValidUserName( $name ) ) {
1051 if ( !User
::isUsableName( $name ) ) {
1056 if ( !User
::isCreatableName( $name ) ) {
1061 throw new InvalidArgumentException(
1062 'Invalid parameter value for $validate in ' . __METHOD__
);
1068 * Count the number of edits of a user
1070 * @param int $uid User ID to check
1071 * @return int The user's edit count
1073 * @deprecated since 1.21 in favour of User::getEditCount
1075 public static function edits( $uid ) {
1076 wfDeprecated( __METHOD__
, '1.21' );
1077 $user = self
::newFromId( $uid );
1078 return $user->getEditCount();
1082 * Return a random password.
1084 * @deprecated since 1.27, use PasswordFactory::generateRandomPasswordString()
1085 * @return string New random password
1087 public static function randomPassword() {
1088 global $wgMinimalPasswordLength;
1089 return PasswordFactory
::generateRandomPasswordString( $wgMinimalPasswordLength );
1093 * Set cached properties to default.
1095 * @note This no longer clears uncached lazy-initialised properties;
1096 * the constructor does that instead.
1098 * @param string|bool $name
1100 public function loadDefaults( $name = false ) {
1102 $this->mName
= $name;
1103 $this->mRealName
= '';
1105 $this->mOptionOverrides
= null;
1106 $this->mOptionsLoaded
= false;
1108 $loggedOut = $this->mRequest ?
$this->mRequest
->getSession()->getLoggedOutTimestamp() : 0;
1109 if ( $loggedOut !== 0 ) {
1110 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1112 $this->mTouched
= '1'; # Allow any pages to be cached
1115 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1116 $this->mEmailAuthenticated
= null;
1117 $this->mEmailToken
= '';
1118 $this->mEmailTokenExpires
= null;
1119 $this->mRegistration
= wfTimestamp( TS_MW
);
1120 $this->mGroups
= array();
1122 Hooks
::run( 'UserLoadDefaults', array( $this, $name ) );
1126 * Return whether an item has been loaded.
1128 * @param string $item Item to check. Current possibilities:
1132 * @param string $all 'all' to check if the whole object has been loaded
1133 * or any other string to check if only the item is available (e.g.
1137 public function isItemLoaded( $item, $all = 'all' ) {
1138 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1139 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1143 * Set that an item has been loaded
1145 * @param string $item
1147 protected function setItemLoaded( $item ) {
1148 if ( is_array( $this->mLoadedItems
) ) {
1149 $this->mLoadedItems
[$item] = true;
1154 * Load user data from the session.
1156 * @return bool True if the user is logged in, false otherwise.
1158 private function loadFromSession() {
1161 Hooks
::run( 'UserLoadFromSession', array( $this, &$result ), '1.27' );
1162 if ( $result !== null ) {
1166 // MediaWiki\Session\Session already did the necessary authentication of the user
1167 // returned here, so just use it if applicable.
1168 $session = $this->getRequest()->getSession();
1169 $user = $session->getUser();
1170 if ( $user->isLoggedIn() ) {
1171 $this->loadFromUserObject( $user );
1172 // Other code expects these to be set in the session, so set them.
1173 $session->set( 'wsUserID', $this->getId() );
1174 $session->set( 'wsUserName', $this->getName() );
1175 $session->set( 'wsToken', $this->getToken() );
1183 * Load user and user_group data from the database.
1184 * $this->mId must be set, this is how the user is identified.
1186 * @param integer $flags User::READ_* constant bitfield
1187 * @return bool True if the user exists, false if the user is anonymous
1189 public function loadFromDatabase( $flags = self
::READ_LATEST
) {
1191 $this->mId
= intval( $this->mId
);
1194 if ( !$this->mId
) {
1195 $this->loadDefaults();
1199 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
1200 $db = wfGetDB( $index );
1202 $s = $db->selectRow(
1204 self
::selectFields(),
1205 array( 'user_id' => $this->mId
),
1210 $this->queryFlagsUsed
= $flags;
1211 Hooks
::run( 'UserLoadFromDatabase', array( $this, &$s ) );
1213 if ( $s !== false ) {
1214 // Initialise user table data
1215 $this->loadFromRow( $s );
1216 $this->mGroups
= null; // deferred
1217 $this->getEditCount(); // revalidation for nulls
1222 $this->loadDefaults();
1228 * Initialize this object from a row from the user table.
1230 * @param stdClass $row Row from the user table to load.
1231 * @param array $data Further user data to load into the object
1233 * user_groups Array with groups out of the user_groups table
1234 * user_properties Array with properties out of the user_properties table
1236 protected function loadFromRow( $row, $data = null ) {
1239 $this->mGroups
= null; // deferred
1241 if ( isset( $row->user_name
) ) {
1242 $this->mName
= $row->user_name
;
1243 $this->mFrom
= 'name';
1244 $this->setItemLoaded( 'name' );
1249 if ( isset( $row->user_real_name
) ) {
1250 $this->mRealName
= $row->user_real_name
;
1251 $this->setItemLoaded( 'realname' );
1256 if ( isset( $row->user_id
) ) {
1257 $this->mId
= intval( $row->user_id
);
1258 $this->mFrom
= 'id';
1259 $this->setItemLoaded( 'id' );
1264 if ( isset( $row->user_id
) && isset( $row->user_name
) ) {
1265 self
::$idCacheByName[$row->user_name
] = $row->user_id
;
1268 if ( isset( $row->user_editcount
) ) {
1269 $this->mEditCount
= $row->user_editcount
;
1274 if ( isset( $row->user_touched
) ) {
1275 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1280 if ( isset( $row->user_token
) ) {
1281 // The definition for the column is binary(32), so trim the NULs
1282 // that appends. The previous definition was char(32), so trim
1284 $this->mToken
= rtrim( $row->user_token
, " \0" );
1285 if ( $this->mToken
=== '' ) {
1286 $this->mToken
= null;
1292 if ( isset( $row->user_email
) ) {
1293 $this->mEmail
= $row->user_email
;
1294 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1295 $this->mEmailToken
= $row->user_email_token
;
1296 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1297 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1303 $this->mLoadedItems
= true;
1306 if ( is_array( $data ) ) {
1307 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1308 $this->mGroups
= $data['user_groups'];
1310 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1311 $this->loadOptions( $data['user_properties'] );
1317 * Load the data for this user object from another user object.
1321 protected function loadFromUserObject( $user ) {
1323 $user->loadGroups();
1324 $user->loadOptions();
1325 foreach ( self
::$mCacheVars as $var ) {
1326 $this->$var = $user->$var;
1331 * Load the groups from the database if they aren't already loaded.
1333 private function loadGroups() {
1334 if ( is_null( $this->mGroups
) ) {
1335 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
1336 ?
wfGetDB( DB_MASTER
)
1337 : wfGetDB( DB_SLAVE
);
1338 $res = $db->select( 'user_groups',
1339 array( 'ug_group' ),
1340 array( 'ug_user' => $this->mId
),
1342 $this->mGroups
= array();
1343 foreach ( $res as $row ) {
1344 $this->mGroups
[] = $row->ug_group
;
1350 * Add the user to the group if he/she meets given criteria.
1352 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1353 * possible to remove manually via Special:UserRights. In such case it
1354 * will not be re-added automatically. The user will also not lose the
1355 * group if they no longer meet the criteria.
1357 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1359 * @return array Array of groups the user has been promoted to.
1361 * @see $wgAutopromoteOnce
1363 public function addAutopromoteOnceGroups( $event ) {
1364 global $wgAutopromoteOnceLogInRC, $wgAuth;
1366 if ( wfReadOnly() ||
!$this->getId() ) {
1370 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1371 if ( !count( $toPromote ) ) {
1375 if ( !$this->checkAndSetTouched() ) {
1376 return array(); // raced out (bug T48834)
1379 $oldGroups = $this->getGroups(); // previous groups
1380 foreach ( $toPromote as $group ) {
1381 $this->addGroup( $group );
1383 // update groups in external authentication database
1384 Hooks
::run( 'UserGroupsChanged', array( $this, $toPromote, array(), false ) );
1385 $wgAuth->updateExternalDBGroups( $this, $toPromote );
1387 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1389 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1390 $logEntry->setPerformer( $this );
1391 $logEntry->setTarget( $this->getUserPage() );
1392 $logEntry->setParameters( array(
1393 '4::oldgroups' => $oldGroups,
1394 '5::newgroups' => $newGroups,
1396 $logid = $logEntry->insert();
1397 if ( $wgAutopromoteOnceLogInRC ) {
1398 $logEntry->publish( $logid );
1405 * Bump user_touched if it didn't change since this object was loaded
1407 * On success, the mTouched field is updated.
1408 * The user serialization cache is always cleared.
1410 * @return bool Whether user_touched was actually updated
1413 protected function checkAndSetTouched() {
1416 if ( !$this->mId
) {
1417 return false; // anon
1420 // Get a new user_touched that is higher than the old one
1421 $oldTouched = $this->mTouched
;
1422 $newTouched = $this->newTouchedTimestamp();
1424 $dbw = wfGetDB( DB_MASTER
);
1425 $dbw->update( 'user',
1426 array( 'user_touched' => $dbw->timestamp( $newTouched ) ),
1428 'user_id' => $this->mId
,
1429 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
1433 $success = ( $dbw->affectedRows() > 0 );
1436 $this->mTouched
= $newTouched;
1437 $this->clearSharedCache();
1439 // Clears on failure too since that is desired if the cache is stale
1440 $this->clearSharedCache( 'refresh' );
1447 * Clear various cached data stored in this object. The cache of the user table
1448 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1450 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1451 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1453 public function clearInstanceCache( $reloadFrom = false ) {
1454 $this->mNewtalk
= -1;
1455 $this->mDatePreference
= null;
1456 $this->mBlockedby
= -1; # Unset
1457 $this->mHash
= false;
1458 $this->mRights
= null;
1459 $this->mEffectiveGroups
= null;
1460 $this->mImplicitGroups
= null;
1461 $this->mGroups
= null;
1462 $this->mOptions
= null;
1463 $this->mOptionsLoaded
= false;
1464 $this->mEditCount
= null;
1466 if ( $reloadFrom ) {
1467 $this->mLoadedItems
= array();
1468 $this->mFrom
= $reloadFrom;
1473 * Combine the language default options with any site-specific options
1474 * and add the default language variants.
1476 * @return array Array of String options
1478 public static function getDefaultOptions() {
1479 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1481 static $defOpt = null;
1482 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1483 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1484 // mid-request and see that change reflected in the return value of this function.
1485 // Which is insane and would never happen during normal MW operation
1489 $defOpt = $wgDefaultUserOptions;
1490 // Default language setting
1491 $defOpt['language'] = $wgContLang->getCode();
1492 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1493 $defOpt[$langCode == $wgContLang->getCode() ?
'variant' : "variant-$langCode"] = $langCode;
1495 foreach ( SearchEngine
::searchableNamespaces() as $nsnum => $nsname ) {
1496 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1498 $defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1500 Hooks
::run( 'UserGetDefaultOptions', array( &$defOpt ) );
1506 * Get a given default option value.
1508 * @param string $opt Name of option to retrieve
1509 * @return string Default option value
1511 public static function getDefaultOption( $opt ) {
1512 $defOpts = self
::getDefaultOptions();
1513 if ( isset( $defOpts[$opt] ) ) {
1514 return $defOpts[$opt];
1521 * Get blocking information
1522 * @param bool $bFromSlave Whether to check the slave database first.
1523 * To improve performance, non-critical checks are done against slaves.
1524 * Check when actually saving should be done against master.
1526 private function getBlockedStatus( $bFromSlave = true ) {
1527 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1529 if ( -1 != $this->mBlockedby
) {
1533 wfDebug( __METHOD__
. ": checking...\n" );
1535 // Initialize data...
1536 // Otherwise something ends up stomping on $this->mBlockedby when
1537 // things get lazy-loaded later, causing false positive block hits
1538 // due to -1 !== 0. Probably session-related... Nothing should be
1539 // overwriting mBlockedby, surely?
1542 # We only need to worry about passing the IP address to the Block generator if the
1543 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1544 # know which IP address they're actually coming from
1546 if ( !$this->isAllowed( 'ipblock-exempt' ) ) {
1547 // $wgUser->getName() only works after the end of Setup.php. Until
1548 // then, assume it's a logged-out user.
1549 $globalUserName = $wgUser->isSafeToLoad()
1550 ?
$wgUser->getName()
1551 : IP
::sanitizeIP( $wgUser->getRequest()->getIP() );
1552 if ( $this->getName() === $globalUserName ) {
1553 $ip = $this->getRequest()->getIP();
1558 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1561 if ( !$block instanceof Block
&& $ip !== null && !in_array( $ip, $wgProxyWhitelist ) ) {
1563 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1565 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1566 $block->mReason
= wfMessage( 'proxyblockreason' )->text();
1567 $block->setTarget( $ip );
1568 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1570 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1571 $block->mReason
= wfMessage( 'sorbsreason' )->text();
1572 $block->setTarget( $ip );
1576 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1577 if ( !$block instanceof Block
1578 && $wgApplyIpBlocksToXff
1580 && !in_array( $ip, $wgProxyWhitelist )
1582 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1583 $xff = array_map( 'trim', explode( ',', $xff ) );
1584 $xff = array_diff( $xff, array( $ip ) );
1585 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1586 $block = Block
::chooseBlock( $xffblocks, $xff );
1587 if ( $block instanceof Block
) {
1588 # Mangle the reason to alert the user that the block
1589 # originated from matching the X-Forwarded-For header.
1590 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->text();
1594 if ( $block instanceof Block
) {
1595 wfDebug( __METHOD__
. ": Found block.\n" );
1596 $this->mBlock
= $block;
1597 $this->mBlockedby
= $block->getByName();
1598 $this->mBlockreason
= $block->mReason
;
1599 $this->mHideName
= $block->mHideName
;
1600 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1602 $this->mBlockedby
= '';
1603 $this->mHideName
= 0;
1604 $this->mAllowUsertalk
= false;
1608 Hooks
::run( 'GetBlockedStatus', array( &$this ) );
1613 * Whether the given IP is in a DNS blacklist.
1615 * @param string $ip IP to check
1616 * @param bool $checkWhitelist Whether to check the whitelist first
1617 * @return bool True if blacklisted.
1619 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1620 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1622 if ( !$wgEnableDnsBlacklist ) {
1626 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1630 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1634 * Whether the given IP is in a given DNS blacklist.
1636 * @param string $ip IP to check
1637 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1638 * @return bool True if blacklisted.
1640 public function inDnsBlacklist( $ip, $bases ) {
1643 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1644 if ( IP
::isIPv4( $ip ) ) {
1645 // Reverse IP, bug 21255
1646 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1648 foreach ( (array)$bases as $base ) {
1650 // If we have an access key, use that too (ProjectHoneypot, etc.)
1652 if ( is_array( $base ) ) {
1653 if ( count( $base ) >= 2 ) {
1654 // Access key is 1, base URL is 0
1655 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1657 $host = "$ipReversed.{$base[0]}";
1659 $basename = $base[0];
1661 $host = "$ipReversed.$base";
1665 $ipList = gethostbynamel( $host );
1668 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
1672 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
1681 * Check if an IP address is in the local proxy list
1687 public static function isLocallyBlockedProxy( $ip ) {
1688 global $wgProxyList;
1690 if ( !$wgProxyList ) {
1694 if ( !is_array( $wgProxyList ) ) {
1695 // Load from the specified file
1696 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1699 if ( !is_array( $wgProxyList ) ) {
1701 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1703 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1704 // Old-style flipped proxy list
1713 * Is this user subject to rate limiting?
1715 * @return bool True if rate limited
1717 public function isPingLimitable() {
1718 global $wgRateLimitsExcludedIPs;
1719 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1720 // No other good way currently to disable rate limits
1721 // for specific IPs. :P
1722 // But this is a crappy hack and should die.
1725 return !$this->isAllowed( 'noratelimit' );
1729 * Primitive rate limits: enforce maximum actions per time period
1730 * to put a brake on flooding.
1732 * The method generates both a generic profiling point and a per action one
1733 * (suffix being "-$action".
1735 * @note When using a shared cache like memcached, IP-address
1736 * last-hit counters will be shared across wikis.
1738 * @param string $action Action to enforce; 'edit' if unspecified
1739 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1740 * @return bool True if a rate limiter was tripped
1742 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1743 // Call the 'PingLimiter' hook
1745 if ( !Hooks
::run( 'PingLimiter', array( &$this, $action, &$result, $incrBy ) ) ) {
1749 global $wgRateLimits;
1750 if ( !isset( $wgRateLimits[$action] ) ) {
1754 // Some groups shouldn't trigger the ping limiter, ever
1755 if ( !$this->isPingLimitable() ) {
1759 $limits = $wgRateLimits[$action];
1761 $id = $this->getId();
1763 $isNewbie = $this->isNewbie();
1767 if ( isset( $limits['anon'] ) ) {
1768 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1771 // limits for logged-in users
1772 if ( isset( $limits['user'] ) ) {
1773 $userLimit = $limits['user'];
1775 // limits for newbie logged-in users
1776 if ( $isNewbie && isset( $limits['newbie'] ) ) {
1777 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1781 // limits for anons and for newbie logged-in users
1784 if ( isset( $limits['ip'] ) ) {
1785 $ip = $this->getRequest()->getIP();
1786 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1788 // subnet-based limits
1789 if ( isset( $limits['subnet'] ) ) {
1790 $ip = $this->getRequest()->getIP();
1791 $subnet = IP
::getSubnet( $ip );
1792 if ( $subnet !== false ) {
1793 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1798 // Check for group-specific permissions
1799 // If more than one group applies, use the group with the highest limit ratio (max/period)
1800 foreach ( $this->getGroups() as $group ) {
1801 if ( isset( $limits[$group] ) ) {
1802 if ( $userLimit === false
1803 ||
$limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1805 $userLimit = $limits[$group];
1810 // Set the user limit key
1811 if ( $userLimit !== false ) {
1812 list( $max, $period ) = $userLimit;
1813 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
1814 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1817 // ip-based limits for all ping-limitable users
1818 if ( isset( $limits['ip-all'] ) ) {
1819 $ip = $this->getRequest()->getIP();
1820 // ignore if user limit is more permissive
1821 if ( $isNewbie ||
$userLimit === false
1822 ||
$limits['ip-all'][0] / $limits['ip-all'][1] > $userLimit[0] / $userLimit[1] ) {
1823 $keys["mediawiki:limiter:$action:ip-all:$ip"] = $limits['ip-all'];
1827 // subnet-based limits for all ping-limitable users
1828 if ( isset( $limits['subnet-all'] ) ) {
1829 $ip = $this->getRequest()->getIP();
1830 $subnet = IP
::getSubnet( $ip );
1831 if ( $subnet !== false ) {
1832 // ignore if user limit is more permissive
1833 if ( $isNewbie ||
$userLimit === false
1834 ||
$limits['ip-all'][0] / $limits['ip-all'][1]
1835 > $userLimit[0] / $userLimit[1] ) {
1836 $keys["mediawiki:limiter:$action:subnet-all:$subnet"] = $limits['subnet-all'];
1841 $cache = ObjectCache
::getLocalClusterInstance();
1844 foreach ( $keys as $key => $limit ) {
1845 list( $max, $period ) = $limit;
1846 $summary = "(limit $max in {$period}s)";
1847 $count = $cache->get( $key );
1850 if ( $count >= $max ) {
1851 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1852 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1855 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1858 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1859 if ( $incrBy > 0 ) {
1860 $cache->add( $key, 0, intval( $period ) ); // first ping
1863 if ( $incrBy > 0 ) {
1864 $cache->incr( $key, $incrBy );
1872 * Check if user is blocked
1874 * @param bool $bFromSlave Whether to check the slave database instead of
1875 * the master. Hacked from false due to horrible probs on site.
1876 * @return bool True if blocked, false otherwise
1878 public function isBlocked( $bFromSlave = true ) {
1879 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
1883 * Get the block affecting the user, or null if the user is not blocked
1885 * @param bool $bFromSlave Whether to check the slave database instead of the master
1886 * @return Block|null
1888 public function getBlock( $bFromSlave = true ) {
1889 $this->getBlockedStatus( $bFromSlave );
1890 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
1894 * Check if user is blocked from editing a particular article
1896 * @param Title $title Title to check
1897 * @param bool $bFromSlave Whether to check the slave database instead of the master
1900 public function isBlockedFrom( $title, $bFromSlave = false ) {
1901 global $wgBlockAllowsUTEdit;
1903 $blocked = $this->isBlocked( $bFromSlave );
1904 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
1905 // If a user's name is suppressed, they cannot make edits anywhere
1906 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName()
1907 && $title->getNamespace() == NS_USER_TALK
) {
1909 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
1912 Hooks
::run( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1918 * If user is blocked, return the name of the user who placed the block
1919 * @return string Name of blocker
1921 public function blockedBy() {
1922 $this->getBlockedStatus();
1923 return $this->mBlockedby
;
1927 * If user is blocked, return the specified reason for the block
1928 * @return string Blocking reason
1930 public function blockedFor() {
1931 $this->getBlockedStatus();
1932 return $this->mBlockreason
;
1936 * If user is blocked, return the ID for the block
1937 * @return int Block ID
1939 public function getBlockId() {
1940 $this->getBlockedStatus();
1941 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
1945 * Check if user is blocked on all wikis.
1946 * Do not use for actual edit permission checks!
1947 * This is intended for quick UI checks.
1949 * @param string $ip IP address, uses current client if none given
1950 * @return bool True if blocked, false otherwise
1952 public function isBlockedGlobally( $ip = '' ) {
1953 if ( $this->mBlockedGlobally
!== null ) {
1954 return $this->mBlockedGlobally
;
1956 // User is already an IP?
1957 if ( IP
::isIPAddress( $this->getName() ) ) {
1958 $ip = $this->getName();
1960 $ip = $this->getRequest()->getIP();
1963 Hooks
::run( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1964 $this->mBlockedGlobally
= (bool)$blocked;
1965 return $this->mBlockedGlobally
;
1969 * Check if user account is locked
1971 * @return bool True if locked, false otherwise
1973 public function isLocked() {
1974 if ( $this->mLocked
!== null ) {
1975 return $this->mLocked
;
1978 $authUser = $wgAuth->getUserInstance( $this );
1979 $this->mLocked
= (bool)$authUser->isLocked();
1980 Hooks
::run( 'UserIsLocked', array( $this, &$this->mLocked
) );
1981 return $this->mLocked
;
1985 * Check if user account is hidden
1987 * @return bool True if hidden, false otherwise
1989 public function isHidden() {
1990 if ( $this->mHideName
!== null ) {
1991 return $this->mHideName
;
1993 $this->getBlockedStatus();
1994 if ( !$this->mHideName
) {
1996 $authUser = $wgAuth->getUserInstance( $this );
1997 $this->mHideName
= (bool)$authUser->isHidden();
1998 Hooks
::run( 'UserIsHidden', array( $this, &$this->mHideName
) );
2000 return $this->mHideName
;
2004 * Get the user's ID.
2005 * @return int The user's ID; 0 if the user is anonymous or nonexistent
2007 public function getId() {
2008 if ( $this->mId
=== null && $this->mName
!== null && User
::isIP( $this->mName
) ) {
2009 // Special case, we know the user is anonymous
2011 } elseif ( !$this->isItemLoaded( 'id' ) ) {
2012 // Don't load if this was initialized from an ID
2019 * Set the user and reload all fields according to a given ID
2020 * @param int $v User ID to reload
2022 public function setId( $v ) {
2024 $this->clearInstanceCache( 'id' );
2028 * Get the user name, or the IP of an anonymous user
2029 * @return string User's name or IP address
2031 public function getName() {
2032 if ( $this->isItemLoaded( 'name', 'only' ) ) {
2033 // Special case optimisation
2034 return $this->mName
;
2037 if ( $this->mName
=== false ) {
2039 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
2041 return $this->mName
;
2046 * Set the user name.
2048 * This does not reload fields from the database according to the given
2049 * name. Rather, it is used to create a temporary "nonexistent user" for
2050 * later addition to the database. It can also be used to set the IP
2051 * address for an anonymous user to something other than the current
2054 * @note User::newFromName() has roughly the same function, when the named user
2056 * @param string $str New user name to set
2058 public function setName( $str ) {
2060 $this->mName
= $str;
2064 * Get the user's name escaped by underscores.
2065 * @return string Username escaped by underscores.
2067 public function getTitleKey() {
2068 return str_replace( ' ', '_', $this->getName() );
2072 * Check if the user has new messages.
2073 * @return bool True if the user has new messages
2075 public function getNewtalk() {
2078 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2079 if ( $this->mNewtalk
=== -1 ) {
2080 $this->mNewtalk
= false; # reset talk page status
2082 // Check memcached separately for anons, who have no
2083 // entire User object stored in there.
2084 if ( !$this->mId
) {
2085 global $wgDisableAnonTalk;
2086 if ( $wgDisableAnonTalk ) {
2087 // Anon newtalk disabled by configuration.
2088 $this->mNewtalk
= false;
2090 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
2093 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2097 return (bool)$this->mNewtalk
;
2101 * Return the data needed to construct links for new talk page message
2102 * alerts. If there are new messages, this will return an associative array
2103 * with the following data:
2104 * wiki: The database name of the wiki
2105 * link: Root-relative link to the user's talk page
2106 * rev: The last talk page revision that the user has seen or null. This
2107 * is useful for building diff links.
2108 * If there are no new messages, it returns an empty array.
2109 * @note This function was designed to accomodate multiple talk pages, but
2110 * currently only returns a single link and revision.
2113 public function getNewMessageLinks() {
2115 if ( !Hooks
::run( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) ) {
2117 } elseif ( !$this->getNewtalk() ) {
2120 $utp = $this->getTalkPage();
2121 $dbr = wfGetDB( DB_SLAVE
);
2122 // Get the "last viewed rev" timestamp from the oldest message notification
2123 $timestamp = $dbr->selectField( 'user_newtalk',
2124 'MIN(user_last_timestamp)',
2125 $this->isAnon() ?
array( 'user_ip' => $this->getName() ) : array( 'user_id' => $this->getID() ),
2127 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2128 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ) );
2132 * Get the revision ID for the last talk page revision viewed by the talk
2134 * @return int|null Revision ID or null
2136 public function getNewMessageRevisionId() {
2137 $newMessageRevisionId = null;
2138 $newMessageLinks = $this->getNewMessageLinks();
2139 if ( $newMessageLinks ) {
2140 // Note: getNewMessageLinks() never returns more than a single link
2141 // and it is always for the same wiki, but we double-check here in
2142 // case that changes some time in the future.
2143 if ( count( $newMessageLinks ) === 1
2144 && $newMessageLinks[0]['wiki'] === wfWikiID()
2145 && $newMessageLinks[0]['rev']
2147 /** @var Revision $newMessageRevision */
2148 $newMessageRevision = $newMessageLinks[0]['rev'];
2149 $newMessageRevisionId = $newMessageRevision->getId();
2152 return $newMessageRevisionId;
2156 * Internal uncached check for new messages
2159 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2160 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2161 * @return bool True if the user has new messages
2163 protected function checkNewtalk( $field, $id ) {
2164 $dbr = wfGetDB( DB_SLAVE
);
2166 $ok = $dbr->selectField( 'user_newtalk', $field, array( $field => $id ), __METHOD__
);
2168 return $ok !== false;
2172 * Add or update the new messages flag
2173 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2174 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2175 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2176 * @return bool True if successful, false otherwise
2178 protected function updateNewtalk( $field, $id, $curRev = null ) {
2179 // Get timestamp of the talk page revision prior to the current one
2180 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2181 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2182 // Mark the user as having new messages since this revision
2183 $dbw = wfGetDB( DB_MASTER
);
2184 $dbw->insert( 'user_newtalk',
2185 array( $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ),
2188 if ( $dbw->affectedRows() ) {
2189 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2192 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2198 * Clear the new messages flag for the given user
2199 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2200 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2201 * @return bool True if successful, false otherwise
2203 protected function deleteNewtalk( $field, $id ) {
2204 $dbw = wfGetDB( DB_MASTER
);
2205 $dbw->delete( 'user_newtalk',
2206 array( $field => $id ),
2208 if ( $dbw->affectedRows() ) {
2209 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2212 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2218 * Update the 'You have new messages!' status.
2219 * @param bool $val Whether the user has new messages
2220 * @param Revision $curRev New, as yet unseen revision of the user talk
2221 * page. Ignored if null or !$val.
2223 public function setNewtalk( $val, $curRev = null ) {
2224 if ( wfReadOnly() ) {
2229 $this->mNewtalk
= $val;
2231 if ( $this->isAnon() ) {
2233 $id = $this->getName();
2236 $id = $this->getId();
2240 $changed = $this->updateNewtalk( $field, $id, $curRev );
2242 $changed = $this->deleteNewtalk( $field, $id );
2246 $this->invalidateCache();
2251 * Generate a current or new-future timestamp to be stored in the
2252 * user_touched field when we update things.
2253 * @return string Timestamp in TS_MW format
2255 private function newTouchedTimestamp() {
2256 global $wgClockSkewFudge;
2258 $time = wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2259 if ( $this->mTouched
&& $time <= $this->mTouched
) {
2260 $time = wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $this->mTouched
) +
1 );
2267 * Clear user data from memcached
2269 * Use after applying updates to the database; caller's
2270 * responsibility to update user_touched if appropriate.
2272 * Called implicitly from invalidateCache() and saveSettings().
2274 * @param string $mode Use 'refresh' to clear now; otherwise before DB commit
2276 public function clearSharedCache( $mode = 'changed' ) {
2277 if ( !$this->getId() ) {
2281 $cache = ObjectCache
::getMainWANInstance();
2282 $key = $this->getCacheKey( $cache );
2283 if ( $mode === 'refresh' ) {
2284 $cache->delete( $key, 1 );
2286 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle( function() use ( $cache, $key ) {
2287 $cache->delete( $key );
2293 * Immediately touch the user data cache for this account
2295 * Calls touch() and removes account data from memcached
2297 public function invalidateCache() {
2299 $this->clearSharedCache();
2303 * Update the "touched" timestamp for the user
2305 * This is useful on various login/logout events when making sure that
2306 * a browser or proxy that has multiple tenants does not suffer cache
2307 * pollution where the new user sees the old users content. The value
2308 * of getTouched() is checked when determining 304 vs 200 responses.
2309 * Unlike invalidateCache(), this preserves the User object cache and
2310 * avoids database writes.
2314 public function touch() {
2315 $id = $this->getId();
2317 $key = wfMemcKey( 'user-quicktouched', 'id', $id );
2318 ObjectCache
::getMainWANInstance()->touchCheckKey( $key );
2319 $this->mQuickTouched
= null;
2324 * Validate the cache for this account.
2325 * @param string $timestamp A timestamp in TS_MW format
2328 public function validateCache( $timestamp ) {
2329 return ( $timestamp >= $this->getTouched() );
2333 * Get the user touched timestamp
2335 * Use this value only to validate caches via inequalities
2336 * such as in the case of HTTP If-Modified-Since response logic
2338 * @return string TS_MW Timestamp
2340 public function getTouched() {
2344 if ( $this->mQuickTouched
=== null ) {
2345 $key = wfMemcKey( 'user-quicktouched', 'id', $this->mId
);
2346 $cache = ObjectCache
::getMainWANInstance();
2348 $this->mQuickTouched
= wfTimestamp( TS_MW
, $cache->getCheckKeyTime( $key ) );
2351 return max( $this->mTouched
, $this->mQuickTouched
);
2354 return $this->mTouched
;
2358 * Get the user_touched timestamp field (time of last DB updates)
2359 * @return string TS_MW Timestamp
2362 public function getDBTouched() {
2365 return $this->mTouched
;
2369 * @deprecated Removed in 1.27.
2373 public function getPassword() {
2374 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2378 * @deprecated Removed in 1.27.
2382 public function getTemporaryPassword() {
2383 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2387 * Set the password and reset the random token.
2388 * Calls through to authentication plugin if necessary;
2389 * will have no effect if the auth plugin refuses to
2390 * pass the change through or if the legal password
2393 * As a special case, setting the password to null
2394 * wipes it, so the account cannot be logged in until
2395 * a new password is set, for instance via e-mail.
2397 * @deprecated since 1.27. AuthManager is coming.
2398 * @param string $str New password to set
2399 * @throws PasswordError On failure
2402 public function setPassword( $str ) {
2405 if ( $str !== null ) {
2406 if ( !$wgAuth->allowPasswordChange() ) {
2407 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2410 $status = $this->checkPasswordValidity( $str );
2411 if ( !$status->isGood() ) {
2412 throw new PasswordError( $status->getMessage()->text() );
2416 if ( !$wgAuth->setPassword( $this, $str ) ) {
2417 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2421 $this->setOption( 'watchlisttoken', false );
2422 $this->setPasswordInternal( $str );
2428 * Set the password and reset the random token unconditionally.
2430 * @deprecated since 1.27. AuthManager is coming.
2431 * @param string|null $str New password to set or null to set an invalid
2432 * password hash meaning that the user will not be able to log in
2433 * through the web interface.
2435 public function setInternalPassword( $str ) {
2438 if ( $wgAuth->allowSetLocalPassword() ) {
2440 $this->setOption( 'watchlisttoken', false );
2441 $this->setPasswordInternal( $str );
2446 * Actually set the password and such
2447 * @since 1.27 cannot set a password for a user not in the database
2448 * @param string|null $str New password to set or null to set an invalid
2449 * password hash meaning that the user will not be able to log in
2450 * through the web interface.
2452 private function setPasswordInternal( $str ) {
2453 $id = self
::idFromName( $this->getName(), self
::READ_LATEST
);
2455 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2458 $passwordFactory = new PasswordFactory();
2459 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
2460 $dbw = wfGetDB( DB_MASTER
);
2464 'user_password' => $passwordFactory->newFromPlaintext( $str )->toString(),
2465 'user_newpassword' => PasswordFactory
::newInvalidPassword()->toString(),
2466 'user_newpass_time' => $dbw->timestampOrNull( null ),
2474 // When the main password is changed, invalidate all bot passwords too
2475 BotPassword
::invalidateAllPasswordsForUser( $this->getName() );
2479 * Get the user's current token.
2480 * @param bool $forceCreation Force the generation of a new token if the
2481 * user doesn't have one (default=true for backwards compatibility).
2482 * @return string|null Token
2484 public function getToken( $forceCreation = true ) {
2485 global $wgAuthenticationTokenVersion;
2488 if ( !$this->mToken
&& $forceCreation ) {
2492 // If the user doesn't have a token, return null to indicate that.
2493 // Otherwise, hmac the version with the secret if we have a version.
2494 if ( !$this->mToken
) {
2496 } elseif ( $wgAuthenticationTokenVersion === null ) {
2497 return $this->mToken
;
2499 $ret = MWCryptHash
::hmac( $wgAuthenticationTokenVersion, $this->mToken
, false );
2501 // The raw hash can be overly long. Shorten it up.
2502 $len = max( 32, self
::TOKEN_LENGTH
);
2503 if ( strlen( $ret ) < $len ) {
2504 // Should never happen, even md5 is 128 bits
2505 throw new \
UnexpectedValueException( 'Hmac returned less than 128 bits' );
2507 return substr( $ret, -$len );
2512 * Set the random token (used for persistent authentication)
2513 * Called from loadDefaults() among other places.
2515 * @param string|bool $token If specified, set the token to this value
2517 public function setToken( $token = false ) {
2520 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2522 $this->mToken
= $token;
2527 * Set the password for a password reminder or new account email
2529 * @deprecated since 1.27, AuthManager is coming
2530 * @param string $str New password to set or null to set an invalid
2531 * password hash meaning that the user will not be able to use it
2532 * @param bool $throttle If true, reset the throttle timestamp to the present
2534 public function setNewpassword( $str, $throttle = true ) {
2535 $id = $this->getId();
2537 throw new LogicException( 'Cannot set new password for a user that is not in the database.' );
2540 $dbw = wfGetDB( DB_MASTER
);
2542 $passwordFactory = new PasswordFactory();
2543 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
2545 'user_newpassword' => $passwordFactory->newFromPlaintext( $str )->toString(),
2548 if ( $str === null ) {
2549 $update['user_newpass_time'] = null;
2550 } elseif ( $throttle ) {
2551 $update['user_newpass_time'] = $dbw->timestamp();
2554 $dbw->update( 'user', $update, array( 'user_id' => $id ), __METHOD__
);
2558 * Has password reminder email been sent within the last
2559 * $wgPasswordReminderResendTime hours?
2562 public function isPasswordReminderThrottled() {
2563 global $wgPasswordReminderResendTime;
2565 if ( !$wgPasswordReminderResendTime ) {
2571 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
2572 ?
wfGetDB( DB_MASTER
)
2573 : wfGetDB( DB_SLAVE
);
2574 $newpassTime = $db->selectField(
2576 'user_newpass_time',
2577 array( 'user_id' => $this->getId() ),
2581 if ( $newpassTime === null ) {
2584 $expiry = wfTimestamp( TS_UNIX
, $newpassTime ) +
$wgPasswordReminderResendTime * 3600;
2585 return time() < $expiry;
2589 * Get the user's e-mail address
2590 * @return string User's email address
2592 public function getEmail() {
2594 Hooks
::run( 'UserGetEmail', array( $this, &$this->mEmail
) );
2595 return $this->mEmail
;
2599 * Get the timestamp of the user's e-mail authentication
2600 * @return string TS_MW timestamp
2602 public function getEmailAuthenticationTimestamp() {
2604 Hooks
::run( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
2605 return $this->mEmailAuthenticated
;
2609 * Set the user's e-mail address
2610 * @param string $str New e-mail address
2612 public function setEmail( $str ) {
2614 if ( $str == $this->mEmail
) {
2617 $this->invalidateEmail();
2618 $this->mEmail
= $str;
2619 Hooks
::run( 'UserSetEmail', array( $this, &$this->mEmail
) );
2623 * Set the user's e-mail address and a confirmation mail if needed.
2626 * @param string $str New e-mail address
2629 public function setEmailWithConfirmation( $str ) {
2630 global $wgEnableEmail, $wgEmailAuthentication;
2632 if ( !$wgEnableEmail ) {
2633 return Status
::newFatal( 'emaildisabled' );
2636 $oldaddr = $this->getEmail();
2637 if ( $str === $oldaddr ) {
2638 return Status
::newGood( true );
2641 $this->setEmail( $str );
2643 if ( $str !== '' && $wgEmailAuthentication ) {
2644 // Send a confirmation request to the new address if needed
2645 $type = $oldaddr != '' ?
'changed' : 'set';
2646 $result = $this->sendConfirmationMail( $type );
2647 if ( $result->isGood() ) {
2648 // Say to the caller that a confirmation mail has been sent
2649 $result->value
= 'eauth';
2652 $result = Status
::newGood( true );
2659 * Get the user's real name
2660 * @return string User's real name
2662 public function getRealName() {
2663 if ( !$this->isItemLoaded( 'realname' ) ) {
2667 return $this->mRealName
;
2671 * Set the user's real name
2672 * @param string $str New real name
2674 public function setRealName( $str ) {
2676 $this->mRealName
= $str;
2680 * Get the user's current setting for a given option.
2682 * @param string $oname The option to check
2683 * @param string $defaultOverride A default value returned if the option does not exist
2684 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2685 * @return string User's current value for the option
2686 * @see getBoolOption()
2687 * @see getIntOption()
2689 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2690 global $wgHiddenPrefs;
2691 $this->loadOptions();
2693 # We want 'disabled' preferences to always behave as the default value for
2694 # users, even if they have set the option explicitly in their settings (ie they
2695 # set it, and then it was disabled removing their ability to change it). But
2696 # we don't want to erase the preferences in the database in case the preference
2697 # is re-enabled again. So don't touch $mOptions, just override the returned value
2698 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2699 return self
::getDefaultOption( $oname );
2702 if ( array_key_exists( $oname, $this->mOptions
) ) {
2703 return $this->mOptions
[$oname];
2705 return $defaultOverride;
2710 * Get all user's options
2712 * @param int $flags Bitwise combination of:
2713 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2714 * to the default value. (Since 1.25)
2717 public function getOptions( $flags = 0 ) {
2718 global $wgHiddenPrefs;
2719 $this->loadOptions();
2720 $options = $this->mOptions
;
2722 # We want 'disabled' preferences to always behave as the default value for
2723 # users, even if they have set the option explicitly in their settings (ie they
2724 # set it, and then it was disabled removing their ability to change it). But
2725 # we don't want to erase the preferences in the database in case the preference
2726 # is re-enabled again. So don't touch $mOptions, just override the returned value
2727 foreach ( $wgHiddenPrefs as $pref ) {
2728 $default = self
::getDefaultOption( $pref );
2729 if ( $default !== null ) {
2730 $options[$pref] = $default;
2734 if ( $flags & self
::GETOPTIONS_EXCLUDE_DEFAULTS
) {
2735 $options = array_diff_assoc( $options, self
::getDefaultOptions() );
2742 * Get the user's current setting for a given option, as a boolean value.
2744 * @param string $oname The option to check
2745 * @return bool User's current value for the option
2748 public function getBoolOption( $oname ) {
2749 return (bool)$this->getOption( $oname );
2753 * Get the user's current setting for a given option, as an integer value.
2755 * @param string $oname The option to check
2756 * @param int $defaultOverride A default value returned if the option does not exist
2757 * @return int User's current value for the option
2760 public function getIntOption( $oname, $defaultOverride = 0 ) {
2761 $val = $this->getOption( $oname );
2763 $val = $defaultOverride;
2765 return intval( $val );
2769 * Set the given option for a user.
2771 * You need to call saveSettings() to actually write to the database.
2773 * @param string $oname The option to set
2774 * @param mixed $val New value to set
2776 public function setOption( $oname, $val ) {
2777 $this->loadOptions();
2779 // Explicitly NULL values should refer to defaults
2780 if ( is_null( $val ) ) {
2781 $val = self
::getDefaultOption( $oname );
2784 $this->mOptions
[$oname] = $val;
2788 * Get a token stored in the preferences (like the watchlist one),
2789 * resetting it if it's empty (and saving changes).
2791 * @param string $oname The option name to retrieve the token from
2792 * @return string|bool User's current value for the option, or false if this option is disabled.
2793 * @see resetTokenFromOption()
2795 * @deprecated 1.26 Applications should use the OAuth extension
2797 public function getTokenFromOption( $oname ) {
2798 global $wgHiddenPrefs;
2800 $id = $this->getId();
2801 if ( !$id ||
in_array( $oname, $wgHiddenPrefs ) ) {
2805 $token = $this->getOption( $oname );
2807 // Default to a value based on the user token to avoid space
2808 // wasted on storing tokens for all users. When this option
2809 // is set manually by the user, only then is it stored.
2810 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
2817 * Reset a token stored in the preferences (like the watchlist one).
2818 * *Does not* save user's preferences (similarly to setOption()).
2820 * @param string $oname The option name to reset the token in
2821 * @return string|bool New token value, or false if this option is disabled.
2822 * @see getTokenFromOption()
2825 public function resetTokenFromOption( $oname ) {
2826 global $wgHiddenPrefs;
2827 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2831 $token = MWCryptRand
::generateHex( 40 );
2832 $this->setOption( $oname, $token );
2837 * Return a list of the types of user options currently returned by
2838 * User::getOptionKinds().
2840 * Currently, the option kinds are:
2841 * - 'registered' - preferences which are registered in core MediaWiki or
2842 * by extensions using the UserGetDefaultOptions hook.
2843 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2844 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2845 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2846 * be used by user scripts.
2847 * - 'special' - "preferences" that are not accessible via User::getOptions
2848 * or User::setOptions.
2849 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2850 * These are usually legacy options, removed in newer versions.
2852 * The API (and possibly others) use this function to determine the possible
2853 * option types for validation purposes, so make sure to update this when a
2854 * new option kind is added.
2856 * @see User::getOptionKinds
2857 * @return array Option kinds
2859 public static function listOptionKinds() {
2862 'registered-multiselect',
2863 'registered-checkmatrix',
2871 * Return an associative array mapping preferences keys to the kind of a preference they're
2872 * used for. Different kinds are handled differently when setting or reading preferences.
2874 * See User::listOptionKinds for the list of valid option types that can be provided.
2876 * @see User::listOptionKinds
2877 * @param IContextSource $context
2878 * @param array $options Assoc. array with options keys to check as keys.
2879 * Defaults to $this->mOptions.
2880 * @return array The key => kind mapping data
2882 public function getOptionKinds( IContextSource
$context, $options = null ) {
2883 $this->loadOptions();
2884 if ( $options === null ) {
2885 $options = $this->mOptions
;
2888 $prefs = Preferences
::getPreferences( $this, $context );
2891 // Pull out the "special" options, so they don't get converted as
2892 // multiselect or checkmatrix.
2893 $specialOptions = array_fill_keys( Preferences
::getSaveBlacklist(), true );
2894 foreach ( $specialOptions as $name => $value ) {
2895 unset( $prefs[$name] );
2898 // Multiselect and checkmatrix options are stored in the database with
2899 // one key per option, each having a boolean value. Extract those keys.
2900 $multiselectOptions = array();
2901 foreach ( $prefs as $name => $info ) {
2902 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2903 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2904 $opts = HTMLFormField
::flattenOptions( $info['options'] );
2905 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2907 foreach ( $opts as $value ) {
2908 $multiselectOptions["$prefix$value"] = true;
2911 unset( $prefs[$name] );
2914 $checkmatrixOptions = array();
2915 foreach ( $prefs as $name => $info ) {
2916 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2917 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2918 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
2919 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
2920 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2922 foreach ( $columns as $column ) {
2923 foreach ( $rows as $row ) {
2924 $checkmatrixOptions["$prefix$column-$row"] = true;
2928 unset( $prefs[$name] );
2932 // $value is ignored
2933 foreach ( $options as $key => $value ) {
2934 if ( isset( $prefs[$key] ) ) {
2935 $mapping[$key] = 'registered';
2936 } elseif ( isset( $multiselectOptions[$key] ) ) {
2937 $mapping[$key] = 'registered-multiselect';
2938 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2939 $mapping[$key] = 'registered-checkmatrix';
2940 } elseif ( isset( $specialOptions[$key] ) ) {
2941 $mapping[$key] = 'special';
2942 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2943 $mapping[$key] = 'userjs';
2945 $mapping[$key] = 'unused';
2953 * Reset certain (or all) options to the site defaults
2955 * The optional parameter determines which kinds of preferences will be reset.
2956 * Supported values are everything that can be reported by getOptionKinds()
2957 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2959 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
2960 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2961 * for backwards-compatibility.
2962 * @param IContextSource|null $context Context source used when $resetKinds
2963 * does not contain 'all', passed to getOptionKinds().
2964 * Defaults to RequestContext::getMain() when null.
2966 public function resetOptions(
2967 $resetKinds = array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ),
2968 IContextSource
$context = null
2971 $defaultOptions = self
::getDefaultOptions();
2973 if ( !is_array( $resetKinds ) ) {
2974 $resetKinds = array( $resetKinds );
2977 if ( in_array( 'all', $resetKinds ) ) {
2978 $newOptions = $defaultOptions;
2980 if ( $context === null ) {
2981 $context = RequestContext
::getMain();
2984 $optionKinds = $this->getOptionKinds( $context );
2985 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
2986 $newOptions = array();
2988 // Use default values for the options that should be deleted, and
2989 // copy old values for the ones that shouldn't.
2990 foreach ( $this->mOptions
as $key => $value ) {
2991 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
2992 if ( array_key_exists( $key, $defaultOptions ) ) {
2993 $newOptions[$key] = $defaultOptions[$key];
2996 $newOptions[$key] = $value;
3001 Hooks
::run( 'UserResetAllOptions', array( $this, &$newOptions, $this->mOptions
, $resetKinds ) );
3003 $this->mOptions
= $newOptions;
3004 $this->mOptionsLoaded
= true;
3008 * Get the user's preferred date format.
3009 * @return string User's preferred date format
3011 public function getDatePreference() {
3012 // Important migration for old data rows
3013 if ( is_null( $this->mDatePreference
) ) {
3015 $value = $this->getOption( 'date' );
3016 $map = $wgLang->getDatePreferenceMigrationMap();
3017 if ( isset( $map[$value] ) ) {
3018 $value = $map[$value];
3020 $this->mDatePreference
= $value;
3022 return $this->mDatePreference
;
3026 * Determine based on the wiki configuration and the user's options,
3027 * whether this user must be over HTTPS no matter what.
3031 public function requiresHTTPS() {
3032 global $wgSecureLogin;
3033 if ( !$wgSecureLogin ) {
3036 $https = $this->getBoolOption( 'prefershttps' );
3037 Hooks
::run( 'UserRequiresHTTPS', array( $this, &$https ) );
3039 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
3046 * Get the user preferred stub threshold
3050 public function getStubThreshold() {
3051 global $wgMaxArticleSize; # Maximum article size, in Kb
3052 $threshold = $this->getIntOption( 'stubthreshold' );
3053 if ( $threshold > $wgMaxArticleSize * 1024 ) {
3054 // If they have set an impossible value, disable the preference
3055 // so we can use the parser cache again.
3062 * Get the permissions this user has.
3063 * @return array Array of String permission names
3065 public function getRights() {
3066 if ( is_null( $this->mRights
) ) {
3067 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
3069 $allowedRights = $this->getRequest()->getSession()->getAllowedUserRights();
3070 if ( $allowedRights !== null ) {
3071 $this->mRights
= array_intersect( $this->mRights
, $allowedRights );
3074 Hooks
::run( 'UserGetRights', array( $this, &$this->mRights
) );
3075 // Force reindexation of rights when a hook has unset one of them
3076 $this->mRights
= array_values( array_unique( $this->mRights
) );
3078 return $this->mRights
;
3082 * Get the list of explicit group memberships this user has.
3083 * The implicit * and user groups are not included.
3084 * @return array Array of String internal group names
3086 public function getGroups() {
3088 $this->loadGroups();
3089 return $this->mGroups
;
3093 * Get the list of implicit group memberships this user has.
3094 * This includes all explicit groups, plus 'user' if logged in,
3095 * '*' for all accounts, and autopromoted groups
3096 * @param bool $recache Whether to avoid the cache
3097 * @return array Array of String internal group names
3099 public function getEffectiveGroups( $recache = false ) {
3100 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
3101 $this->mEffectiveGroups
= array_unique( array_merge(
3102 $this->getGroups(), // explicit groups
3103 $this->getAutomaticGroups( $recache ) // implicit groups
3105 // Hook for additional groups
3106 Hooks
::run( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
3107 // Force reindexation of groups when a hook has unset one of them
3108 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
3110 return $this->mEffectiveGroups
;
3114 * Get the list of implicit group memberships this user has.
3115 * This includes 'user' if logged in, '*' for all accounts,
3116 * and autopromoted groups
3117 * @param bool $recache Whether to avoid the cache
3118 * @return array Array of String internal group names
3120 public function getAutomaticGroups( $recache = false ) {
3121 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
3122 $this->mImplicitGroups
= array( '*' );
3123 if ( $this->getId() ) {
3124 $this->mImplicitGroups
[] = 'user';
3126 $this->mImplicitGroups
= array_unique( array_merge(
3127 $this->mImplicitGroups
,
3128 Autopromote
::getAutopromoteGroups( $this )
3132 // Assure data consistency with rights/groups,
3133 // as getEffectiveGroups() depends on this function
3134 $this->mEffectiveGroups
= null;
3137 return $this->mImplicitGroups
;
3141 * Returns the groups the user has belonged to.
3143 * The user may still belong to the returned groups. Compare with getGroups().
3145 * The function will not return groups the user had belonged to before MW 1.17
3147 * @return array Names of the groups the user has belonged to.
3149 public function getFormerGroups() {
3152 if ( is_null( $this->mFormerGroups
) ) {
3153 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3154 ?
wfGetDB( DB_MASTER
)
3155 : wfGetDB( DB_SLAVE
);
3156 $res = $db->select( 'user_former_groups',
3157 array( 'ufg_group' ),
3158 array( 'ufg_user' => $this->mId
),
3160 $this->mFormerGroups
= array();
3161 foreach ( $res as $row ) {
3162 $this->mFormerGroups
[] = $row->ufg_group
;
3166 return $this->mFormerGroups
;
3170 * Get the user's edit count.
3171 * @return int|null Null for anonymous users
3173 public function getEditCount() {
3174 if ( !$this->getId() ) {
3178 if ( $this->mEditCount
=== null ) {
3179 /* Populate the count, if it has not been populated yet */
3180 $dbr = wfGetDB( DB_SLAVE
);
3181 // check if the user_editcount field has been initialized
3182 $count = $dbr->selectField(
3183 'user', 'user_editcount',
3184 array( 'user_id' => $this->mId
),
3188 if ( $count === null ) {
3189 // it has not been initialized. do so.
3190 $count = $this->initEditCount();
3192 $this->mEditCount
= $count;
3194 return (int)$this->mEditCount
;
3198 * Add the user to the given group.
3199 * This takes immediate effect.
3200 * @param string $group Name of the group to add
3203 public function addGroup( $group ) {
3206 if ( !Hooks
::run( 'UserAddGroup', array( $this, &$group ) ) ) {
3210 $dbw = wfGetDB( DB_MASTER
);
3211 if ( $this->getId() ) {
3212 $dbw->insert( 'user_groups',
3214 'ug_user' => $this->getID(),
3215 'ug_group' => $group,
3218 array( 'IGNORE' ) );
3221 $this->loadGroups();
3222 $this->mGroups
[] = $group;
3223 // In case loadGroups was not called before, we now have the right twice.
3224 // Get rid of the duplicate.
3225 $this->mGroups
= array_unique( $this->mGroups
);
3227 // Refresh the groups caches, and clear the rights cache so it will be
3228 // refreshed on the next call to $this->getRights().
3229 $this->getEffectiveGroups( true );
3230 $this->mRights
= null;
3232 $this->invalidateCache();
3238 * Remove the user from the given group.
3239 * This takes immediate effect.
3240 * @param string $group Name of the group to remove
3243 public function removeGroup( $group ) {
3245 if ( !Hooks
::run( 'UserRemoveGroup', array( $this, &$group ) ) ) {
3249 $dbw = wfGetDB( DB_MASTER
);
3250 $dbw->delete( 'user_groups',
3252 'ug_user' => $this->getID(),
3253 'ug_group' => $group,
3256 // Remember that the user was in this group
3257 $dbw->insert( 'user_former_groups',
3259 'ufg_user' => $this->getID(),
3260 'ufg_group' => $group,
3266 $this->loadGroups();
3267 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
3269 // Refresh the groups caches, and clear the rights cache so it will be
3270 // refreshed on the next call to $this->getRights().
3271 $this->getEffectiveGroups( true );
3272 $this->mRights
= null;
3274 $this->invalidateCache();
3280 * Get whether the user is logged in
3283 public function isLoggedIn() {
3284 return $this->getID() != 0;
3288 * Get whether the user is anonymous
3291 public function isAnon() {
3292 return !$this->isLoggedIn();
3296 * Check if user is allowed to access a feature / make an action
3298 * @param string ... Permissions to test
3299 * @return bool True if user is allowed to perform *any* of the given actions
3301 public function isAllowedAny() {
3302 $permissions = func_get_args();
3303 foreach ( $permissions as $permission ) {
3304 if ( $this->isAllowed( $permission ) ) {
3313 * @param string ... Permissions to test
3314 * @return bool True if the user is allowed to perform *all* of the given actions
3316 public function isAllowedAll() {
3317 $permissions = func_get_args();
3318 foreach ( $permissions as $permission ) {
3319 if ( !$this->isAllowed( $permission ) ) {
3327 * Internal mechanics of testing a permission
3328 * @param string $action
3331 public function isAllowed( $action = '' ) {
3332 if ( $action === '' ) {
3333 return true; // In the spirit of DWIM
3335 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3336 // by misconfiguration: 0 == 'foo'
3337 return in_array( $action, $this->getRights(), true );
3341 * Check whether to enable recent changes patrol features for this user
3342 * @return bool True or false
3344 public function useRCPatrol() {
3345 global $wgUseRCPatrol;
3346 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3350 * Check whether to enable new pages patrol features for this user
3351 * @return bool True or false
3353 public function useNPPatrol() {
3354 global $wgUseRCPatrol, $wgUseNPPatrol;
3356 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3357 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3362 * Check whether to enable new files patrol features for this user
3363 * @return bool True or false
3365 public function useFilePatrol() {
3366 global $wgUseRCPatrol, $wgUseFilePatrol;
3368 ( $wgUseRCPatrol ||
$wgUseFilePatrol )
3369 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3374 * Get the WebRequest object to use with this object
3376 * @return WebRequest
3378 public function getRequest() {
3379 if ( $this->mRequest
) {
3380 return $this->mRequest
;
3388 * Get a WatchedItem for this user and $title.
3390 * @since 1.22 $checkRights parameter added
3391 * @param Title $title
3392 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3393 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3394 * @return WatchedItem
3396 public function getWatchedItem( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3397 $key = $checkRights . ':' . $title->getNamespace() . ':' . $title->getDBkey();
3399 if ( isset( $this->mWatchedItems
[$key] ) ) {
3400 return $this->mWatchedItems
[$key];
3403 if ( count( $this->mWatchedItems
) >= self
::MAX_WATCHED_ITEMS_CACHE
) {
3404 $this->mWatchedItems
= array();
3407 $this->mWatchedItems
[$key] = WatchedItem
::fromUserTitle( $this, $title, $checkRights );
3408 return $this->mWatchedItems
[$key];
3412 * Check the watched status of an article.
3413 * @since 1.22 $checkRights parameter added
3414 * @param Title $title Title of the article to look at
3415 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3416 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3419 public function isWatched( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3420 return $this->getWatchedItem( $title, $checkRights )->isWatched();
3425 * @since 1.22 $checkRights parameter added
3426 * @param Title $title Title of the article to look at
3427 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3428 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3430 public function addWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3431 $this->getWatchedItem( $title, $checkRights )->addWatch();
3432 $this->invalidateCache();
3436 * Stop watching an article.
3437 * @since 1.22 $checkRights parameter added
3438 * @param Title $title Title of the article to look at
3439 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3440 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3442 public function removeWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3443 $this->getWatchedItem( $title, $checkRights )->removeWatch();
3444 $this->invalidateCache();
3448 * Clear the user's notification timestamp for the given title.
3449 * If e-notif e-mails are on, they will receive notification mails on
3450 * the next change of the page if it's watched etc.
3451 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3452 * @param Title $title Title of the article to look at
3453 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3455 public function clearNotification( &$title, $oldid = 0 ) {
3456 global $wgUseEnotif, $wgShowUpdatedMarker;
3458 // Do nothing if the database is locked to writes
3459 if ( wfReadOnly() ) {
3463 // Do nothing if not allowed to edit the watchlist
3464 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3468 // If we're working on user's talk page, we should update the talk page message indicator
3469 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3470 if ( !Hooks
::run( 'UserClearNewTalkNotification', array( &$this, $oldid ) ) ) {
3475 // Try to update the DB post-send and only if needed...
3476 DeferredUpdates
::addCallableUpdate( function() use ( $that, $title, $oldid ) {
3477 if ( !$that->getNewtalk() ) {
3478 return; // no notifications to clear
3481 // Delete the last notifications (they stack up)
3482 $that->setNewtalk( false );
3484 // If there is a new, unseen, revision, use its timestamp
3486 ?
$title->getNextRevisionID( $oldid, Title
::GAID_FOR_UPDATE
)
3489 $that->setNewtalk( true, Revision
::newFromId( $nextid ) );
3494 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3498 if ( $this->isAnon() ) {
3499 // Nothing else to do...
3503 // Only update the timestamp if the page is being watched.
3504 // The query to find out if it is watched is cached both in memcached and per-invocation,
3505 // and when it does have to be executed, it can be on a slave
3506 // If this is the user's newtalk page, we always update the timestamp
3508 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3512 $this->getWatchedItem( $title )->resetNotificationTimestamp(
3518 * Resets all of the given user's page-change notification timestamps.
3519 * If e-notif e-mails are on, they will receive notification mails on
3520 * the next change of any watched page.
3521 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3523 public function clearAllNotifications() {
3524 if ( wfReadOnly() ) {
3528 // Do nothing if not allowed to edit the watchlist
3529 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3533 global $wgUseEnotif, $wgShowUpdatedMarker;
3534 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3535 $this->setNewtalk( false );
3538 $id = $this->getId();
3540 $dbw = wfGetDB( DB_MASTER
);
3541 $dbw->update( 'watchlist',
3542 array( /* SET */ 'wl_notificationtimestamp' => null ),
3543 array( /* WHERE */ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ),
3546 // We also need to clear here the "you have new message" notification for the own user_talk page;
3547 // it's cleared one page view later in WikiPage::doViewUpdates().
3552 * Set a cookie on the user's client. Wrapper for
3553 * WebResponse::setCookie
3554 * @deprecated since 1.27
3555 * @param string $name Name of the cookie to set
3556 * @param string $value Value to set
3557 * @param int $exp Expiration time, as a UNIX time value;
3558 * if 0 or not specified, use the default $wgCookieExpiration
3559 * @param bool $secure
3560 * true: Force setting the secure attribute when setting the cookie
3561 * false: Force NOT setting the secure attribute when setting the cookie
3562 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3563 * @param array $params Array of options sent passed to WebResponse::setcookie()
3564 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3567 protected function setCookie(
3568 $name, $value, $exp = 0, $secure = null, $params = array(), $request = null
3570 wfDeprecated( __METHOD__
, '1.27' );
3571 if ( $request === null ) {
3572 $request = $this->getRequest();
3574 $params['secure'] = $secure;
3575 $request->response()->setCookie( $name, $value, $exp, $params );
3579 * Clear a cookie on the user's client
3580 * @deprecated since 1.27
3581 * @param string $name Name of the cookie to clear
3582 * @param bool $secure
3583 * true: Force setting the secure attribute when setting the cookie
3584 * false: Force NOT setting the secure attribute when setting the cookie
3585 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3586 * @param array $params Array of options sent passed to WebResponse::setcookie()
3588 protected function clearCookie( $name, $secure = null, $params = array() ) {
3589 wfDeprecated( __METHOD__
, '1.27' );
3590 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3594 * Set an extended login cookie on the user's client. The expiry of the cookie
3595 * is controlled by the $wgExtendedLoginCookieExpiration configuration
3598 * @see User::setCookie
3600 * @deprecated since 1.27
3601 * @param string $name Name of the cookie to set
3602 * @param string $value Value to set
3603 * @param bool $secure
3604 * true: Force setting the secure attribute when setting the cookie
3605 * false: Force NOT setting the secure attribute when setting the cookie
3606 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3608 protected function setExtendedLoginCookie( $name, $value, $secure ) {
3609 global $wgExtendedLoginCookieExpiration, $wgCookieExpiration;
3611 wfDeprecated( __METHOD__
, '1.27' );
3614 $exp +
= $wgExtendedLoginCookieExpiration !== null
3615 ?
$wgExtendedLoginCookieExpiration
3616 : $wgCookieExpiration;
3618 $this->setCookie( $name, $value, $exp, $secure );
3622 * Persist this user's session (e.g. set cookies)
3624 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3626 * @param bool $secure Whether to force secure/insecure cookies or use default
3627 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3629 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3631 if ( 0 == $this->mId
) {
3635 $session = $this->getRequest()->getSession();
3636 if ( $request && $session->getRequest() !== $request ) {
3637 $session = $session->sessionWithRequest( $request );
3639 $delay = $session->delaySave();
3641 if ( !$session->getUser()->equals( $this ) ) {
3642 if ( !$session->canSetUser() ) {
3643 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3644 ->warning( __METHOD__
.
3645 ": Cannot save user \"$this\" to a user \"{$session->getUser()}\"'s immutable session"
3649 $session->setUser( $this );
3652 $session->setRememberUser( $rememberMe );
3653 if ( $secure !== null ) {
3654 $session->setForceHTTPS( $secure );
3657 $session->persist();
3659 ScopedCallback
::consume( $delay );
3663 * Log this user out.
3665 public function logout() {
3666 if ( Hooks
::run( 'UserLogout', array( &$this ) ) ) {
3672 * Clear the user's session, and reset the instance cache.
3675 public function doLogout() {
3676 $session = $this->getRequest()->getSession();
3677 if ( !$session->canSetUser() ) {
3678 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3679 ->warning( __METHOD__
. ": Cannot log out of an immutable session" );
3680 } elseif ( !$session->getUser()->equals( $this ) ) {
3681 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3682 ->warning( __METHOD__
.
3683 ": Cannot log user \"$this\" out of a user \"{$session->getUser()}\"'s session"
3685 // But we still may as well make this user object anon
3686 $this->clearInstanceCache( 'defaults' );
3688 $this->clearInstanceCache( 'defaults' );
3689 $delay = $session->delaySave();
3690 $session->setLoggedOutTimestamp( time() );
3691 $session->setUser( new User
);
3692 $session->set( 'wsUserID', 0 ); // Other code expects this
3693 ScopedCallback
::consume( $delay );
3698 * Save this user's settings into the database.
3699 * @todo Only rarely do all these fields need to be set!
3701 public function saveSettings() {
3702 if ( wfReadOnly() ) {
3703 // @TODO: caller should deal with this instead!
3704 // This should really just be an exception.
3705 MWExceptionHandler
::logException( new DBExpectedError(
3707 "Could not update user with ID '{$this->mId}'; DB is read-only."
3713 if ( 0 == $this->mId
) {
3717 // Get a new user_touched that is higher than the old one.
3718 // This will be used for a CAS check as a last-resort safety
3719 // check against race conditions and slave lag.
3720 $oldTouched = $this->mTouched
;
3721 $newTouched = $this->newTouchedTimestamp();
3723 $dbw = wfGetDB( DB_MASTER
);
3724 $dbw->update( 'user',
3726 'user_name' => $this->mName
,
3727 'user_real_name' => $this->mRealName
,
3728 'user_email' => $this->mEmail
,
3729 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3730 'user_touched' => $dbw->timestamp( $newTouched ),
3731 'user_token' => strval( $this->mToken
),
3732 'user_email_token' => $this->mEmailToken
,
3733 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
3734 ), array( /* WHERE */
3735 'user_id' => $this->mId
,
3736 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
3740 if ( !$dbw->affectedRows() ) {
3741 // Maybe the problem was a missed cache update; clear it to be safe
3742 $this->clearSharedCache( 'refresh' );
3743 // User was changed in the meantime or loaded with stale data
3744 $from = ( $this->queryFlagsUsed
& self
::READ_LATEST
) ?
'master' : 'slave';
3745 throw new MWException(
3746 "CAS update failed on user_touched for user ID '{$this->mId}' (read from $from);" .
3747 " the version of the user to be saved is older than the current version."
3751 $this->mTouched
= $newTouched;
3752 $this->saveOptions();
3754 Hooks
::run( 'UserSaveSettings', array( $this ) );
3755 $this->clearSharedCache();
3756 $this->getUserPage()->invalidateCache();
3760 * If only this user's username is known, and it exists, return the user ID.
3762 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
3765 public function idForName( $flags = 0 ) {
3766 $s = trim( $this->getName() );
3771 $db = ( ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
)
3772 ?
wfGetDB( DB_MASTER
)
3773 : wfGetDB( DB_SLAVE
);
3775 $options = ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
)
3776 ?
array( 'LOCK IN SHARE MODE' )
3779 $id = $db->selectField( 'user',
3780 'user_id', array( 'user_name' => $s ), __METHOD__
, $options );
3786 * Add a user to the database, return the user object
3788 * @param string $name Username to add
3789 * @param array $params Array of Strings Non-default parameters to save to
3790 * the database as user_* fields:
3791 * - email: The user's email address.
3792 * - email_authenticated: The email authentication timestamp.
3793 * - real_name: The user's real name.
3794 * - options: An associative array of non-default options.
3795 * - token: Random authentication token. Do not set.
3796 * - registration: Registration timestamp. Do not set.
3798 * @return User|null User object, or null if the username already exists.
3800 public static function createNew( $name, $params = array() ) {
3801 foreach ( array( 'password', 'newpassword', 'newpass_time', 'password_expires' ) as $field ) {
3802 if ( isset( $params[$field] ) ) {
3803 wfDeprecated( __METHOD__
. " with param '$field'", '1.27' );
3804 unset( $params[$field] );
3810 $user->setToken(); // init token
3811 if ( isset( $params['options'] ) ) {
3812 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
3813 unset( $params['options'] );
3815 $dbw = wfGetDB( DB_MASTER
);
3816 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3818 $noPass = PasswordFactory
::newInvalidPassword()->toString();
3821 'user_id' => $seqVal,
3822 'user_name' => $name,
3823 'user_password' => $noPass,
3824 'user_newpassword' => $noPass,
3825 'user_email' => $user->mEmail
,
3826 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
3827 'user_real_name' => $user->mRealName
,
3828 'user_token' => strval( $user->mToken
),
3829 'user_registration' => $dbw->timestamp( $user->mRegistration
),
3830 'user_editcount' => 0,
3831 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
3833 foreach ( $params as $name => $value ) {
3834 $fields["user_$name"] = $value;
3836 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
3837 if ( $dbw->affectedRows() ) {
3838 $newUser = User
::newFromId( $dbw->insertId() );
3846 * Add this existing user object to the database. If the user already
3847 * exists, a fatal status object is returned, and the user object is
3848 * initialised with the data from the database.
3850 * Previously, this function generated a DB error due to a key conflict
3851 * if the user already existed. Many extension callers use this function
3852 * in code along the lines of:
3854 * $user = User::newFromName( $name );
3855 * if ( !$user->isLoggedIn() ) {
3856 * $user->addToDatabase();
3858 * // do something with $user...
3860 * However, this was vulnerable to a race condition (bug 16020). By
3861 * initialising the user object if the user exists, we aim to support this
3862 * calling sequence as far as possible.
3864 * Note that if the user exists, this function will acquire a write lock,
3865 * so it is still advisable to make the call conditional on isLoggedIn(),
3866 * and to commit the transaction after calling.
3868 * @throws MWException
3871 public function addToDatabase() {
3873 if ( !$this->mToken
) {
3874 $this->setToken(); // init token
3877 $this->mTouched
= $this->newTouchedTimestamp();
3879 $noPass = PasswordFactory
::newInvalidPassword()->toString();
3881 $dbw = wfGetDB( DB_MASTER
);
3882 $inWrite = $dbw->writesOrCallbacksPending();
3883 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3884 $dbw->insert( 'user',
3886 'user_id' => $seqVal,
3887 'user_name' => $this->mName
,
3888 'user_password' => $noPass,
3889 'user_newpassword' => $noPass,
3890 'user_email' => $this->mEmail
,
3891 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3892 'user_real_name' => $this->mRealName
,
3893 'user_token' => strval( $this->mToken
),
3894 'user_registration' => $dbw->timestamp( $this->mRegistration
),
3895 'user_editcount' => 0,
3896 'user_touched' => $dbw->timestamp( $this->mTouched
),
3900 if ( !$dbw->affectedRows() ) {
3901 // The queries below cannot happen in the same REPEATABLE-READ snapshot.
3902 // Handle this by COMMIT, if possible, or by LOCK IN SHARE MODE otherwise.
3904 // Can't commit due to pending writes that may need atomicity.
3905 // This may cause some lock contention unlike the case below.
3906 $options = array( 'LOCK IN SHARE MODE' );
3907 $flags = self
::READ_LOCKING
;
3909 // Often, this case happens early in views before any writes when
3910 // using CentralAuth. It's should be OK to commit and break the snapshot.
3911 $dbw->commit( __METHOD__
, 'flush' );
3913 $flags = self
::READ_LATEST
;
3915 $this->mId
= $dbw->selectField( 'user', 'user_id',
3916 array( 'user_name' => $this->mName
), __METHOD__
, $options );
3919 if ( $this->loadFromDatabase( $flags ) ) {
3924 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
3925 "to insert user '{$this->mName}' row, but it was not present in select!" );
3927 return Status
::newFatal( 'userexists' );
3929 $this->mId
= $dbw->insertId();
3930 self
::$idCacheByName[$this->mName
] = $this->mId
;
3932 // Clear instance cache other than user table data, which is already accurate
3933 $this->clearInstanceCache();
3935 $this->saveOptions();
3936 return Status
::newGood();
3940 * If this user is logged-in and blocked,
3941 * block any IP address they've successfully logged in from.
3942 * @return bool A block was spread
3944 public function spreadAnyEditBlock() {
3945 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3946 return $this->spreadBlock();
3952 * If this (non-anonymous) user is blocked,
3953 * block the IP address they've successfully logged in from.
3954 * @return bool A block was spread
3956 protected function spreadBlock() {
3957 wfDebug( __METHOD__
. "()\n" );
3959 if ( $this->mId
== 0 ) {
3963 $userblock = Block
::newFromTarget( $this->getName() );
3964 if ( !$userblock ) {
3968 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3972 * Get whether the user is explicitly blocked from account creation.
3973 * @return bool|Block
3975 public function isBlockedFromCreateAccount() {
3976 $this->getBlockedStatus();
3977 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
3978 return $this->mBlock
;
3981 # bug 13611: if the IP address the user is trying to create an account from is
3982 # blocked with createaccount disabled, prevent new account creation there even
3983 # when the user is logged in
3984 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3985 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
3987 return $this->mBlockedFromCreateAccount
instanceof Block
3988 && $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
3989 ?
$this->mBlockedFromCreateAccount
3994 * Get whether the user is blocked from using Special:Emailuser.
3997 public function isBlockedFromEmailuser() {
3998 $this->getBlockedStatus();
3999 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
4003 * Get whether the user is allowed to create an account.
4006 public function isAllowedToCreateAccount() {
4007 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
4011 * Get this user's personal page title.
4013 * @return Title User's personal page title
4015 public function getUserPage() {
4016 return Title
::makeTitle( NS_USER
, $this->getName() );
4020 * Get this user's talk page title.
4022 * @return Title User's talk page title
4024 public function getTalkPage() {
4025 $title = $this->getUserPage();
4026 return $title->getTalkPage();
4030 * Determine whether the user is a newbie. Newbies are either
4031 * anonymous IPs, or the most recently created accounts.
4034 public function isNewbie() {
4035 return !$this->isAllowed( 'autoconfirmed' );
4039 * Check to see if the given clear-text password is one of the accepted passwords
4040 * @deprecated since 1.27. AuthManager is coming.
4041 * @param string $password User password
4042 * @return bool True if the given password is correct, otherwise False
4044 public function checkPassword( $password ) {
4045 global $wgAuth, $wgLegacyEncoding;
4049 // Some passwords will give a fatal Status, which means there is
4050 // some sort of technical or security reason for this password to
4051 // be completely invalid and should never be checked (e.g., T64685)
4052 if ( !$this->checkPasswordValidity( $password )->isOK() ) {
4056 // Certain authentication plugins do NOT want to save
4057 // domain passwords in a mysql database, so we should
4058 // check this (in case $wgAuth->strict() is false).
4059 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
4061 } elseif ( $wgAuth->strict() ) {
4062 // Auth plugin doesn't allow local authentication
4064 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
4065 // Auth plugin doesn't allow local authentication for this user name
4069 $passwordFactory = new PasswordFactory();
4070 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4071 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
4072 ?
wfGetDB( DB_MASTER
)
4073 : wfGetDB( DB_SLAVE
);
4076 $mPassword = $passwordFactory->newFromCiphertext( $db->selectField(
4077 'user', 'user_password', array( 'user_id' => $this->getId() ), __METHOD__
4079 } catch ( PasswordError
$e ) {
4080 wfDebug( 'Invalid password hash found in database.' );
4081 $mPassword = PasswordFactory
::newInvalidPassword();
4084 if ( !$mPassword->equals( $password ) ) {
4085 if ( $wgLegacyEncoding ) {
4086 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
4087 // Check for this with iconv
4088 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
4089 if ( $cp1252Password === $password ||
!$mPassword->equals( $cp1252Password ) ) {
4097 if ( $passwordFactory->needsUpdate( $mPassword ) && !wfReadOnly() ) {
4098 $this->setPasswordInternal( $password );
4105 * Check if the given clear-text password matches the temporary password
4106 * sent by e-mail for password reset operations.
4108 * @deprecated since 1.27. AuthManager is coming.
4109 * @param string $plaintext
4110 * @return bool True if matches, false otherwise
4112 public function checkTemporaryPassword( $plaintext ) {
4113 global $wgNewPasswordExpiry;
4117 $passwordFactory = new PasswordFactory();
4118 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4119 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
4120 ?
wfGetDB( DB_MASTER
)
4121 : wfGetDB( DB_SLAVE
);
4123 $row = $db->selectRow(
4125 array( 'user_newpassword', 'user_newpass_time' ),
4126 array( 'user_id' => $this->getId() ),
4130 $newPassword = $passwordFactory->newFromCiphertext( $row->user_newpassword
);
4131 } catch ( PasswordError
$e ) {
4132 wfDebug( 'Invalid password hash found in database.' );
4133 $newPassword = PasswordFactory
::newInvalidPassword();
4136 if ( $newPassword->equals( $plaintext ) ) {
4137 if ( is_null( $row->user_newpass_time
) ) {
4140 $expiry = wfTimestamp( TS_UNIX
, $row->user_newpass_time
) +
$wgNewPasswordExpiry;
4141 return ( time() < $expiry );
4148 * Initialize (if necessary) and return a session token value
4149 * which can be used in edit forms to show that the user's
4150 * login credentials aren't being hijacked with a foreign form
4154 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4155 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4156 * @return MediaWiki\\Session\\Token The new edit token
4158 public function getEditTokenObject( $salt = '', $request = null ) {
4159 if ( $this->isAnon() ) {
4160 return new LoggedOutEditToken();
4164 $request = $this->getRequest();
4166 return $request->getSession()->getToken( $salt );
4170 * Initialize (if necessary) and return a session token value
4171 * which can be used in edit forms to show that the user's
4172 * login credentials aren't being hijacked with a foreign form
4176 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4177 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4178 * @return string The new edit token
4180 public function getEditToken( $salt = '', $request = null ) {
4181 return $this->getEditTokenObject( $salt, $request )->toString();
4185 * Get the embedded timestamp from a token.
4186 * @deprecated since 1.27, use \\MediaWiki\\Session\\Token::getTimestamp instead.
4187 * @param string $val Input token
4190 public static function getEditTokenTimestamp( $val ) {
4191 wfDeprecated( __METHOD__
, '1.27' );
4192 return MediaWiki\Session\Token
::getTimestamp( $val );
4196 * Check given value against the token value stored in the session.
4197 * A match should confirm that the form was submitted from the
4198 * user's own login session, not a form submission from a third-party
4201 * @param string $val Input value to compare
4202 * @param string $salt Optional function-specific data for hashing
4203 * @param WebRequest|null $request Object to use or null to use $wgRequest
4204 * @param int $maxage Fail tokens older than this, in seconds
4205 * @return bool Whether the token matches
4207 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4208 return $this->getEditTokenObject( $salt, $request )->match( $val, $maxage );
4212 * Check given value against the token value stored in the session,
4213 * ignoring the suffix.
4215 * @param string $val Input value to compare
4216 * @param string $salt Optional function-specific data for hashing
4217 * @param WebRequest|null $request Object to use or null to use $wgRequest
4218 * @param int $maxage Fail tokens older than this, in seconds
4219 * @return bool Whether the token matches
4221 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4222 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . self
::EDIT_TOKEN_SUFFIX
;
4223 return $this->matchEditToken( $val, $salt, $request, $maxage );
4227 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4228 * mail to the user's given address.
4230 * @param string $type Message to send, either "created", "changed" or "set"
4233 public function sendConfirmationMail( $type = 'created' ) {
4235 $expiration = null; // gets passed-by-ref and defined in next line.
4236 $token = $this->confirmationToken( $expiration );
4237 $url = $this->confirmationTokenUrl( $token );
4238 $invalidateURL = $this->invalidationTokenUrl( $token );
4239 $this->saveSettings();
4241 if ( $type == 'created' ||
$type === false ) {
4242 $message = 'confirmemail_body';
4243 } elseif ( $type === true ) {
4244 $message = 'confirmemail_body_changed';
4246 // Messages: confirmemail_body_changed, confirmemail_body_set
4247 $message = 'confirmemail_body_' . $type;
4250 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4251 wfMessage( $message,
4252 $this->getRequest()->getIP(),
4255 $wgLang->userTimeAndDate( $expiration, $this ),
4257 $wgLang->userDate( $expiration, $this ),
4258 $wgLang->userTime( $expiration, $this ) )->text() );
4262 * Send an e-mail to this user's account. Does not check for
4263 * confirmed status or validity.
4265 * @param string $subject Message subject
4266 * @param string $body Message body
4267 * @param User|null $from Optional sending user; if unspecified, default
4268 * $wgPasswordSender will be used.
4269 * @param string $replyto Reply-To address
4272 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4273 global $wgPasswordSender;
4275 if ( $from instanceof User
) {
4276 $sender = MailAddress
::newFromUser( $from );
4278 $sender = new MailAddress( $wgPasswordSender,
4279 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4281 $to = MailAddress
::newFromUser( $this );
4283 return UserMailer
::send( $to, $sender, $subject, $body, array(
4284 'replyTo' => $replyto,
4289 * Generate, store, and return a new e-mail confirmation code.
4290 * A hash (unsalted, since it's used as a key) is stored.
4292 * @note Call saveSettings() after calling this function to commit
4293 * this change to the database.
4295 * @param string &$expiration Accepts the expiration time
4296 * @return string New token
4298 protected function confirmationToken( &$expiration ) {
4299 global $wgUserEmailConfirmationTokenExpiry;
4301 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4302 $expiration = wfTimestamp( TS_MW
, $expires );
4304 $token = MWCryptRand
::generateHex( 32 );
4305 $hash = md5( $token );
4306 $this->mEmailToken
= $hash;
4307 $this->mEmailTokenExpires
= $expiration;
4312 * Return a URL the user can use to confirm their email address.
4313 * @param string $token Accepts the email confirmation token
4314 * @return string New token URL
4316 protected function confirmationTokenUrl( $token ) {
4317 return $this->getTokenUrl( 'ConfirmEmail', $token );
4321 * Return a URL the user can use to invalidate their email address.
4322 * @param string $token Accepts the email confirmation token
4323 * @return string New token URL
4325 protected function invalidationTokenUrl( $token ) {
4326 return $this->getTokenUrl( 'InvalidateEmail', $token );
4330 * Internal function to format the e-mail validation/invalidation URLs.
4331 * This uses a quickie hack to use the
4332 * hardcoded English names of the Special: pages, for ASCII safety.
4334 * @note Since these URLs get dropped directly into emails, using the
4335 * short English names avoids insanely long URL-encoded links, which
4336 * also sometimes can get corrupted in some browsers/mailers
4337 * (bug 6957 with Gmail and Internet Explorer).
4339 * @param string $page Special page
4340 * @param string $token Token
4341 * @return string Formatted URL
4343 protected function getTokenUrl( $page, $token ) {
4344 // Hack to bypass localization of 'Special:'
4345 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4346 return $title->getCanonicalURL();
4350 * Mark the e-mail address confirmed.
4352 * @note Call saveSettings() after calling this function to commit the change.
4356 public function confirmEmail() {
4357 // Check if it's already confirmed, so we don't touch the database
4358 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4359 if ( !$this->isEmailConfirmed() ) {
4360 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4361 Hooks
::run( 'ConfirmEmailComplete', array( $this ) );
4367 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4368 * address if it was already confirmed.
4370 * @note Call saveSettings() after calling this function to commit the change.
4371 * @return bool Returns true
4373 public function invalidateEmail() {
4375 $this->mEmailToken
= null;
4376 $this->mEmailTokenExpires
= null;
4377 $this->setEmailAuthenticationTimestamp( null );
4379 Hooks
::run( 'InvalidateEmailComplete', array( $this ) );
4384 * Set the e-mail authentication timestamp.
4385 * @param string $timestamp TS_MW timestamp
4387 public function setEmailAuthenticationTimestamp( $timestamp ) {
4389 $this->mEmailAuthenticated
= $timestamp;
4390 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
4394 * Is this user allowed to send e-mails within limits of current
4395 * site configuration?
4398 public function canSendEmail() {
4399 global $wgEnableEmail, $wgEnableUserEmail;
4400 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4403 $canSend = $this->isEmailConfirmed();
4404 Hooks
::run( 'UserCanSendEmail', array( &$this, &$canSend ) );
4409 * Is this user allowed to receive e-mails within limits of current
4410 * site configuration?
4413 public function canReceiveEmail() {
4414 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4418 * Is this user's e-mail address valid-looking and confirmed within
4419 * limits of the current site configuration?
4421 * @note If $wgEmailAuthentication is on, this may require the user to have
4422 * confirmed their address by returning a code or using a password
4423 * sent to the address from the wiki.
4427 public function isEmailConfirmed() {
4428 global $wgEmailAuthentication;
4431 if ( Hooks
::run( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
4432 if ( $this->isAnon() ) {
4435 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4438 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4448 * Check whether there is an outstanding request for e-mail confirmation.
4451 public function isEmailConfirmationPending() {
4452 global $wgEmailAuthentication;
4453 return $wgEmailAuthentication &&
4454 !$this->isEmailConfirmed() &&
4455 $this->mEmailToken
&&
4456 $this->mEmailTokenExpires
> wfTimestamp();
4460 * Get the timestamp of account creation.
4462 * @return string|bool|null Timestamp of account creation, false for
4463 * non-existent/anonymous user accounts, or null if existing account
4464 * but information is not in database.
4466 public function getRegistration() {
4467 if ( $this->isAnon() ) {
4471 return $this->mRegistration
;
4475 * Get the timestamp of the first edit
4477 * @return string|bool Timestamp of first edit, or false for
4478 * non-existent/anonymous user accounts.
4480 public function getFirstEditTimestamp() {
4481 if ( $this->getId() == 0 ) {
4482 return false; // anons
4484 $dbr = wfGetDB( DB_SLAVE
);
4485 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4486 array( 'rev_user' => $this->getId() ),
4488 array( 'ORDER BY' => 'rev_timestamp ASC' )
4491 return false; // no edits
4493 return wfTimestamp( TS_MW
, $time );
4497 * Get the permissions associated with a given list of groups
4499 * @param array $groups Array of Strings List of internal group names
4500 * @return array Array of Strings List of permission key names for given groups combined
4502 public static function getGroupPermissions( $groups ) {
4503 global $wgGroupPermissions, $wgRevokePermissions;
4505 // grant every granted permission first
4506 foreach ( $groups as $group ) {
4507 if ( isset( $wgGroupPermissions[$group] ) ) {
4508 $rights = array_merge( $rights,
4509 // array_filter removes empty items
4510 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4513 // now revoke the revoked permissions
4514 foreach ( $groups as $group ) {
4515 if ( isset( $wgRevokePermissions[$group] ) ) {
4516 $rights = array_diff( $rights,
4517 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4520 return array_unique( $rights );
4524 * Get all the groups who have a given permission
4526 * @param string $role Role to check
4527 * @return array Array of Strings List of internal group names with the given permission
4529 public static function getGroupsWithPermission( $role ) {
4530 global $wgGroupPermissions;
4531 $allowedGroups = array();
4532 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4533 if ( self
::groupHasPermission( $group, $role ) ) {
4534 $allowedGroups[] = $group;
4537 return $allowedGroups;
4541 * Check, if the given group has the given permission
4543 * If you're wanting to check whether all users have a permission, use
4544 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4548 * @param string $group Group to check
4549 * @param string $role Role to check
4552 public static function groupHasPermission( $group, $role ) {
4553 global $wgGroupPermissions, $wgRevokePermissions;
4554 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4555 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4559 * Check if all users may be assumed to have the given permission
4561 * We generally assume so if the right is granted to '*' and isn't revoked
4562 * on any group. It doesn't attempt to take grants or other extension
4563 * limitations on rights into account in the general case, though, as that
4564 * would require it to always return false and defeat the purpose.
4565 * Specifically, session-based rights restrictions (such as OAuth or bot
4566 * passwords) are applied based on the current session.
4569 * @param string $right Right to check
4572 public static function isEveryoneAllowed( $right ) {
4573 global $wgGroupPermissions, $wgRevokePermissions;
4574 static $cache = array();
4576 // Use the cached results, except in unit tests which rely on
4577 // being able change the permission mid-request
4578 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4579 return $cache[$right];
4582 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4583 $cache[$right] = false;
4587 // If it's revoked anywhere, then everyone doesn't have it
4588 foreach ( $wgRevokePermissions as $rights ) {
4589 if ( isset( $rights[$right] ) && $rights[$right] ) {
4590 $cache[$right] = false;
4595 // Remove any rights that aren't allowed to the global-session user
4596 $allowedRights = SessionManager
::getGlobalSession()->getAllowedUserRights();
4597 if ( $allowedRights !== null && !in_array( $right, $allowedRights, true ) ) {
4598 $cache[$right] = false;
4602 // Allow extensions to say false
4603 if ( !Hooks
::run( 'UserIsEveryoneAllowed', array( $right ) ) ) {
4604 $cache[$right] = false;
4608 $cache[$right] = true;
4613 * Get the localized descriptive name for a group, if it exists
4615 * @param string $group Internal group name
4616 * @return string Localized descriptive group name
4618 public static function getGroupName( $group ) {
4619 $msg = wfMessage( "group-$group" );
4620 return $msg->isBlank() ?
$group : $msg->text();
4624 * Get the localized descriptive name for a member of a group, if it exists
4626 * @param string $group Internal group name
4627 * @param string $username Username for gender (since 1.19)
4628 * @return string Localized name for group member
4630 public static function getGroupMember( $group, $username = '#' ) {
4631 $msg = wfMessage( "group-$group-member", $username );
4632 return $msg->isBlank() ?
$group : $msg->text();
4636 * Return the set of defined explicit groups.
4637 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4638 * are not included, as they are defined automatically, not in the database.
4639 * @return array Array of internal group names
4641 public static function getAllGroups() {
4642 global $wgGroupPermissions, $wgRevokePermissions;
4644 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4645 self
::getImplicitGroups()
4650 * Get a list of all available permissions.
4651 * @return string[] Array of permission names
4653 public static function getAllRights() {
4654 if ( self
::$mAllRights === false ) {
4655 global $wgAvailableRights;
4656 if ( count( $wgAvailableRights ) ) {
4657 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
4659 self
::$mAllRights = self
::$mCoreRights;
4661 Hooks
::run( 'UserGetAllRights', array( &self
::$mAllRights ) );
4663 return self
::$mAllRights;
4667 * Get a list of implicit groups
4668 * @return array Array of Strings Array of internal group names
4670 public static function getImplicitGroups() {
4671 global $wgImplicitGroups;
4673 $groups = $wgImplicitGroups;
4674 # Deprecated, use $wgImplicitGroups instead
4675 Hooks
::run( 'UserGetImplicitGroups', array( &$groups ), '1.25' );
4681 * Get the title of a page describing a particular group
4683 * @param string $group Internal group name
4684 * @return Title|bool Title of the page if it exists, false otherwise
4686 public static function getGroupPage( $group ) {
4687 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4688 if ( $msg->exists() ) {
4689 $title = Title
::newFromText( $msg->text() );
4690 if ( is_object( $title ) ) {
4698 * Create a link to the group in HTML, if available;
4699 * else return the group name.
4701 * @param string $group Internal name of the group
4702 * @param string $text The text of the link
4703 * @return string HTML link to the group
4705 public static function makeGroupLinkHTML( $group, $text = '' ) {
4706 if ( $text == '' ) {
4707 $text = self
::getGroupName( $group );
4709 $title = self
::getGroupPage( $group );
4711 return Linker
::link( $title, htmlspecialchars( $text ) );
4713 return htmlspecialchars( $text );
4718 * Create a link to the group in Wikitext, if available;
4719 * else return the group name.
4721 * @param string $group Internal name of the group
4722 * @param string $text The text of the link
4723 * @return string Wikilink to the group
4725 public static function makeGroupLinkWiki( $group, $text = '' ) {
4726 if ( $text == '' ) {
4727 $text = self
::getGroupName( $group );
4729 $title = self
::getGroupPage( $group );
4731 $page = $title->getFullText();
4732 return "[[$page|$text]]";
4739 * Returns an array of the groups that a particular group can add/remove.
4741 * @param string $group The group to check for whether it can add/remove
4742 * @return array Array( 'add' => array( addablegroups ),
4743 * 'remove' => array( removablegroups ),
4744 * 'add-self' => array( addablegroups to self),
4745 * 'remove-self' => array( removable groups from self) )
4747 public static function changeableByGroup( $group ) {
4748 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4752 'remove' => array(),
4753 'add-self' => array(),
4754 'remove-self' => array()
4757 if ( empty( $wgAddGroups[$group] ) ) {
4758 // Don't add anything to $groups
4759 } elseif ( $wgAddGroups[$group] === true ) {
4760 // You get everything
4761 $groups['add'] = self
::getAllGroups();
4762 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4763 $groups['add'] = $wgAddGroups[$group];
4766 // Same thing for remove
4767 if ( empty( $wgRemoveGroups[$group] ) ) {
4769 } elseif ( $wgRemoveGroups[$group] === true ) {
4770 $groups['remove'] = self
::getAllGroups();
4771 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4772 $groups['remove'] = $wgRemoveGroups[$group];
4775 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4776 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4777 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4778 if ( is_int( $key ) ) {
4779 $wgGroupsAddToSelf['user'][] = $value;
4784 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
4785 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4786 if ( is_int( $key ) ) {
4787 $wgGroupsRemoveFromSelf['user'][] = $value;
4792 // Now figure out what groups the user can add to him/herself
4793 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4795 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4796 // No idea WHY this would be used, but it's there
4797 $groups['add-self'] = User
::getAllGroups();
4798 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4799 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4802 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4804 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4805 $groups['remove-self'] = User
::getAllGroups();
4806 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4807 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4814 * Returns an array of groups that this user can add and remove
4815 * @return array Array( 'add' => array( addablegroups ),
4816 * 'remove' => array( removablegroups ),
4817 * 'add-self' => array( addablegroups to self),
4818 * 'remove-self' => array( removable groups from self) )
4820 public function changeableGroups() {
4821 if ( $this->isAllowed( 'userrights' ) ) {
4822 // This group gives the right to modify everything (reverse-
4823 // compatibility with old "userrights lets you change
4825 // Using array_merge to make the groups reindexed
4826 $all = array_merge( User
::getAllGroups() );
4830 'add-self' => array(),
4831 'remove-self' => array()
4835 // Okay, it's not so simple, we will have to go through the arrays
4838 'remove' => array(),
4839 'add-self' => array(),
4840 'remove-self' => array()
4842 $addergroups = $this->getEffectiveGroups();
4844 foreach ( $addergroups as $addergroup ) {
4845 $groups = array_merge_recursive(
4846 $groups, $this->changeableByGroup( $addergroup )
4848 $groups['add'] = array_unique( $groups['add'] );
4849 $groups['remove'] = array_unique( $groups['remove'] );
4850 $groups['add-self'] = array_unique( $groups['add-self'] );
4851 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4857 * Deferred version of incEditCountImmediate()
4859 public function incEditCount() {
4861 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle( function() use ( $that ) {
4862 $that->incEditCountImmediate();
4867 * Increment the user's edit-count field.
4868 * Will have no effect for anonymous users.
4871 public function incEditCountImmediate() {
4872 if ( $this->isAnon() ) {
4876 $dbw = wfGetDB( DB_MASTER
);
4877 // No rows will be "affected" if user_editcount is NULL
4880 array( 'user_editcount=user_editcount+1' ),
4881 array( 'user_id' => $this->getId(), 'user_editcount IS NOT NULL' ),
4884 // Lazy initialization check...
4885 if ( $dbw->affectedRows() == 0 ) {
4886 // Now here's a goddamn hack...
4887 $dbr = wfGetDB( DB_SLAVE
);
4888 if ( $dbr !== $dbw ) {
4889 // If we actually have a slave server, the count is
4890 // at least one behind because the current transaction
4891 // has not been committed and replicated.
4892 $this->initEditCount( 1 );
4894 // But if DB_SLAVE is selecting the master, then the
4895 // count we just read includes the revision that was
4896 // just added in the working transaction.
4897 $this->initEditCount();
4900 // Edit count in user cache too
4901 $this->invalidateCache();
4905 * Initialize user_editcount from data out of the revision table
4907 * @param int $add Edits to add to the count from the revision table
4908 * @return int Number of edits
4910 protected function initEditCount( $add = 0 ) {
4911 // Pull from a slave to be less cruel to servers
4912 // Accuracy isn't the point anyway here
4913 $dbr = wfGetDB( DB_SLAVE
);
4914 $count = (int)$dbr->selectField(
4917 array( 'rev_user' => $this->getId() ),
4920 $count = $count +
$add;
4922 $dbw = wfGetDB( DB_MASTER
);
4925 array( 'user_editcount' => $count ),
4926 array( 'user_id' => $this->getId() ),
4934 * Get the description of a given right
4936 * @param string $right Right to query
4937 * @return string Localized description of the right
4939 public static function getRightDescription( $right ) {
4940 $key = "right-$right";
4941 $msg = wfMessage( $key );
4942 return $msg->isBlank() ?
$right : $msg->text();
4946 * Make a new-style password hash
4948 * @param string $password Plain-text password
4949 * @param bool|string $salt Optional salt, may be random or the user ID.
4950 * If unspecified or false, will generate one automatically
4951 * @return string Password hash
4952 * @deprecated since 1.24, use Password class
4954 public static function crypt( $password, $salt = false ) {
4955 wfDeprecated( __METHOD__
, '1.24' );
4956 $passwordFactory = new PasswordFactory();
4957 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4958 $hash = $passwordFactory->newFromPlaintext( $password );
4959 return $hash->toString();
4963 * Compare a password hash with a plain-text password. Requires the user
4964 * ID if there's a chance that the hash is an old-style hash.
4966 * @param string $hash Password hash
4967 * @param string $password Plain-text password to compare
4968 * @param string|bool $userId User ID for old-style password salt
4971 * @deprecated since 1.24, use Password class
4973 public static function comparePasswords( $hash, $password, $userId = false ) {
4974 wfDeprecated( __METHOD__
, '1.24' );
4976 // Check for *really* old password hashes that don't even have a type
4977 // The old hash format was just an md5 hex hash, with no type information
4978 if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) {
4979 global $wgPasswordSalt;
4980 if ( $wgPasswordSalt ) {
4981 $password = ":B:{$userId}:{$hash}";
4983 $password = ":A:{$hash}";
4987 $passwordFactory = new PasswordFactory();
4988 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4989 $hash = $passwordFactory->newFromCiphertext( $hash );
4990 return $hash->equals( $password );
4994 * Add a newuser log entry for this user.
4995 * Before 1.19 the return value was always true.
4997 * @param string|bool $action Account creation type.
4998 * - String, one of the following values:
4999 * - 'create' for an anonymous user creating an account for himself.
5000 * This will force the action's performer to be the created user itself,
5001 * no matter the value of $wgUser
5002 * - 'create2' for a logged in user creating an account for someone else
5003 * - 'byemail' when the created user will receive its password by e-mail
5004 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
5005 * - Boolean means whether the account was created by e-mail (deprecated):
5006 * - true will be converted to 'byemail'
5007 * - false will be converted to 'create' if this object is the same as
5008 * $wgUser and to 'create2' otherwise
5010 * @param string $reason User supplied reason
5012 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
5014 public function addNewUserLogEntry( $action = false, $reason = '' ) {
5015 global $wgUser, $wgNewUserLog;
5016 if ( empty( $wgNewUserLog ) ) {
5017 return true; // disabled
5020 if ( $action === true ) {
5021 $action = 'byemail';
5022 } elseif ( $action === false ) {
5023 if ( $this->equals( $wgUser ) ) {
5026 $action = 'create2';
5030 if ( $action === 'create' ||
$action === 'autocreate' ) {
5033 $performer = $wgUser;
5036 $logEntry = new ManualLogEntry( 'newusers', $action );
5037 $logEntry->setPerformer( $performer );
5038 $logEntry->setTarget( $this->getUserPage() );
5039 $logEntry->setComment( $reason );
5040 $logEntry->setParameters( array(
5041 '4::userid' => $this->getId(),
5043 $logid = $logEntry->insert();
5045 if ( $action !== 'autocreate' ) {
5046 $logEntry->publish( $logid );
5053 * Add an autocreate newuser log entry for this user
5054 * Used by things like CentralAuth and perhaps other authplugins.
5055 * Consider calling addNewUserLogEntry() directly instead.
5059 public function addNewUserLogEntryAutoCreate() {
5060 $this->addNewUserLogEntry( 'autocreate' );
5066 * Load the user options either from cache, the database or an array
5068 * @param array $data Rows for the current user out of the user_properties table
5070 protected function loadOptions( $data = null ) {
5075 if ( $this->mOptionsLoaded
) {
5079 $this->mOptions
= self
::getDefaultOptions();
5081 if ( !$this->getId() ) {
5082 // For unlogged-in users, load language/variant options from request.
5083 // There's no need to do it for logged-in users: they can set preferences,
5084 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5085 // so don't override user's choice (especially when the user chooses site default).
5086 $variant = $wgContLang->getDefaultVariant();
5087 $this->mOptions
['variant'] = $variant;
5088 $this->mOptions
['language'] = $variant;
5089 $this->mOptionsLoaded
= true;
5093 // Maybe load from the object
5094 if ( !is_null( $this->mOptionOverrides
) ) {
5095 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5096 foreach ( $this->mOptionOverrides
as $key => $value ) {
5097 $this->mOptions
[$key] = $value;
5100 if ( !is_array( $data ) ) {
5101 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5102 // Load from database
5103 $dbr = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
5104 ?
wfGetDB( DB_MASTER
)
5105 : wfGetDB( DB_SLAVE
);
5107 $res = $dbr->select(
5109 array( 'up_property', 'up_value' ),
5110 array( 'up_user' => $this->getId() ),
5114 $this->mOptionOverrides
= array();
5116 foreach ( $res as $row ) {
5117 $data[$row->up_property
] = $row->up_value
;
5120 foreach ( $data as $property => $value ) {
5121 $this->mOptionOverrides
[$property] = $value;
5122 $this->mOptions
[$property] = $value;
5126 $this->mOptionsLoaded
= true;
5128 Hooks
::run( 'UserLoadOptions', array( $this, &$this->mOptions
) );
5132 * Saves the non-default options for this user, as previously set e.g. via
5133 * setOption(), in the database's "user_properties" (preferences) table.
5134 * Usually used via saveSettings().
5136 protected function saveOptions() {
5137 $this->loadOptions();
5139 // Not using getOptions(), to keep hidden preferences in database
5140 $saveOptions = $this->mOptions
;
5142 // Allow hooks to abort, for instance to save to a global profile.
5143 // Reset options to default state before saving.
5144 if ( !Hooks
::run( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
5148 $userId = $this->getId();
5150 $insert_rows = array(); // all the new preference rows
5151 foreach ( $saveOptions as $key => $value ) {
5152 // Don't bother storing default values
5153 $defaultOption = self
::getDefaultOption( $key );
5154 if ( ( $defaultOption === null && $value !== false && $value !== null )
5155 ||
$value != $defaultOption
5157 $insert_rows[] = array(
5158 'up_user' => $userId,
5159 'up_property' => $key,
5160 'up_value' => $value,
5165 $dbw = wfGetDB( DB_MASTER
);
5167 $res = $dbw->select( 'user_properties',
5168 array( 'up_property', 'up_value' ), array( 'up_user' => $userId ), __METHOD__
);
5170 // Find prior rows that need to be removed or updated. These rows will
5171 // all be deleted (the later so that INSERT IGNORE applies the new values).
5172 $keysDelete = array();
5173 foreach ( $res as $row ) {
5174 if ( !isset( $saveOptions[$row->up_property
] )
5175 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
5177 $keysDelete[] = $row->up_property
;
5181 if ( count( $keysDelete ) ) {
5182 // Do the DELETE by PRIMARY KEY for prior rows.
5183 // In the past a very large portion of calls to this function are for setting
5184 // 'rememberpassword' for new accounts (a preference that has since been removed).
5185 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5186 // caused gap locks on [max user ID,+infinity) which caused high contention since
5187 // updates would pile up on each other as they are for higher (newer) user IDs.
5188 // It might not be necessary these days, but it shouldn't hurt either.
5189 $dbw->delete( 'user_properties',
5190 array( 'up_user' => $userId, 'up_property' => $keysDelete ), __METHOD__
);
5192 // Insert the new preference rows
5193 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, array( 'IGNORE' ) );
5197 * Lazily instantiate and return a factory object for making passwords
5199 * @deprecated since 1.27, create a PasswordFactory directly instead
5200 * @return PasswordFactory
5202 public static function getPasswordFactory() {
5203 wfDeprecated( __METHOD__
, '1.27' );
5204 $ret = new PasswordFactory();
5205 $ret->init( RequestContext
::getMain()->getConfig() );
5210 * Provide an array of HTML5 attributes to put on an input element
5211 * intended for the user to enter a new password. This may include
5212 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
5214 * Do *not* use this when asking the user to enter his current password!
5215 * Regardless of configuration, users may have invalid passwords for whatever
5216 * reason (e.g., they were set before requirements were tightened up).
5217 * Only use it when asking for a new password, like on account creation or
5220 * Obviously, you still need to do server-side checking.
5222 * NOTE: A combination of bugs in various browsers means that this function
5223 * actually just returns array() unconditionally at the moment. May as
5224 * well keep it around for when the browser bugs get fixed, though.
5226 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
5228 * @deprecated since 1.27
5229 * @return array Array of HTML attributes suitable for feeding to
5230 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
5231 * That will get confused by the boolean attribute syntax used.)
5233 public static function passwordChangeInputAttribs() {
5234 global $wgMinimalPasswordLength;
5236 if ( $wgMinimalPasswordLength == 0 ) {
5240 # Note that the pattern requirement will always be satisfied if the
5241 # input is empty, so we need required in all cases.
5243 # @todo FIXME: Bug 23769: This needs to not claim the password is required
5244 # if e-mail confirmation is being used. Since HTML5 input validation
5245 # is b0rked anyway in some browsers, just return nothing. When it's
5246 # re-enabled, fix this code to not output required for e-mail
5248 # $ret = array( 'required' );
5251 # We can't actually do this right now, because Opera 9.6 will print out
5252 # the entered password visibly in its error message! When other
5253 # browsers add support for this attribute, or Opera fixes its support,
5254 # we can add support with a version check to avoid doing this on Opera
5255 # versions where it will be a problem. Reported to Opera as
5256 # DSK-262266, but they don't have a public bug tracker for us to follow.
5258 if ( $wgMinimalPasswordLength > 1 ) {
5259 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
5260 $ret['title'] = wfMessage( 'passwordtooshort' )
5261 ->numParams( $wgMinimalPasswordLength )->text();
5269 * Return the list of user fields that should be selected to create
5270 * a new user object.
5273 public static function selectFields() {
5281 'user_email_authenticated',
5283 'user_email_token_expires',
5284 'user_registration',
5290 * Factory function for fatal permission-denied errors
5293 * @param string $permission User right required
5296 static function newFatalPermissionDeniedStatus( $permission ) {
5299 $groups = array_map(
5300 array( 'User', 'makeGroupLinkWiki' ),
5301 User
::getGroupsWithPermission( $permission )
5305 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5307 return Status
::newFatal( 'badaccess-group0' );
5312 * Get a new instance of this user that was loaded from the master via a locking read
5314 * Use this instead of the main context User when updating that user. This avoids races
5315 * where that user was loaded from a slave or even the master but without proper locks.
5317 * @return User|null Returns null if the user was not found in the DB
5320 public function getInstanceForUpdate() {
5321 if ( !$this->getId() ) {
5322 return null; // anon
5325 $user = self
::newFromId( $this->getId() );
5326 if ( !$user->loadFromId( self
::READ_EXCLUSIVE
) ) {
5334 * Checks if two user objects point to the same user.
5340 public function equals( User
$user ) {
5341 return $this->getName() === $user->getName();