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
24 * String Some punctuation to prevent editing from broken text-mangling proxies.
27 define( 'EDIT_TOKEN_SUFFIX', '+\\' );
30 * The User object encapsulates all of the user-specific settings (user_id,
31 * name, rights, email address, options, last login time). Client
32 * classes use the getXXX() functions to access these fields. These functions
33 * do all the work of determining whether the user is logged in,
34 * whether the requested option can be satisfied from cookies or
35 * whether a database query is needed. Most of the settings needed
36 * for rendering normal pages are set in the cookie to minimize use
39 class User
implements IDBAccessObject
{
41 * @const int Number of characters in user_token field.
43 const TOKEN_LENGTH
= 32;
46 * Global constant made accessible as class constants so that autoloader
49 const EDIT_TOKEN_SUFFIX
= EDIT_TOKEN_SUFFIX
;
52 * @const int Serialized record version.
57 * Maximum items in $mWatchedItems
59 const MAX_WATCHED_ITEMS_CACHE
= 100;
62 * Exclude user options that are set to their default value.
65 const GETOPTIONS_EXCLUDE_DEFAULTS
= 1;
68 * Array of Strings List of member variables which are saved to the
69 * shared cache (memcached). Any operation which changes the
70 * corresponding database fields must call a cache-clearing function.
73 protected static $mCacheVars = array(
81 'mEmailAuthenticated',
88 // user_properties table
93 * Array of Strings Core rights.
94 * Each of these should have a corresponding message of the form
98 protected static $mCoreRights = array(
127 'editusercssjs', # deprecated
140 'move-categorypages',
141 'move-rootuserpages',
145 'override-export-depth',
169 'userrights-interwiki',
177 * String Cached results of getAllRights()
179 protected static $mAllRights = false;
181 /** Cache variables */
191 /** @var string TS_MW timestamp from the DB */
193 /** @var string TS_MW timestamp from cache */
194 protected $mQuickTouched;
198 public $mEmailAuthenticated;
200 protected $mEmailToken;
202 protected $mEmailTokenExpires;
204 protected $mRegistration;
206 protected $mEditCount;
210 protected $mOptionOverrides;
214 * Bool Whether the cache variables have been loaded.
217 public $mOptionsLoaded;
220 * Array with already loaded items or true if all items have been loaded.
222 protected $mLoadedItems = array();
226 * String Initialization data source if mLoadedItems!==true. May be one of:
227 * - 'defaults' anonymous user initialised from class defaults
228 * - 'name' initialise from mName
229 * - 'id' initialise from mId
230 * - 'session' log in from cookies or session if possible
232 * Use the User::newFrom*() family of functions to set this.
237 * Lazy-initialized variables, invalidated with clearInstanceCache
241 protected $mDatePreference;
249 protected $mBlockreason;
251 protected $mEffectiveGroups;
253 protected $mImplicitGroups;
255 protected $mFormerGroups;
257 protected $mBlockedGlobally;
274 protected $mAllowUsertalk;
277 private $mBlockedFromCreateAccount = false;
280 private $mWatchedItems = array();
282 /** @var integer User::READ_* constant bitfield used to load data */
283 protected $queryFlagsUsed = self
::READ_NORMAL
;
285 public static $idCacheByName = array();
288 * Lightweight constructor for an anonymous user.
289 * Use the User::newFrom* factory functions for other kinds of users.
293 * @see newFromConfirmationCode()
294 * @see newFromSession()
297 public function __construct() {
298 $this->clearInstanceCache( 'defaults' );
304 public function __toString() {
305 return $this->getName();
309 * Load the user table data for this object from the source given by mFrom.
311 * @param integer $flags User::READ_* constant bitfield
313 public function load( $flags = self
::READ_NORMAL
) {
314 if ( $this->mLoadedItems
=== true ) {
318 // Set it now to avoid infinite recursion in accessors
319 $this->mLoadedItems
= true;
320 $this->queryFlagsUsed
= $flags;
322 switch ( $this->mFrom
) {
324 $this->loadDefaults();
327 // Make sure this thread sees its own changes
328 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
329 $flags |
= self
::READ_LATEST
;
330 $this->queryFlagsUsed
= $flags;
333 $this->mId
= self
::idFromName( $this->mName
, $flags );
335 // Nonexistent user placeholder object
336 $this->loadDefaults( $this->mName
);
338 $this->loadFromId( $flags );
342 $this->loadFromId( $flags );
345 if ( !$this->loadFromSession() ) {
346 // Loading from session failed. Load defaults.
347 $this->loadDefaults();
349 Hooks
::run( 'UserLoadAfterLoadFromSession', array( $this ) );
352 throw new UnexpectedValueException(
353 "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
358 * Load user table data, given mId has already been set.
359 * @param integer $flags User::READ_* constant bitfield
360 * @return bool False if the ID does not exist, true otherwise
362 public function loadFromId( $flags = self
::READ_NORMAL
) {
363 if ( $this->mId
== 0 ) {
364 $this->loadDefaults();
368 // Try cache (unless this needs data from the master DB).
369 // NOTE: if this thread called saveSettings(), the cache was cleared.
370 $latest = DBAccessObjectUtils
::hasFlags( $flags, self
::READ_LATEST
);
371 if ( $latest ||
!$this->loadFromCache() ) {
372 wfDebug( "User: cache miss for user {$this->mId}\n" );
373 // Load from DB (make sure this thread sees its own changes)
374 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
375 $flags |
= self
::READ_LATEST
;
377 if ( !$this->loadFromDatabase( $flags ) ) {
378 // Can't load from ID, user is anonymous
381 $this->saveToCache();
384 $this->mLoadedItems
= true;
385 $this->queryFlagsUsed
= $flags;
392 * @param string $wikiId
393 * @param integer $userId
395 public static function purge( $wikiId, $userId ) {
396 $cache = ObjectCache
::getMainWANInstance();
397 $cache->delete( $cache->makeGlobalKey( 'user', 'id', $wikiId, $userId ) );
402 * @param WANObjectCache $cache
405 protected function getCacheKey( WANObjectCache
$cache ) {
406 return $cache->makeGlobalKey( 'user', 'id', wfWikiID(), $this->mId
);
410 * Load user data from shared cache, given mId has already been set.
412 * @return bool false if the ID does not exist or data is invalid, true otherwise
415 protected function loadFromCache() {
416 if ( $this->mId
== 0 ) {
417 $this->loadDefaults();
421 $cache = ObjectCache
::getMainWANInstance();
422 $data = $cache->get( $this->getCacheKey( $cache ) );
423 if ( !is_array( $data ) ||
$data['mVersion'] < self
::VERSION
) {
428 wfDebug( "User: got user {$this->mId} from cache\n" );
430 // Restore from cache
431 foreach ( self
::$mCacheVars as $name ) {
432 $this->$name = $data[$name];
439 * Save user data to the shared cache
441 * This method should not be called outside the User class
443 public function saveToCache() {
446 $this->loadOptions();
448 if ( $this->isAnon() ) {
449 // Anonymous users are uncached
454 foreach ( self
::$mCacheVars as $name ) {
455 $data[$name] = $this->$name;
457 $data['mVersion'] = self
::VERSION
;
458 $opts = Database
::getCacheSetOptions( wfGetDB( DB_SLAVE
) );
460 $cache = ObjectCache
::getMainWANInstance();
461 $key = $this->getCacheKey( $cache );
462 $cache->set( $key, $data, $cache::TTL_HOUR
, $opts );
465 /** @name newFrom*() static factory methods */
469 * Static factory method for creation from username.
471 * This is slightly less efficient than newFromId(), so use newFromId() if
472 * you have both an ID and a name handy.
474 * @param string $name Username, validated by Title::newFromText()
475 * @param string|bool $validate Validate username. Takes the same parameters as
476 * User::getCanonicalName(), except that true is accepted as an alias
477 * for 'valid', for BC.
479 * @return User|bool User object, or false if the username is invalid
480 * (e.g. if it contains illegal characters or is an IP address). If the
481 * username is not present in the database, the result will be a user object
482 * with a name, zero user ID and default settings.
484 public static function newFromName( $name, $validate = 'valid' ) {
485 if ( $validate === true ) {
488 $name = self
::getCanonicalName( $name, $validate );
489 if ( $name === false ) {
492 // Create unloaded user object
496 $u->setItemLoaded( 'name' );
502 * Static factory method for creation from a given user ID.
504 * @param int $id Valid user ID
505 * @return User The corresponding User object
507 public static function newFromId( $id ) {
511 $u->setItemLoaded( 'id' );
516 * Factory method to fetch whichever user has a given email confirmation code.
517 * This code is generated when an account is created or its e-mail address
520 * If the code is invalid or has expired, returns NULL.
522 * @param string $code Confirmation code
523 * @param int $flags User::READ_* bitfield
526 public static function newFromConfirmationCode( $code, $flags = 0 ) {
527 $db = ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
528 ?
wfGetDB( DB_MASTER
)
529 : wfGetDB( DB_SLAVE
);
531 $id = $db->selectField(
535 'user_email_token' => md5( $code ),
536 'user_email_token_expires > ' . $db->addQuotes( $db->timestamp() ),
540 return $id ? User
::newFromId( $id ) : null;
544 * Create a new user object using data from session or cookies. If the
545 * login credentials are invalid, the result is an anonymous user.
547 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
550 public static function newFromSession( WebRequest
$request = null ) {
552 $user->mFrom
= 'session';
553 $user->mRequest
= $request;
558 * Create a new user object from a user row.
559 * The row should have the following fields from the user table in it:
560 * - either user_name or user_id to load further data if needed (or both)
562 * - all other fields (email, etc.)
563 * It is useless to provide the remaining fields if either user_id,
564 * user_name and user_real_name are not provided because the whole row
565 * will be loaded once more from the database when accessing them.
567 * @param stdClass $row A row from the user table
568 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
571 public static function newFromRow( $row, $data = null ) {
573 $user->loadFromRow( $row, $data );
578 * Static factory method for creation of a "system" user from username.
580 * A "system" user is an account that's used to attribute logged actions
581 * taken by MediaWiki itself, as opposed to a bot or human user. Examples
582 * might include the 'Maintenance script' or 'Conversion script' accounts
583 * used by various scripts in the maintenance/ directory or accounts such
584 * as 'MediaWiki message delivery' used by the MassMessage extension.
586 * This can optionally create the user if it doesn't exist, and "steal" the
587 * account if it does exist.
589 * @param string $name Username
590 * @param array $options Options are:
591 * - validate: As for User::getCanonicalName(), default 'valid'
592 * - create: Whether to create the user if it doesn't already exist, default true
593 * - steal: Whether to reset the account's password and email if it
594 * already exists, default false
597 public static function newSystemUser( $name, $options = array() ) {
599 'validate' => 'valid',
604 $name = self
::getCanonicalName( $name, $options['validate'] );
605 if ( $name === false ) {
609 $dbw = wfGetDB( DB_MASTER
);
610 $row = $dbw->selectRow(
613 self
::selectFields(),
614 array( 'user_password', 'user_newpassword' )
616 array( 'user_name' => $name ),
620 // No user. Create it?
621 return $options['create'] ? self
::createNew( $name ) : null;
623 $user = self
::newFromRow( $row );
625 // A user is considered to exist as a non-system user if it has a
626 // password set, or a temporary password set, or an email set.
627 $passwordFactory = new PasswordFactory();
628 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
630 $password = $passwordFactory->newFromCiphertext( $row->user_password
);
631 } catch ( PasswordError
$e ) {
632 wfDebug( 'Invalid password hash found in database.' );
633 $password = PasswordFactory
::newInvalidPassword();
636 $newpassword = $passwordFactory->newFromCiphertext( $row->user_newpassword
);
637 } catch ( PasswordError
$e ) {
638 wfDebug( 'Invalid password hash found in database.' );
639 $newpassword = PasswordFactory
::newInvalidPassword();
641 if ( !$password instanceof InvalidPassword ||
!$newpassword instanceof InvalidPassword
644 // User exists. Steal it?
645 if ( !$options['steal'] ) {
649 $nopass = PasswordFactory
::newInvalidPassword()->toString();
654 'user_password' => $nopass,
655 'user_newpassword' => $nopass,
656 'user_newpass_time' => null,
658 array( 'user_id' => $user->getId() ),
661 $user->invalidateEmail();
662 $user->saveSettings();
671 * Get the username corresponding to a given user ID
672 * @param int $id User ID
673 * @return string|bool The corresponding username
675 public static function whoIs( $id ) {
676 return UserCache
::singleton()->getProp( $id, 'name' );
680 * Get the real name of a user given their user ID
682 * @param int $id User ID
683 * @return string|bool The corresponding user's real name
685 public static function whoIsReal( $id ) {
686 return UserCache
::singleton()->getProp( $id, 'real_name' );
690 * Get database id given a user name
691 * @param string $name Username
692 * @param integer $flags User::READ_* constant bitfield
693 * @return int|null The corresponding user's ID, or null if user is nonexistent
695 public static function idFromName( $name, $flags = self
::READ_NORMAL
) {
696 $nt = Title
::makeTitleSafe( NS_USER
, $name );
697 if ( is_null( $nt ) ) {
702 if ( !( $flags & self
::READ_LATEST
) && isset( self
::$idCacheByName[$name] ) ) {
703 return self
::$idCacheByName[$name];
706 $db = ( $flags & self
::READ_LATEST
)
707 ?
wfGetDB( DB_MASTER
)
708 : wfGetDB( DB_SLAVE
);
713 array( 'user_name' => $nt->getText() ),
717 if ( $s === false ) {
720 $result = $s->user_id
;
723 self
::$idCacheByName[$name] = $result;
725 if ( count( self
::$idCacheByName ) > 1000 ) {
726 self
::$idCacheByName = array();
733 * Reset the cache used in idFromName(). For use in tests.
735 public static function resetIdByNameCache() {
736 self
::$idCacheByName = array();
740 * Does the string match an anonymous IPv4 address?
742 * This function exists for username validation, in order to reject
743 * usernames which are similar in form to IP addresses. Strings such
744 * as 300.300.300.300 will return true because it looks like an IP
745 * address, despite not being strictly valid.
747 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
748 * address because the usemod software would "cloak" anonymous IP
749 * addresses like this, if we allowed accounts like this to be created
750 * new users could get the old edits of these anonymous users.
752 * @param string $name Name to match
755 public static function isIP( $name ) {
756 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
757 || IP
::isIPv6( $name );
761 * Is the input a valid username?
763 * Checks if the input is a valid username, we don't want an empty string,
764 * an IP address, anything that contains slashes (would mess up subpages),
765 * is longer than the maximum allowed username size or doesn't begin with
768 * @param string $name Name to match
771 public static function isValidUserName( $name ) {
772 global $wgContLang, $wgMaxNameChars;
775 || User
::isIP( $name )
776 ||
strpos( $name, '/' ) !== false
777 ||
strlen( $name ) > $wgMaxNameChars
778 ||
$name != $wgContLang->ucfirst( $name )
780 wfDebugLog( 'username', __METHOD__
.
781 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
785 // Ensure that the name can't be misresolved as a different title,
786 // such as with extra namespace keys at the start.
787 $parsed = Title
::newFromText( $name );
788 if ( is_null( $parsed )
789 ||
$parsed->getNamespace()
790 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
791 wfDebugLog( 'username', __METHOD__
.
792 ": '$name' invalid due to ambiguous prefixes" );
796 // Check an additional blacklist of troublemaker characters.
797 // Should these be merged into the title char list?
798 $unicodeBlacklist = '/[' .
799 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
800 '\x{00a0}' . # non-breaking space
801 '\x{2000}-\x{200f}' . # various whitespace
802 '\x{2028}-\x{202f}' . # breaks and control chars
803 '\x{3000}' . # ideographic space
804 '\x{e000}-\x{f8ff}' . # private use
806 if ( preg_match( $unicodeBlacklist, $name ) ) {
807 wfDebugLog( 'username', __METHOD__
.
808 ": '$name' invalid due to blacklisted characters" );
816 * Usernames which fail to pass this function will be blocked
817 * from user login and new account registrations, but may be used
818 * internally by batch processes.
820 * If an account already exists in this form, login will be blocked
821 * by a failure to pass this function.
823 * @param string $name Name to match
826 public static function isUsableName( $name ) {
827 global $wgReservedUsernames;
828 // Must be a valid username, obviously ;)
829 if ( !self
::isValidUserName( $name ) ) {
833 static $reservedUsernames = false;
834 if ( !$reservedUsernames ) {
835 $reservedUsernames = $wgReservedUsernames;
836 Hooks
::run( 'UserGetReservedNames', array( &$reservedUsernames ) );
839 // Certain names may be reserved for batch processes.
840 foreach ( $reservedUsernames as $reserved ) {
841 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
842 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
844 if ( $reserved == $name ) {
852 * Usernames which fail to pass this function will be blocked
853 * from new account registrations, but may be used internally
854 * either by batch processes or by user accounts which have
855 * already been created.
857 * Additional blacklisting may be added here rather than in
858 * isValidUserName() to avoid disrupting existing accounts.
860 * @param string $name String to match
863 public static function isCreatableName( $name ) {
864 global $wgInvalidUsernameCharacters;
866 // Ensure that the username isn't longer than 235 bytes, so that
867 // (at least for the builtin skins) user javascript and css files
868 // will work. (bug 23080)
869 if ( strlen( $name ) > 235 ) {
870 wfDebugLog( 'username', __METHOD__
.
871 ": '$name' invalid due to length" );
875 // Preg yells if you try to give it an empty string
876 if ( $wgInvalidUsernameCharacters !== '' ) {
877 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
878 wfDebugLog( 'username', __METHOD__
.
879 ": '$name' invalid due to wgInvalidUsernameCharacters" );
884 return self
::isUsableName( $name );
888 * Is the input a valid password for this user?
890 * @param string $password Desired password
893 public function isValidPassword( $password ) {
894 // simple boolean wrapper for getPasswordValidity
895 return $this->getPasswordValidity( $password ) === true;
899 * Given unvalidated password input, return error message on failure.
901 * @param string $password Desired password
902 * @return bool|string|array True on success, string or array of error message on failure
904 public function getPasswordValidity( $password ) {
905 $result = $this->checkPasswordValidity( $password );
906 if ( $result->isGood() ) {
910 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
911 $messages[] = $error['message'];
913 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
914 $messages[] = $warning['message'];
916 if ( count( $messages ) === 1 ) {
924 * Check if this is a valid password for this user
926 * Create a Status object based on the password's validity.
927 * The Status should be set to fatal if the user should not
928 * be allowed to log in, and should have any errors that
929 * would block changing the password.
931 * If the return value of this is not OK, the password
932 * should not be checked. If the return value is not Good,
933 * the password can be checked, but the user should not be
934 * able to set their password to this.
936 * @param string $password Desired password
937 * @param string $purpose one of 'login', 'create', 'reset'
941 public function checkPasswordValidity( $password, $purpose = 'login' ) {
942 global $wgPasswordPolicy;
944 $upp = new UserPasswordPolicy(
945 $wgPasswordPolicy['policies'],
946 $wgPasswordPolicy['checks']
949 $status = Status
::newGood();
950 $result = false; // init $result to false for the internal checks
952 if ( !Hooks
::run( 'isValidPassword', array( $password, &$result, $this ) ) ) {
953 $status->error( $result );
957 if ( $result === false ) {
958 $status->merge( $upp->checkUserPassword( $this, $password, $purpose ) );
960 } elseif ( $result === true ) {
963 $status->error( $result );
964 return $status; // the isValidPassword hook set a string $result and returned true
969 * Given unvalidated user input, return a canonical username, or false if
970 * the username is invalid.
971 * @param string $name User input
972 * @param string|bool $validate Type of validation to use:
973 * - false No validation
974 * - 'valid' Valid for batch processes
975 * - 'usable' Valid for batch processes and login
976 * - 'creatable' Valid for batch processes, login and account creation
978 * @throws InvalidArgumentException
979 * @return bool|string
981 public static function getCanonicalName( $name, $validate = 'valid' ) {
982 // Force usernames to capital
984 $name = $wgContLang->ucfirst( $name );
986 # Reject names containing '#'; these will be cleaned up
987 # with title normalisation, but then it's too late to
989 if ( strpos( $name, '#' ) !== false ) {
993 // Clean up name according to title rules,
994 // but only when validation is requested (bug 12654)
995 $t = ( $validate !== false ) ?
996 Title
::newFromText( $name ) : Title
::makeTitle( NS_USER
, $name );
997 // Check for invalid titles
998 if ( is_null( $t ) ) {
1002 // Reject various classes of invalid names
1004 $name = $wgAuth->getCanonicalName( $t->getText() );
1006 switch ( $validate ) {
1010 if ( !User
::isValidUserName( $name ) ) {
1015 if ( !User
::isUsableName( $name ) ) {
1020 if ( !User
::isCreatableName( $name ) ) {
1025 throw new InvalidArgumentException(
1026 'Invalid parameter value for $validate in ' . __METHOD__
);
1032 * Count the number of edits of a user
1034 * @param int $uid User ID to check
1035 * @return int The user's edit count
1037 * @deprecated since 1.21 in favour of User::getEditCount
1039 public static function edits( $uid ) {
1040 wfDeprecated( __METHOD__
, '1.21' );
1041 $user = self
::newFromId( $uid );
1042 return $user->getEditCount();
1046 * Return a random password.
1048 * @deprecated since 1.27, use PasswordFactory::generateRandomPasswordString()
1049 * @return string New random password
1051 public static function randomPassword() {
1052 global $wgMinimalPasswordLength;
1053 return PasswordFactory
::generateRandomPasswordString( $wgMinimalPasswordLength );
1057 * Set cached properties to default.
1059 * @note This no longer clears uncached lazy-initialised properties;
1060 * the constructor does that instead.
1062 * @param string|bool $name
1064 public function loadDefaults( $name = false ) {
1066 $this->mName
= $name;
1067 $this->mRealName
= '';
1069 $this->mOptionOverrides
= null;
1070 $this->mOptionsLoaded
= false;
1072 $loggedOut = $this->getRequest()->getCookie( 'LoggedOut' );
1073 if ( $loggedOut !== null ) {
1074 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1076 $this->mTouched
= '1'; # Allow any pages to be cached
1079 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1080 $this->mEmailAuthenticated
= null;
1081 $this->mEmailToken
= '';
1082 $this->mEmailTokenExpires
= null;
1083 $this->mRegistration
= wfTimestamp( TS_MW
);
1084 $this->mGroups
= array();
1086 Hooks
::run( 'UserLoadDefaults', array( $this, $name ) );
1090 * Return whether an item has been loaded.
1092 * @param string $item Item to check. Current possibilities:
1096 * @param string $all 'all' to check if the whole object has been loaded
1097 * or any other string to check if only the item is available (e.g.
1101 public function isItemLoaded( $item, $all = 'all' ) {
1102 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1103 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1107 * Set that an item has been loaded
1109 * @param string $item
1111 protected function setItemLoaded( $item ) {
1112 if ( is_array( $this->mLoadedItems
) ) {
1113 $this->mLoadedItems
[$item] = true;
1118 * Load user data from the session or login cookie.
1120 * @return bool True if the user is logged in, false otherwise.
1122 private function loadFromSession() {
1124 Hooks
::run( 'UserLoadFromSession', array( $this, &$result ) );
1125 if ( $result !== null ) {
1129 $request = $this->getRequest();
1131 $cookieId = $request->getCookie( 'UserID' );
1132 $sessId = $request->getSessionData( 'wsUserID' );
1134 if ( $cookieId !== null ) {
1135 $sId = intval( $cookieId );
1136 if ( $sessId !== null && $cookieId != $sessId ) {
1137 wfDebugLog( 'loginSessions', "Session user ID ($sessId) and
1138 cookie user ID ($sId) don't match!" );
1141 $request->setSessionData( 'wsUserID', $sId );
1142 } elseif ( $sessId !== null && $sessId != 0 ) {
1148 if ( $request->getSessionData( 'wsUserName' ) !== null ) {
1149 $sName = $request->getSessionData( 'wsUserName' );
1150 } elseif ( $request->getCookie( 'UserName' ) !== null ) {
1151 $sName = $request->getCookie( 'UserName' );
1152 $request->setSessionData( 'wsUserName', $sName );
1157 $proposedUser = User
::newFromId( $sId );
1158 if ( !$proposedUser->isLoggedIn() ) {
1163 global $wgBlockDisablesLogin;
1164 if ( $wgBlockDisablesLogin && $proposedUser->isBlocked() ) {
1165 // User blocked and we've disabled blocked user logins
1169 if ( $request->getSessionData( 'wsToken' ) ) {
1171 ( $proposedUser->getToken( false ) === $request->getSessionData( 'wsToken' ) );
1173 } elseif ( $request->getCookie( 'Token' ) ) {
1174 # Get the token from DB/cache and clean it up to remove garbage padding.
1175 # This deals with historical problems with bugs and the default column value.
1176 $token = rtrim( $proposedUser->getToken( false ) ); // correct token
1177 // Make comparison in constant time (bug 61346)
1178 $passwordCorrect = strlen( $token )
1179 && hash_equals( $token, $request->getCookie( 'Token' ) );
1182 // No session or persistent login cookie
1186 if ( ( $sName === $proposedUser->getName() ) && $passwordCorrect ) {
1187 $this->loadFromUserObject( $proposedUser );
1188 $request->setSessionData( 'wsToken', $this->mToken
);
1189 wfDebug( "User: logged in from $from\n" );
1192 // Invalid credentials
1193 wfDebug( "User: can't log in from $from, invalid credentials\n" );
1199 * Load user and user_group data from the database.
1200 * $this->mId must be set, this is how the user is identified.
1202 * @param integer $flags User::READ_* constant bitfield
1203 * @return bool True if the user exists, false if the user is anonymous
1205 public function loadFromDatabase( $flags = self
::READ_LATEST
) {
1207 $this->mId
= intval( $this->mId
);
1210 if ( !$this->mId
) {
1211 $this->loadDefaults();
1215 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
1216 $db = wfGetDB( $index );
1218 $s = $db->selectRow(
1220 self
::selectFields(),
1221 array( 'user_id' => $this->mId
),
1226 $this->queryFlagsUsed
= $flags;
1227 Hooks
::run( 'UserLoadFromDatabase', array( $this, &$s ) );
1229 if ( $s !== false ) {
1230 // Initialise user table data
1231 $this->loadFromRow( $s );
1232 $this->mGroups
= null; // deferred
1233 $this->getEditCount(); // revalidation for nulls
1238 $this->loadDefaults();
1244 * Initialize this object from a row from the user table.
1246 * @param stdClass $row Row from the user table to load.
1247 * @param array $data Further user data to load into the object
1249 * user_groups Array with groups out of the user_groups table
1250 * user_properties Array with properties out of the user_properties table
1252 protected function loadFromRow( $row, $data = null ) {
1255 $this->mGroups
= null; // deferred
1257 if ( isset( $row->user_name
) ) {
1258 $this->mName
= $row->user_name
;
1259 $this->mFrom
= 'name';
1260 $this->setItemLoaded( 'name' );
1265 if ( isset( $row->user_real_name
) ) {
1266 $this->mRealName
= $row->user_real_name
;
1267 $this->setItemLoaded( 'realname' );
1272 if ( isset( $row->user_id
) ) {
1273 $this->mId
= intval( $row->user_id
);
1274 $this->mFrom
= 'id';
1275 $this->setItemLoaded( 'id' );
1280 if ( isset( $row->user_id
) && isset( $row->user_name
) ) {
1281 self
::$idCacheByName[$row->user_name
] = $row->user_id
;
1284 if ( isset( $row->user_editcount
) ) {
1285 $this->mEditCount
= $row->user_editcount
;
1290 if ( isset( $row->user_email
) ) {
1291 $this->mEmail
= $row->user_email
;
1292 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1293 $this->mToken
= $row->user_token
;
1294 if ( $this->mToken
== '' ) {
1295 $this->mToken
= null;
1297 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1298 $this->mEmailToken
= $row->user_email_token
;
1299 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1300 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1306 $this->mLoadedItems
= true;
1309 if ( is_array( $data ) ) {
1310 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1311 $this->mGroups
= $data['user_groups'];
1313 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1314 $this->loadOptions( $data['user_properties'] );
1320 * Load the data for this user object from another user object.
1324 protected function loadFromUserObject( $user ) {
1326 $user->loadGroups();
1327 $user->loadOptions();
1328 foreach ( self
::$mCacheVars as $var ) {
1329 $this->$var = $user->$var;
1334 * Load the groups from the database if they aren't already loaded.
1336 private function loadGroups() {
1337 if ( is_null( $this->mGroups
) ) {
1338 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
1339 ?
wfGetDB( DB_MASTER
)
1340 : wfGetDB( DB_SLAVE
);
1341 $res = $db->select( 'user_groups',
1342 array( 'ug_group' ),
1343 array( 'ug_user' => $this->mId
),
1345 $this->mGroups
= array();
1346 foreach ( $res as $row ) {
1347 $this->mGroups
[] = $row->ug_group
;
1353 * Add the user to the group if he/she meets given criteria.
1355 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1356 * possible to remove manually via Special:UserRights. In such case it
1357 * will not be re-added automatically. The user will also not lose the
1358 * group if they no longer meet the criteria.
1360 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1362 * @return array Array of groups the user has been promoted to.
1364 * @see $wgAutopromoteOnce
1366 public function addAutopromoteOnceGroups( $event ) {
1367 global $wgAutopromoteOnceLogInRC, $wgAuth;
1369 if ( wfReadOnly() ||
!$this->getId() ) {
1373 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1374 if ( !count( $toPromote ) ) {
1378 if ( !$this->checkAndSetTouched() ) {
1379 return array(); // raced out (bug T48834)
1382 $oldGroups = $this->getGroups(); // previous groups
1383 foreach ( $toPromote as $group ) {
1384 $this->addGroup( $group );
1386 // update groups in external authentication database
1387 Hooks
::run( 'UserGroupsChanged', array( $this, $toPromote, array(), false ) );
1388 $wgAuth->updateExternalDBGroups( $this, $toPromote );
1390 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1392 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1393 $logEntry->setPerformer( $this );
1394 $logEntry->setTarget( $this->getUserPage() );
1395 $logEntry->setParameters( array(
1396 '4::oldgroups' => $oldGroups,
1397 '5::newgroups' => $newGroups,
1399 $logid = $logEntry->insert();
1400 if ( $wgAutopromoteOnceLogInRC ) {
1401 $logEntry->publish( $logid );
1408 * Bump user_touched if it didn't change since this object was loaded
1410 * On success, the mTouched field is updated.
1411 * The user serialization cache is always cleared.
1413 * @return bool Whether user_touched was actually updated
1416 protected function checkAndSetTouched() {
1419 if ( !$this->mId
) {
1420 return false; // anon
1423 // Get a new user_touched that is higher than the old one
1424 $oldTouched = $this->mTouched
;
1425 $newTouched = $this->newTouchedTimestamp();
1427 $dbw = wfGetDB( DB_MASTER
);
1428 $dbw->update( 'user',
1429 array( 'user_touched' => $dbw->timestamp( $newTouched ) ),
1431 'user_id' => $this->mId
,
1432 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
1436 $success = ( $dbw->affectedRows() > 0 );
1439 $this->mTouched
= $newTouched;
1440 $this->clearSharedCache();
1442 // Clears on failure too since that is desired if the cache is stale
1443 $this->clearSharedCache( 'refresh' );
1450 * Clear various cached data stored in this object. The cache of the user table
1451 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1453 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1454 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1456 public function clearInstanceCache( $reloadFrom = false ) {
1457 $this->mNewtalk
= -1;
1458 $this->mDatePreference
= null;
1459 $this->mBlockedby
= -1; # Unset
1460 $this->mHash
= false;
1461 $this->mRights
= null;
1462 $this->mEffectiveGroups
= null;
1463 $this->mImplicitGroups
= null;
1464 $this->mGroups
= null;
1465 $this->mOptions
= null;
1466 $this->mOptionsLoaded
= false;
1467 $this->mEditCount
= null;
1469 if ( $reloadFrom ) {
1470 $this->mLoadedItems
= array();
1471 $this->mFrom
= $reloadFrom;
1476 * Combine the language default options with any site-specific options
1477 * and add the default language variants.
1479 * @return array Array of String options
1481 public static function getDefaultOptions() {
1482 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1484 static $defOpt = null;
1485 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1486 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1487 // mid-request and see that change reflected in the return value of this function.
1488 // Which is insane and would never happen during normal MW operation
1492 $defOpt = $wgDefaultUserOptions;
1493 // Default language setting
1494 $defOpt['language'] = $wgContLang->getCode();
1495 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1496 $defOpt[$langCode == $wgContLang->getCode() ?
'variant' : "variant-$langCode"] = $langCode;
1498 foreach ( SearchEngine
::searchableNamespaces() as $nsnum => $nsname ) {
1499 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1501 $defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1503 Hooks
::run( 'UserGetDefaultOptions', array( &$defOpt ) );
1509 * Get a given default option value.
1511 * @param string $opt Name of option to retrieve
1512 * @return string Default option value
1514 public static function getDefaultOption( $opt ) {
1515 $defOpts = self
::getDefaultOptions();
1516 if ( isset( $defOpts[$opt] ) ) {
1517 return $defOpts[$opt];
1524 * Get blocking information
1525 * @param bool $bFromSlave Whether to check the slave database first.
1526 * To improve performance, non-critical checks are done against slaves.
1527 * Check when actually saving should be done against master.
1529 private function getBlockedStatus( $bFromSlave = true ) {
1530 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1532 if ( -1 != $this->mBlockedby
) {
1536 wfDebug( __METHOD__
. ": checking...\n" );
1538 // Initialize data...
1539 // Otherwise something ends up stomping on $this->mBlockedby when
1540 // things get lazy-loaded later, causing false positive block hits
1541 // due to -1 !== 0. Probably session-related... Nothing should be
1542 // overwriting mBlockedby, surely?
1545 # We only need to worry about passing the IP address to the Block generator if the
1546 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1547 # know which IP address they're actually coming from
1548 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->equals( $wgUser ) ) {
1549 $ip = $this->getRequest()->getIP();
1555 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1558 if ( !$block instanceof Block
&& $ip !== null && !$this->isAllowed( 'proxyunbannable' )
1559 && !in_array( $ip, $wgProxyWhitelist )
1562 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1564 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1565 $block->mReason
= wfMessage( 'proxyblockreason' )->text();
1566 $block->setTarget( $ip );
1567 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1569 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1570 $block->mReason
= wfMessage( 'sorbsreason' )->text();
1571 $block->setTarget( $ip );
1575 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1576 if ( !$block instanceof Block
1577 && $wgApplyIpBlocksToXff
1579 && !$this->isAllowed( 'proxyunbannable' )
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();
1764 if ( isset( $limits['anon'] ) && $id == 0 ) {
1765 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1768 if ( isset( $limits['user'] ) && $id != 0 ) {
1769 $userLimit = $limits['user'];
1771 if ( $this->isNewbie() ) {
1772 if ( isset( $limits['newbie'] ) && $id != 0 ) {
1773 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1775 if ( isset( $limits['ip'] ) ) {
1776 $ip = $this->getRequest()->getIP();
1777 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1779 if ( isset( $limits['subnet'] ) ) {
1780 $ip = $this->getRequest()->getIP();
1783 if ( IP
::isIPv6( $ip ) ) {
1784 $parts = IP
::parseRange( "$ip/64" );
1785 $subnet = $parts[0];
1786 } elseif ( preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1788 $subnet = $matches[1];
1790 if ( $subnet !== false ) {
1791 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1795 // Check for group-specific permissions
1796 // If more than one group applies, use the group with the highest limit
1797 foreach ( $this->getGroups() as $group ) {
1798 if ( isset( $limits[$group] ) ) {
1799 if ( $userLimit === false
1800 ||
$limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1802 $userLimit = $limits[$group];
1806 // Set the user limit key
1807 if ( $userLimit !== false ) {
1808 list( $max, $period ) = $userLimit;
1809 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
1810 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1813 $cache = ObjectCache
::getLocalClusterInstance();
1816 foreach ( $keys as $key => $limit ) {
1817 list( $max, $period ) = $limit;
1818 $summary = "(limit $max in {$period}s)";
1819 $count = $cache->get( $key );
1822 if ( $count >= $max ) {
1823 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1824 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1827 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1830 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1831 if ( $incrBy > 0 ) {
1832 $cache->add( $key, 0, intval( $period ) ); // first ping
1835 if ( $incrBy > 0 ) {
1836 $cache->incr( $key, $incrBy );
1844 * Check if user is blocked
1846 * @param bool $bFromSlave Whether to check the slave database instead of
1847 * the master. Hacked from false due to horrible probs on site.
1848 * @return bool True if blocked, false otherwise
1850 public function isBlocked( $bFromSlave = true ) {
1851 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
1855 * Get the block affecting the user, or null if the user is not blocked
1857 * @param bool $bFromSlave Whether to check the slave database instead of the master
1858 * @return Block|null
1860 public function getBlock( $bFromSlave = true ) {
1861 $this->getBlockedStatus( $bFromSlave );
1862 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
1866 * Check if user is blocked from editing a particular article
1868 * @param Title $title Title to check
1869 * @param bool $bFromSlave Whether to check the slave database instead of the master
1872 public function isBlockedFrom( $title, $bFromSlave = false ) {
1873 global $wgBlockAllowsUTEdit;
1875 $blocked = $this->isBlocked( $bFromSlave );
1876 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
1877 // If a user's name is suppressed, they cannot make edits anywhere
1878 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName()
1879 && $title->getNamespace() == NS_USER_TALK
) {
1881 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
1884 Hooks
::run( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1890 * If user is blocked, return the name of the user who placed the block
1891 * @return string Name of blocker
1893 public function blockedBy() {
1894 $this->getBlockedStatus();
1895 return $this->mBlockedby
;
1899 * If user is blocked, return the specified reason for the block
1900 * @return string Blocking reason
1902 public function blockedFor() {
1903 $this->getBlockedStatus();
1904 return $this->mBlockreason
;
1908 * If user is blocked, return the ID for the block
1909 * @return int Block ID
1911 public function getBlockId() {
1912 $this->getBlockedStatus();
1913 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
1917 * Check if user is blocked on all wikis.
1918 * Do not use for actual edit permission checks!
1919 * This is intended for quick UI checks.
1921 * @param string $ip IP address, uses current client if none given
1922 * @return bool True if blocked, false otherwise
1924 public function isBlockedGlobally( $ip = '' ) {
1925 if ( $this->mBlockedGlobally
!== null ) {
1926 return $this->mBlockedGlobally
;
1928 // User is already an IP?
1929 if ( IP
::isIPAddress( $this->getName() ) ) {
1930 $ip = $this->getName();
1932 $ip = $this->getRequest()->getIP();
1935 Hooks
::run( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1936 $this->mBlockedGlobally
= (bool)$blocked;
1937 return $this->mBlockedGlobally
;
1941 * Check if user account is locked
1943 * @return bool True if locked, false otherwise
1945 public function isLocked() {
1946 if ( $this->mLocked
!== null ) {
1947 return $this->mLocked
;
1950 $authUser = $wgAuth->getUserInstance( $this );
1951 $this->mLocked
= (bool)$authUser->isLocked();
1952 Hooks
::run( 'UserIsLocked', array( $this, &$this->mLocked
) );
1953 return $this->mLocked
;
1957 * Check if user account is hidden
1959 * @return bool True if hidden, false otherwise
1961 public function isHidden() {
1962 if ( $this->mHideName
!== null ) {
1963 return $this->mHideName
;
1965 $this->getBlockedStatus();
1966 if ( !$this->mHideName
) {
1968 $authUser = $wgAuth->getUserInstance( $this );
1969 $this->mHideName
= (bool)$authUser->isHidden();
1970 Hooks
::run( 'UserIsHidden', array( $this, &$this->mHideName
) );
1972 return $this->mHideName
;
1976 * Get the user's ID.
1977 * @return int The user's ID; 0 if the user is anonymous or nonexistent
1979 public function getId() {
1980 if ( $this->mId
=== null && $this->mName
!== null && User
::isIP( $this->mName
) ) {
1981 // Special case, we know the user is anonymous
1983 } elseif ( !$this->isItemLoaded( 'id' ) ) {
1984 // Don't load if this was initialized from an ID
1991 * Set the user and reload all fields according to a given ID
1992 * @param int $v User ID to reload
1994 public function setId( $v ) {
1996 $this->clearInstanceCache( 'id' );
2000 * Get the user name, or the IP of an anonymous user
2001 * @return string User's name or IP address
2003 public function getName() {
2004 if ( $this->isItemLoaded( 'name', 'only' ) ) {
2005 // Special case optimisation
2006 return $this->mName
;
2009 if ( $this->mName
=== false ) {
2011 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
2013 return $this->mName
;
2018 * Set the user name.
2020 * This does not reload fields from the database according to the given
2021 * name. Rather, it is used to create a temporary "nonexistent user" for
2022 * later addition to the database. It can also be used to set the IP
2023 * address for an anonymous user to something other than the current
2026 * @note User::newFromName() has roughly the same function, when the named user
2028 * @param string $str New user name to set
2030 public function setName( $str ) {
2032 $this->mName
= $str;
2036 * Get the user's name escaped by underscores.
2037 * @return string Username escaped by underscores.
2039 public function getTitleKey() {
2040 return str_replace( ' ', '_', $this->getName() );
2044 * Check if the user has new messages.
2045 * @return bool True if the user has new messages
2047 public function getNewtalk() {
2050 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2051 if ( $this->mNewtalk
=== -1 ) {
2052 $this->mNewtalk
= false; # reset talk page status
2054 // Check memcached separately for anons, who have no
2055 // entire User object stored in there.
2056 if ( !$this->mId
) {
2057 global $wgDisableAnonTalk;
2058 if ( $wgDisableAnonTalk ) {
2059 // Anon newtalk disabled by configuration.
2060 $this->mNewtalk
= false;
2062 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
2065 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2069 return (bool)$this->mNewtalk
;
2073 * Return the data needed to construct links for new talk page message
2074 * alerts. If there are new messages, this will return an associative array
2075 * with the following data:
2076 * wiki: The database name of the wiki
2077 * link: Root-relative link to the user's talk page
2078 * rev: The last talk page revision that the user has seen or null. This
2079 * is useful for building diff links.
2080 * If there are no new messages, it returns an empty array.
2081 * @note This function was designed to accomodate multiple talk pages, but
2082 * currently only returns a single link and revision.
2085 public function getNewMessageLinks() {
2087 if ( !Hooks
::run( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) ) {
2089 } elseif ( !$this->getNewtalk() ) {
2092 $utp = $this->getTalkPage();
2093 $dbr = wfGetDB( DB_SLAVE
);
2094 // Get the "last viewed rev" timestamp from the oldest message notification
2095 $timestamp = $dbr->selectField( 'user_newtalk',
2096 'MIN(user_last_timestamp)',
2097 $this->isAnon() ?
array( 'user_ip' => $this->getName() ) : array( 'user_id' => $this->getID() ),
2099 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2100 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ) );
2104 * Get the revision ID for the last talk page revision viewed by the talk
2106 * @return int|null Revision ID or null
2108 public function getNewMessageRevisionId() {
2109 $newMessageRevisionId = null;
2110 $newMessageLinks = $this->getNewMessageLinks();
2111 if ( $newMessageLinks ) {
2112 // Note: getNewMessageLinks() never returns more than a single link
2113 // and it is always for the same wiki, but we double-check here in
2114 // case that changes some time in the future.
2115 if ( count( $newMessageLinks ) === 1
2116 && $newMessageLinks[0]['wiki'] === wfWikiID()
2117 && $newMessageLinks[0]['rev']
2119 /** @var Revision $newMessageRevision */
2120 $newMessageRevision = $newMessageLinks[0]['rev'];
2121 $newMessageRevisionId = $newMessageRevision->getId();
2124 return $newMessageRevisionId;
2128 * Internal uncached check for new messages
2131 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2132 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2133 * @return bool True if the user has new messages
2135 protected function checkNewtalk( $field, $id ) {
2136 $dbr = wfGetDB( DB_SLAVE
);
2138 $ok = $dbr->selectField( 'user_newtalk', $field, array( $field => $id ), __METHOD__
);
2140 return $ok !== false;
2144 * Add or update the new messages flag
2145 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2146 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2147 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2148 * @return bool True if successful, false otherwise
2150 protected function updateNewtalk( $field, $id, $curRev = null ) {
2151 // Get timestamp of the talk page revision prior to the current one
2152 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2153 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2154 // Mark the user as having new messages since this revision
2155 $dbw = wfGetDB( DB_MASTER
);
2156 $dbw->insert( 'user_newtalk',
2157 array( $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ),
2160 if ( $dbw->affectedRows() ) {
2161 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2164 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2170 * Clear the new messages flag for the given user
2171 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2172 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2173 * @return bool True if successful, false otherwise
2175 protected function deleteNewtalk( $field, $id ) {
2176 $dbw = wfGetDB( DB_MASTER
);
2177 $dbw->delete( 'user_newtalk',
2178 array( $field => $id ),
2180 if ( $dbw->affectedRows() ) {
2181 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2184 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2190 * Update the 'You have new messages!' status.
2191 * @param bool $val Whether the user has new messages
2192 * @param Revision $curRev New, as yet unseen revision of the user talk
2193 * page. Ignored if null or !$val.
2195 public function setNewtalk( $val, $curRev = null ) {
2196 if ( wfReadOnly() ) {
2201 $this->mNewtalk
= $val;
2203 if ( $this->isAnon() ) {
2205 $id = $this->getName();
2208 $id = $this->getId();
2212 $changed = $this->updateNewtalk( $field, $id, $curRev );
2214 $changed = $this->deleteNewtalk( $field, $id );
2218 $this->invalidateCache();
2223 * Generate a current or new-future timestamp to be stored in the
2224 * user_touched field when we update things.
2225 * @return string Timestamp in TS_MW format
2227 private function newTouchedTimestamp() {
2228 global $wgClockSkewFudge;
2230 $time = wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2231 if ( $this->mTouched
&& $time <= $this->mTouched
) {
2232 $time = wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $this->mTouched
) +
1 );
2239 * Clear user data from memcached
2241 * Use after applying updates to the database; caller's
2242 * responsibility to update user_touched if appropriate.
2244 * Called implicitly from invalidateCache() and saveSettings().
2246 * @param string $mode Use 'refresh' to clear now; otherwise before DB commit
2248 public function clearSharedCache( $mode = 'changed' ) {
2249 if ( !$this->getId() ) {
2253 $cache = ObjectCache
::getMainWANInstance();
2254 $key = $this->getCacheKey( $cache );
2255 if ( $mode === 'refresh' ) {
2256 $cache->delete( $key, 1 );
2258 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle( function() use ( $cache, $key ) {
2259 $cache->delete( $key );
2265 * Immediately touch the user data cache for this account
2267 * Calls touch() and removes account data from memcached
2269 public function invalidateCache() {
2271 $this->clearSharedCache();
2275 * Update the "touched" timestamp for the user
2277 * This is useful on various login/logout events when making sure that
2278 * a browser or proxy that has multiple tenants does not suffer cache
2279 * pollution where the new user sees the old users content. The value
2280 * of getTouched() is checked when determining 304 vs 200 responses.
2281 * Unlike invalidateCache(), this preserves the User object cache and
2282 * avoids database writes.
2286 public function touch() {
2287 $id = $this->getId();
2289 $key = wfMemcKey( 'user-quicktouched', 'id', $id );
2290 ObjectCache
::getMainWANInstance()->touchCheckKey( $key );
2291 $this->mQuickTouched
= null;
2296 * Validate the cache for this account.
2297 * @param string $timestamp A timestamp in TS_MW format
2300 public function validateCache( $timestamp ) {
2301 return ( $timestamp >= $this->getTouched() );
2305 * Get the user touched timestamp
2307 * Use this value only to validate caches via inequalities
2308 * such as in the case of HTTP If-Modified-Since response logic
2310 * @return string TS_MW Timestamp
2312 public function getTouched() {
2316 if ( $this->mQuickTouched
=== null ) {
2317 $key = wfMemcKey( 'user-quicktouched', 'id', $this->mId
);
2318 $cache = ObjectCache
::getMainWANInstance();
2320 $this->mQuickTouched
= wfTimestamp( TS_MW
, $cache->getCheckKeyTime( $key ) );
2323 return max( $this->mTouched
, $this->mQuickTouched
);
2326 return $this->mTouched
;
2330 * Get the user_touched timestamp field (time of last DB updates)
2331 * @return string TS_MW Timestamp
2334 public function getDBTouched() {
2337 return $this->mTouched
;
2341 * @deprecated Removed in 1.27.
2345 public function getPassword() {
2346 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2350 * @deprecated Removed in 1.27.
2354 public function getTemporaryPassword() {
2355 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2359 * Set the password and reset the random token.
2360 * Calls through to authentication plugin if necessary;
2361 * will have no effect if the auth plugin refuses to
2362 * pass the change through or if the legal password
2365 * As a special case, setting the password to null
2366 * wipes it, so the account cannot be logged in until
2367 * a new password is set, for instance via e-mail.
2369 * @deprecated since 1.27. AuthManager is coming.
2370 * @param string $str New password to set
2371 * @throws PasswordError On failure
2374 public function setPassword( $str ) {
2377 if ( $str !== null ) {
2378 if ( !$wgAuth->allowPasswordChange() ) {
2379 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2382 $status = $this->checkPasswordValidity( $str );
2383 if ( !$status->isGood() ) {
2384 throw new PasswordError( $status->getMessage()->text() );
2388 if ( !$wgAuth->setPassword( $this, $str ) ) {
2389 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2393 $this->setOption( 'watchlisttoken', false );
2394 $this->setPasswordInternal( $str );
2400 * Set the password and reset the random token unconditionally.
2402 * @deprecated since 1.27. AuthManager is coming.
2403 * @param string|null $str New password to set or null to set an invalid
2404 * password hash meaning that the user will not be able to log in
2405 * through the web interface.
2407 public function setInternalPassword( $str ) {
2410 if ( $wgAuth->allowSetLocalPassword() ) {
2412 $this->setOption( 'watchlisttoken', false );
2413 $this->setPasswordInternal( $str );
2418 * Actually set the password and such
2419 * @since 1.27 cannot set a password for a user not in the database
2420 * @param string|null $str New password to set or null to set an invalid
2421 * password hash meaning that the user will not be able to log in
2422 * through the web interface.
2424 private function setPasswordInternal( $str ) {
2425 $id = self
::idFromName( $this->getName(), self
::READ_LATEST
);
2427 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2430 $passwordFactory = new PasswordFactory();
2431 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
2432 $dbw = wfGetDB( DB_MASTER
);
2436 'user_password' => $passwordFactory->newFromPlaintext( $str )->toString(),
2437 'user_newpassword' => PasswordFactory
::newInvalidPassword()->toString(),
2438 'user_newpass_time' => $dbw->timestampOrNull( null ),
2448 * Get the user's current token.
2449 * @param bool $forceCreation Force the generation of a new token if the
2450 * user doesn't have one (default=true for backwards compatibility).
2451 * @return string Token
2453 public function getToken( $forceCreation = true ) {
2455 if ( !$this->mToken
&& $forceCreation ) {
2458 return $this->mToken
;
2462 * Set the random token (used for persistent authentication)
2463 * Called from loadDefaults() among other places.
2465 * @param string|bool $token If specified, set the token to this value
2467 public function setToken( $token = false ) {
2470 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2472 $this->mToken
= $token;
2477 * Set the password for a password reminder or new account email
2479 * @deprecated since 1.27, AuthManager is coming
2480 * @param string $str New password to set or null to set an invalid
2481 * password hash meaning that the user will not be able to use it
2482 * @param bool $throttle If true, reset the throttle timestamp to the present
2484 public function setNewpassword( $str, $throttle = true ) {
2485 $id = $this->getId();
2487 throw new LogicException( 'Cannot set new password for a user that is not in the database.' );
2490 $dbw = wfGetDB( DB_MASTER
);
2492 $passwordFactory = new PasswordFactory();
2493 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
2495 'user_newpassword' => $passwordFactory->newFromPlaintext( $str )->toString(),
2498 if ( $str === null ) {
2499 $update['user_newpass_time'] = null;
2500 } elseif ( $throttle ) {
2501 $update['user_newpass_time'] = $dbw->timestamp();
2504 $dbw->update( 'user', $update, array( 'user_id' => $id ), __METHOD__
);
2508 * Has password reminder email been sent within the last
2509 * $wgPasswordReminderResendTime hours?
2512 public function isPasswordReminderThrottled() {
2513 global $wgPasswordReminderResendTime;
2515 if ( !$wgPasswordReminderResendTime ) {
2521 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
2522 ?
wfGetDB( DB_MASTER
)
2523 : wfGetDB( DB_SLAVE
);
2524 $newpassTime = $db->selectField(
2526 'user_newpass_time',
2527 array( 'user_id' => $this->getId() ),
2531 if ( $newpassTime === null ) {
2534 $expiry = wfTimestamp( TS_UNIX
, $newpassTime ) +
$wgPasswordReminderResendTime * 3600;
2535 return time() < $expiry;
2539 * Get the user's e-mail address
2540 * @return string User's email address
2542 public function getEmail() {
2544 Hooks
::run( 'UserGetEmail', array( $this, &$this->mEmail
) );
2545 return $this->mEmail
;
2549 * Get the timestamp of the user's e-mail authentication
2550 * @return string TS_MW timestamp
2552 public function getEmailAuthenticationTimestamp() {
2554 Hooks
::run( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
2555 return $this->mEmailAuthenticated
;
2559 * Set the user's e-mail address
2560 * @param string $str New e-mail address
2562 public function setEmail( $str ) {
2564 if ( $str == $this->mEmail
) {
2567 $this->invalidateEmail();
2568 $this->mEmail
= $str;
2569 Hooks
::run( 'UserSetEmail', array( $this, &$this->mEmail
) );
2573 * Set the user's e-mail address and a confirmation mail if needed.
2576 * @param string $str New e-mail address
2579 public function setEmailWithConfirmation( $str ) {
2580 global $wgEnableEmail, $wgEmailAuthentication;
2582 if ( !$wgEnableEmail ) {
2583 return Status
::newFatal( 'emaildisabled' );
2586 $oldaddr = $this->getEmail();
2587 if ( $str === $oldaddr ) {
2588 return Status
::newGood( true );
2591 $this->setEmail( $str );
2593 if ( $str !== '' && $wgEmailAuthentication ) {
2594 // Send a confirmation request to the new address if needed
2595 $type = $oldaddr != '' ?
'changed' : 'set';
2596 $result = $this->sendConfirmationMail( $type );
2597 if ( $result->isGood() ) {
2598 // Say to the caller that a confirmation mail has been sent
2599 $result->value
= 'eauth';
2602 $result = Status
::newGood( true );
2609 * Get the user's real name
2610 * @return string User's real name
2612 public function getRealName() {
2613 if ( !$this->isItemLoaded( 'realname' ) ) {
2617 return $this->mRealName
;
2621 * Set the user's real name
2622 * @param string $str New real name
2624 public function setRealName( $str ) {
2626 $this->mRealName
= $str;
2630 * Get the user's current setting for a given option.
2632 * @param string $oname The option to check
2633 * @param string $defaultOverride A default value returned if the option does not exist
2634 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2635 * @return string User's current value for the option
2636 * @see getBoolOption()
2637 * @see getIntOption()
2639 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2640 global $wgHiddenPrefs;
2641 $this->loadOptions();
2643 # We want 'disabled' preferences to always behave as the default value for
2644 # users, even if they have set the option explicitly in their settings (ie they
2645 # set it, and then it was disabled removing their ability to change it). But
2646 # we don't want to erase the preferences in the database in case the preference
2647 # is re-enabled again. So don't touch $mOptions, just override the returned value
2648 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2649 return self
::getDefaultOption( $oname );
2652 if ( array_key_exists( $oname, $this->mOptions
) ) {
2653 return $this->mOptions
[$oname];
2655 return $defaultOverride;
2660 * Get all user's options
2662 * @param int $flags Bitwise combination of:
2663 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2664 * to the default value. (Since 1.25)
2667 public function getOptions( $flags = 0 ) {
2668 global $wgHiddenPrefs;
2669 $this->loadOptions();
2670 $options = $this->mOptions
;
2672 # We want 'disabled' preferences to always behave as the default value for
2673 # users, even if they have set the option explicitly in their settings (ie they
2674 # set it, and then it was disabled removing their ability to change it). But
2675 # we don't want to erase the preferences in the database in case the preference
2676 # is re-enabled again. So don't touch $mOptions, just override the returned value
2677 foreach ( $wgHiddenPrefs as $pref ) {
2678 $default = self
::getDefaultOption( $pref );
2679 if ( $default !== null ) {
2680 $options[$pref] = $default;
2684 if ( $flags & self
::GETOPTIONS_EXCLUDE_DEFAULTS
) {
2685 $options = array_diff_assoc( $options, self
::getDefaultOptions() );
2692 * Get the user's current setting for a given option, as a boolean value.
2694 * @param string $oname The option to check
2695 * @return bool User's current value for the option
2698 public function getBoolOption( $oname ) {
2699 return (bool)$this->getOption( $oname );
2703 * Get the user's current setting for a given option, as an integer value.
2705 * @param string $oname The option to check
2706 * @param int $defaultOverride A default value returned if the option does not exist
2707 * @return int User's current value for the option
2710 public function getIntOption( $oname, $defaultOverride = 0 ) {
2711 $val = $this->getOption( $oname );
2713 $val = $defaultOverride;
2715 return intval( $val );
2719 * Set the given option for a user.
2721 * You need to call saveSettings() to actually write to the database.
2723 * @param string $oname The option to set
2724 * @param mixed $val New value to set
2726 public function setOption( $oname, $val ) {
2727 $this->loadOptions();
2729 // Explicitly NULL values should refer to defaults
2730 if ( is_null( $val ) ) {
2731 $val = self
::getDefaultOption( $oname );
2734 $this->mOptions
[$oname] = $val;
2738 * Get a token stored in the preferences (like the watchlist one),
2739 * resetting it if it's empty (and saving changes).
2741 * @param string $oname The option name to retrieve the token from
2742 * @return string|bool User's current value for the option, or false if this option is disabled.
2743 * @see resetTokenFromOption()
2745 * @deprecated 1.26 Applications should use the OAuth extension
2747 public function getTokenFromOption( $oname ) {
2748 global $wgHiddenPrefs;
2750 $id = $this->getId();
2751 if ( !$id ||
in_array( $oname, $wgHiddenPrefs ) ) {
2755 $token = $this->getOption( $oname );
2757 // Default to a value based on the user token to avoid space
2758 // wasted on storing tokens for all users. When this option
2759 // is set manually by the user, only then is it stored.
2760 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
2767 * Reset a token stored in the preferences (like the watchlist one).
2768 * *Does not* save user's preferences (similarly to setOption()).
2770 * @param string $oname The option name to reset the token in
2771 * @return string|bool New token value, or false if this option is disabled.
2772 * @see getTokenFromOption()
2775 public function resetTokenFromOption( $oname ) {
2776 global $wgHiddenPrefs;
2777 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2781 $token = MWCryptRand
::generateHex( 40 );
2782 $this->setOption( $oname, $token );
2787 * Return a list of the types of user options currently returned by
2788 * User::getOptionKinds().
2790 * Currently, the option kinds are:
2791 * - 'registered' - preferences which are registered in core MediaWiki or
2792 * by extensions using the UserGetDefaultOptions hook.
2793 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2794 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2795 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2796 * be used by user scripts.
2797 * - 'special' - "preferences" that are not accessible via User::getOptions
2798 * or User::setOptions.
2799 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2800 * These are usually legacy options, removed in newer versions.
2802 * The API (and possibly others) use this function to determine the possible
2803 * option types for validation purposes, so make sure to update this when a
2804 * new option kind is added.
2806 * @see User::getOptionKinds
2807 * @return array Option kinds
2809 public static function listOptionKinds() {
2812 'registered-multiselect',
2813 'registered-checkmatrix',
2821 * Return an associative array mapping preferences keys to the kind of a preference they're
2822 * used for. Different kinds are handled differently when setting or reading preferences.
2824 * See User::listOptionKinds for the list of valid option types that can be provided.
2826 * @see User::listOptionKinds
2827 * @param IContextSource $context
2828 * @param array $options Assoc. array with options keys to check as keys.
2829 * Defaults to $this->mOptions.
2830 * @return array The key => kind mapping data
2832 public function getOptionKinds( IContextSource
$context, $options = null ) {
2833 $this->loadOptions();
2834 if ( $options === null ) {
2835 $options = $this->mOptions
;
2838 $prefs = Preferences
::getPreferences( $this, $context );
2841 // Pull out the "special" options, so they don't get converted as
2842 // multiselect or checkmatrix.
2843 $specialOptions = array_fill_keys( Preferences
::getSaveBlacklist(), true );
2844 foreach ( $specialOptions as $name => $value ) {
2845 unset( $prefs[$name] );
2848 // Multiselect and checkmatrix options are stored in the database with
2849 // one key per option, each having a boolean value. Extract those keys.
2850 $multiselectOptions = array();
2851 foreach ( $prefs as $name => $info ) {
2852 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2853 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2854 $opts = HTMLFormField
::flattenOptions( $info['options'] );
2855 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2857 foreach ( $opts as $value ) {
2858 $multiselectOptions["$prefix$value"] = true;
2861 unset( $prefs[$name] );
2864 $checkmatrixOptions = array();
2865 foreach ( $prefs as $name => $info ) {
2866 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2867 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2868 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
2869 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
2870 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2872 foreach ( $columns as $column ) {
2873 foreach ( $rows as $row ) {
2874 $checkmatrixOptions["$prefix$column-$row"] = true;
2878 unset( $prefs[$name] );
2882 // $value is ignored
2883 foreach ( $options as $key => $value ) {
2884 if ( isset( $prefs[$key] ) ) {
2885 $mapping[$key] = 'registered';
2886 } elseif ( isset( $multiselectOptions[$key] ) ) {
2887 $mapping[$key] = 'registered-multiselect';
2888 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2889 $mapping[$key] = 'registered-checkmatrix';
2890 } elseif ( isset( $specialOptions[$key] ) ) {
2891 $mapping[$key] = 'special';
2892 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2893 $mapping[$key] = 'userjs';
2895 $mapping[$key] = 'unused';
2903 * Reset certain (or all) options to the site defaults
2905 * The optional parameter determines which kinds of preferences will be reset.
2906 * Supported values are everything that can be reported by getOptionKinds()
2907 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2909 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
2910 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2911 * for backwards-compatibility.
2912 * @param IContextSource|null $context Context source used when $resetKinds
2913 * does not contain 'all', passed to getOptionKinds().
2914 * Defaults to RequestContext::getMain() when null.
2916 public function resetOptions(
2917 $resetKinds = array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ),
2918 IContextSource
$context = null
2921 $defaultOptions = self
::getDefaultOptions();
2923 if ( !is_array( $resetKinds ) ) {
2924 $resetKinds = array( $resetKinds );
2927 if ( in_array( 'all', $resetKinds ) ) {
2928 $newOptions = $defaultOptions;
2930 if ( $context === null ) {
2931 $context = RequestContext
::getMain();
2934 $optionKinds = $this->getOptionKinds( $context );
2935 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
2936 $newOptions = array();
2938 // Use default values for the options that should be deleted, and
2939 // copy old values for the ones that shouldn't.
2940 foreach ( $this->mOptions
as $key => $value ) {
2941 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
2942 if ( array_key_exists( $key, $defaultOptions ) ) {
2943 $newOptions[$key] = $defaultOptions[$key];
2946 $newOptions[$key] = $value;
2951 Hooks
::run( 'UserResetAllOptions', array( $this, &$newOptions, $this->mOptions
, $resetKinds ) );
2953 $this->mOptions
= $newOptions;
2954 $this->mOptionsLoaded
= true;
2958 * Get the user's preferred date format.
2959 * @return string User's preferred date format
2961 public function getDatePreference() {
2962 // Important migration for old data rows
2963 if ( is_null( $this->mDatePreference
) ) {
2965 $value = $this->getOption( 'date' );
2966 $map = $wgLang->getDatePreferenceMigrationMap();
2967 if ( isset( $map[$value] ) ) {
2968 $value = $map[$value];
2970 $this->mDatePreference
= $value;
2972 return $this->mDatePreference
;
2976 * Determine based on the wiki configuration and the user's options,
2977 * whether this user must be over HTTPS no matter what.
2981 public function requiresHTTPS() {
2982 global $wgSecureLogin;
2983 if ( !$wgSecureLogin ) {
2986 $https = $this->getBoolOption( 'prefershttps' );
2987 Hooks
::run( 'UserRequiresHTTPS', array( $this, &$https ) );
2989 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
2996 * Get the user preferred stub threshold
3000 public function getStubThreshold() {
3001 global $wgMaxArticleSize; # Maximum article size, in Kb
3002 $threshold = $this->getIntOption( 'stubthreshold' );
3003 if ( $threshold > $wgMaxArticleSize * 1024 ) {
3004 // If they have set an impossible value, disable the preference
3005 // so we can use the parser cache again.
3012 * Get the permissions this user has.
3013 * @return array Array of String permission names
3015 public function getRights() {
3016 if ( is_null( $this->mRights
) ) {
3017 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
3018 Hooks
::run( 'UserGetRights', array( $this, &$this->mRights
) );
3019 // Force reindexation of rights when a hook has unset one of them
3020 $this->mRights
= array_values( array_unique( $this->mRights
) );
3022 return $this->mRights
;
3026 * Get the list of explicit group memberships this user has.
3027 * The implicit * and user groups are not included.
3028 * @return array Array of String internal group names
3030 public function getGroups() {
3032 $this->loadGroups();
3033 return $this->mGroups
;
3037 * Get the list of implicit group memberships this user has.
3038 * This includes all explicit groups, plus 'user' if logged in,
3039 * '*' for all accounts, and autopromoted groups
3040 * @param bool $recache Whether to avoid the cache
3041 * @return array Array of String internal group names
3043 public function getEffectiveGroups( $recache = false ) {
3044 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
3045 $this->mEffectiveGroups
= array_unique( array_merge(
3046 $this->getGroups(), // explicit groups
3047 $this->getAutomaticGroups( $recache ) // implicit groups
3049 // Hook for additional groups
3050 Hooks
::run( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
3051 // Force reindexation of groups when a hook has unset one of them
3052 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
3054 return $this->mEffectiveGroups
;
3058 * Get the list of implicit group memberships this user has.
3059 * This includes 'user' if logged in, '*' for all accounts,
3060 * and autopromoted groups
3061 * @param bool $recache Whether to avoid the cache
3062 * @return array Array of String internal group names
3064 public function getAutomaticGroups( $recache = false ) {
3065 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
3066 $this->mImplicitGroups
= array( '*' );
3067 if ( $this->getId() ) {
3068 $this->mImplicitGroups
[] = 'user';
3070 $this->mImplicitGroups
= array_unique( array_merge(
3071 $this->mImplicitGroups
,
3072 Autopromote
::getAutopromoteGroups( $this )
3076 // Assure data consistency with rights/groups,
3077 // as getEffectiveGroups() depends on this function
3078 $this->mEffectiveGroups
= null;
3081 return $this->mImplicitGroups
;
3085 * Returns the groups the user has belonged to.
3087 * The user may still belong to the returned groups. Compare with getGroups().
3089 * The function will not return groups the user had belonged to before MW 1.17
3091 * @return array Names of the groups the user has belonged to.
3093 public function getFormerGroups() {
3096 if ( is_null( $this->mFormerGroups
) ) {
3097 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3098 ?
wfGetDB( DB_MASTER
)
3099 : wfGetDB( DB_SLAVE
);
3100 $res = $db->select( 'user_former_groups',
3101 array( 'ufg_group' ),
3102 array( 'ufg_user' => $this->mId
),
3104 $this->mFormerGroups
= array();
3105 foreach ( $res as $row ) {
3106 $this->mFormerGroups
[] = $row->ufg_group
;
3110 return $this->mFormerGroups
;
3114 * Get the user's edit count.
3115 * @return int|null Null for anonymous users
3117 public function getEditCount() {
3118 if ( !$this->getId() ) {
3122 if ( $this->mEditCount
=== null ) {
3123 /* Populate the count, if it has not been populated yet */
3124 $dbr = wfGetDB( DB_SLAVE
);
3125 // check if the user_editcount field has been initialized
3126 $count = $dbr->selectField(
3127 'user', 'user_editcount',
3128 array( 'user_id' => $this->mId
),
3132 if ( $count === null ) {
3133 // it has not been initialized. do so.
3134 $count = $this->initEditCount();
3136 $this->mEditCount
= $count;
3138 return (int)$this->mEditCount
;
3142 * Add the user to the given group.
3143 * This takes immediate effect.
3144 * @param string $group Name of the group to add
3147 public function addGroup( $group ) {
3150 if ( !Hooks
::run( 'UserAddGroup', array( $this, &$group ) ) ) {
3154 $dbw = wfGetDB( DB_MASTER
);
3155 if ( $this->getId() ) {
3156 $dbw->insert( 'user_groups',
3158 'ug_user' => $this->getID(),
3159 'ug_group' => $group,
3162 array( 'IGNORE' ) );
3165 $this->loadGroups();
3166 $this->mGroups
[] = $group;
3167 // In case loadGroups was not called before, we now have the right twice.
3168 // Get rid of the duplicate.
3169 $this->mGroups
= array_unique( $this->mGroups
);
3171 // Refresh the groups caches, and clear the rights cache so it will be
3172 // refreshed on the next call to $this->getRights().
3173 $this->getEffectiveGroups( true );
3174 $this->mRights
= null;
3176 $this->invalidateCache();
3182 * Remove the user from the given group.
3183 * This takes immediate effect.
3184 * @param string $group Name of the group to remove
3187 public function removeGroup( $group ) {
3189 if ( !Hooks
::run( 'UserRemoveGroup', array( $this, &$group ) ) ) {
3193 $dbw = wfGetDB( DB_MASTER
);
3194 $dbw->delete( 'user_groups',
3196 'ug_user' => $this->getID(),
3197 'ug_group' => $group,
3200 // Remember that the user was in this group
3201 $dbw->insert( 'user_former_groups',
3203 'ufg_user' => $this->getID(),
3204 'ufg_group' => $group,
3210 $this->loadGroups();
3211 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
3213 // Refresh the groups caches, and clear the rights cache so it will be
3214 // refreshed on the next call to $this->getRights().
3215 $this->getEffectiveGroups( true );
3216 $this->mRights
= null;
3218 $this->invalidateCache();
3224 * Get whether the user is logged in
3227 public function isLoggedIn() {
3228 return $this->getID() != 0;
3232 * Get whether the user is anonymous
3235 public function isAnon() {
3236 return !$this->isLoggedIn();
3240 * Check if user is allowed to access a feature / make an action
3242 * @param string ... Permissions to test
3243 * @return bool True if user is allowed to perform *any* of the given actions
3245 public function isAllowedAny() {
3246 $permissions = func_get_args();
3247 foreach ( $permissions as $permission ) {
3248 if ( $this->isAllowed( $permission ) ) {
3257 * @param string ... Permissions to test
3258 * @return bool True if the user is allowed to perform *all* of the given actions
3260 public function isAllowedAll() {
3261 $permissions = func_get_args();
3262 foreach ( $permissions as $permission ) {
3263 if ( !$this->isAllowed( $permission ) ) {
3271 * Internal mechanics of testing a permission
3272 * @param string $action
3275 public function isAllowed( $action = '' ) {
3276 if ( $action === '' ) {
3277 return true; // In the spirit of DWIM
3279 // Patrolling may not be enabled
3280 if ( $action === 'patrol' ||
$action === 'autopatrol' ) {
3281 global $wgUseRCPatrol, $wgUseNPPatrol;
3282 if ( !$wgUseRCPatrol && !$wgUseNPPatrol ) {
3286 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3287 // by misconfiguration: 0 == 'foo'
3288 return in_array( $action, $this->getRights(), true );
3292 * Check whether to enable recent changes patrol features for this user
3293 * @return bool True or false
3295 public function useRCPatrol() {
3296 global $wgUseRCPatrol;
3297 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3301 * Check whether to enable new pages patrol features for this user
3302 * @return bool True or false
3304 public function useNPPatrol() {
3305 global $wgUseRCPatrol, $wgUseNPPatrol;
3307 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3308 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3313 * Get the WebRequest object to use with this object
3315 * @return WebRequest
3317 public function getRequest() {
3318 if ( $this->mRequest
) {
3319 return $this->mRequest
;
3327 * Get a WatchedItem for this user and $title.
3329 * @since 1.22 $checkRights parameter added
3330 * @param Title $title
3331 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3332 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3333 * @return WatchedItem
3335 public function getWatchedItem( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3336 $key = $checkRights . ':' . $title->getNamespace() . ':' . $title->getDBkey();
3338 if ( isset( $this->mWatchedItems
[$key] ) ) {
3339 return $this->mWatchedItems
[$key];
3342 if ( count( $this->mWatchedItems
) >= self
::MAX_WATCHED_ITEMS_CACHE
) {
3343 $this->mWatchedItems
= array();
3346 $this->mWatchedItems
[$key] = WatchedItem
::fromUserTitle( $this, $title, $checkRights );
3347 return $this->mWatchedItems
[$key];
3351 * Check the watched status of an article.
3352 * @since 1.22 $checkRights parameter added
3353 * @param Title $title Title of the article to look at
3354 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3355 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3358 public function isWatched( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3359 return $this->getWatchedItem( $title, $checkRights )->isWatched();
3364 * @since 1.22 $checkRights parameter added
3365 * @param Title $title Title of the article to look at
3366 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3367 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3369 public function addWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3370 $this->getWatchedItem( $title, $checkRights )->addWatch();
3371 $this->invalidateCache();
3375 * Stop watching an article.
3376 * @since 1.22 $checkRights parameter added
3377 * @param Title $title Title of the article to look at
3378 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3379 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3381 public function removeWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3382 $this->getWatchedItem( $title, $checkRights )->removeWatch();
3383 $this->invalidateCache();
3387 * Clear the user's notification timestamp for the given title.
3388 * If e-notif e-mails are on, they will receive notification mails on
3389 * the next change of the page if it's watched etc.
3390 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3391 * @param Title $title Title of the article to look at
3392 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3394 public function clearNotification( &$title, $oldid = 0 ) {
3395 global $wgUseEnotif, $wgShowUpdatedMarker;
3397 // Do nothing if the database is locked to writes
3398 if ( wfReadOnly() ) {
3402 // Do nothing if not allowed to edit the watchlist
3403 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3407 // If we're working on user's talk page, we should update the talk page message indicator
3408 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3409 if ( !Hooks
::run( 'UserClearNewTalkNotification', array( &$this, $oldid ) ) ) {
3414 // Try to update the DB post-send and only if needed...
3415 DeferredUpdates
::addCallableUpdate( function() use ( $that, $title, $oldid ) {
3416 if ( !$that->getNewtalk() ) {
3417 return; // no notifications to clear
3420 // Delete the last notifications (they stack up)
3421 $that->setNewtalk( false );
3423 // If there is a new, unseen, revision, use its timestamp
3425 ?
$title->getNextRevisionID( $oldid, Title
::GAID_FOR_UPDATE
)
3428 $that->setNewtalk( true, Revision
::newFromId( $nextid ) );
3433 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3437 if ( $this->isAnon() ) {
3438 // Nothing else to do...
3442 // Only update the timestamp if the page is being watched.
3443 // The query to find out if it is watched is cached both in memcached and per-invocation,
3444 // and when it does have to be executed, it can be on a slave
3445 // If this is the user's newtalk page, we always update the timestamp
3447 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3451 $this->getWatchedItem( $title )->resetNotificationTimestamp(
3452 $force, $oldid, WatchedItem
::DEFERRED
3457 * Resets all of the given user's page-change notification timestamps.
3458 * If e-notif e-mails are on, they will receive notification mails on
3459 * the next change of any watched page.
3460 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3462 public function clearAllNotifications() {
3463 if ( wfReadOnly() ) {
3467 // Do nothing if not allowed to edit the watchlist
3468 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3472 global $wgUseEnotif, $wgShowUpdatedMarker;
3473 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3474 $this->setNewtalk( false );
3477 $id = $this->getId();
3479 $dbw = wfGetDB( DB_MASTER
);
3480 $dbw->update( 'watchlist',
3481 array( /* SET */ 'wl_notificationtimestamp' => null ),
3482 array( /* WHERE */ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ),
3485 // We also need to clear here the "you have new message" notification for the own user_talk page;
3486 // it's cleared one page view later in WikiPage::doViewUpdates().
3491 * Set a cookie on the user's client. Wrapper for
3492 * WebResponse::setCookie
3493 * @param string $name Name of the cookie to set
3494 * @param string $value Value to set
3495 * @param int $exp Expiration time, as a UNIX time value;
3496 * if 0 or not specified, use the default $wgCookieExpiration
3497 * @param bool $secure
3498 * true: Force setting the secure attribute when setting the cookie
3499 * false: Force NOT setting the secure attribute when setting the cookie
3500 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3501 * @param array $params Array of options sent passed to WebResponse::setcookie()
3502 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3505 protected function setCookie(
3506 $name, $value, $exp = 0, $secure = null, $params = array(), $request = null
3508 if ( $request === null ) {
3509 $request = $this->getRequest();
3511 $params['secure'] = $secure;
3512 $request->response()->setCookie( $name, $value, $exp, $params );
3516 * Clear a cookie on the user's client
3517 * @param string $name Name of the cookie to clear
3518 * @param bool $secure
3519 * true: Force setting the secure attribute when setting the cookie
3520 * false: Force NOT setting the secure attribute when setting the cookie
3521 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3522 * @param array $params Array of options sent passed to WebResponse::setcookie()
3524 protected function clearCookie( $name, $secure = null, $params = array() ) {
3525 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3529 * Set an extended login cookie on the user's client. The expiry of the cookie
3530 * is controlled by the $wgExtendedLoginCookieExpiration configuration
3533 * @see User::setCookie
3535 * @param string $name Name of the cookie to set
3536 * @param string $value Value to set
3537 * @param bool $secure
3538 * true: Force setting the secure attribute when setting the cookie
3539 * false: Force NOT setting the secure attribute when setting the cookie
3540 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3542 protected function setExtendedLoginCookie( $name, $value, $secure ) {
3543 global $wgExtendedLoginCookieExpiration, $wgCookieExpiration;
3546 $exp +
= $wgExtendedLoginCookieExpiration !== null
3547 ?
$wgExtendedLoginCookieExpiration
3548 : $wgCookieExpiration;
3550 $this->setCookie( $name, $value, $exp, $secure );
3554 * Set the default cookies for this session on the user's client.
3556 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3558 * @param bool $secure Whether to force secure/insecure cookies or use default
3559 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3561 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3562 global $wgExtendedLoginCookies;
3564 if ( $request === null ) {
3565 $request = $this->getRequest();
3569 if ( 0 == $this->mId
) {
3572 if ( !$this->mToken
) {
3573 // When token is empty or NULL generate a new one and then save it to the database
3574 // This allows a wiki to re-secure itself after a leak of it's user table or $wgSecretKey
3575 // Simply by setting every cell in the user_token column to NULL and letting them be
3576 // regenerated as users log back into the wiki.
3578 if ( !wfReadOnly() ) {
3579 $this->saveSettings();
3583 'wsUserID' => $this->mId
,
3584 'wsToken' => $this->mToken
,
3585 'wsUserName' => $this->getName()
3588 'UserID' => $this->mId
,
3589 'UserName' => $this->getName(),
3591 if ( $rememberMe ) {
3592 $cookies['Token'] = $this->mToken
;
3594 $cookies['Token'] = false;
3597 Hooks
::run( 'UserSetCookies', array( $this, &$session, &$cookies ) );
3599 foreach ( $session as $name => $value ) {
3600 $request->setSessionData( $name, $value );
3602 foreach ( $cookies as $name => $value ) {
3603 if ( $value === false ) {
3604 $this->clearCookie( $name );
3605 } elseif ( $rememberMe && in_array( $name, $wgExtendedLoginCookies ) ) {
3606 $this->setExtendedLoginCookie( $name, $value, $secure );
3608 $this->setCookie( $name, $value, 0, $secure, array(), $request );
3613 * If wpStickHTTPS was selected, also set an insecure cookie that
3614 * will cause the site to redirect the user to HTTPS, if they access
3615 * it over HTTP. Bug 29898. Use an un-prefixed cookie, so it's the same
3616 * as the one set by centralauth (bug 53538). Also set it to session, or
3617 * standard time setting, based on if rememberme was set.
3619 if ( $request->getCheck( 'wpStickHTTPS' ) ||
$this->requiresHTTPS() ) {
3623 $rememberMe ?
0 : null,
3625 array( 'prefix' => '' ) // no prefix
3631 * Log this user out.
3633 public function logout() {
3634 if ( Hooks
::run( 'UserLogout', array( &$this ) ) ) {
3640 * Clear the user's cookies and session, and reset the instance cache.
3643 public function doLogout() {
3644 $this->clearInstanceCache( 'defaults' );
3646 $this->getRequest()->setSessionData( 'wsUserID', 0 );
3648 $this->clearCookie( 'UserID' );
3649 $this->clearCookie( 'Token' );
3650 $this->clearCookie( 'forceHTTPS', false, array( 'prefix' => '' ) );
3652 // Remember when user logged out, to prevent seeing cached pages
3653 $this->setCookie( 'LoggedOut', time(), time() +
86400 );
3657 * Save this user's settings into the database.
3658 * @todo Only rarely do all these fields need to be set!
3660 public function saveSettings() {
3661 if ( wfReadOnly() ) {
3662 // @TODO: caller should deal with this instead!
3663 // This should really just be an exception.
3664 MWExceptionHandler
::logException( new DBExpectedError(
3666 "Could not update user with ID '{$this->mId}'; DB is read-only."
3672 if ( 0 == $this->mId
) {
3676 // Get a new user_touched that is higher than the old one.
3677 // This will be used for a CAS check as a last-resort safety
3678 // check against race conditions and slave lag.
3679 $oldTouched = $this->mTouched
;
3680 $newTouched = $this->newTouchedTimestamp();
3682 $dbw = wfGetDB( DB_MASTER
);
3683 $dbw->update( 'user',
3685 'user_name' => $this->mName
,
3686 'user_real_name' => $this->mRealName
,
3687 'user_email' => $this->mEmail
,
3688 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3689 'user_touched' => $dbw->timestamp( $newTouched ),
3690 'user_token' => strval( $this->mToken
),
3691 'user_email_token' => $this->mEmailToken
,
3692 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
3693 ), array( /* WHERE */
3694 'user_id' => $this->mId
,
3695 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
3699 if ( !$dbw->affectedRows() ) {
3700 // Maybe the problem was a missed cache update; clear it to be safe
3701 $this->clearSharedCache( 'refresh' );
3702 // User was changed in the meantime or loaded with stale data
3703 $from = ( $this->queryFlagsUsed
& self
::READ_LATEST
) ?
'master' : 'slave';
3704 throw new MWException(
3705 "CAS update failed on user_touched for user ID '{$this->mId}' (read from $from);" .
3706 " the version of the user to be saved is older than the current version."
3710 $this->mTouched
= $newTouched;
3711 $this->saveOptions();
3713 Hooks
::run( 'UserSaveSettings', array( $this ) );
3714 $this->clearSharedCache();
3715 $this->getUserPage()->invalidateCache();
3719 * If only this user's username is known, and it exists, return the user ID.
3721 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
3724 public function idForName( $flags = 0 ) {
3725 $s = trim( $this->getName() );
3730 $db = ( ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
)
3731 ?
wfGetDB( DB_MASTER
)
3732 : wfGetDB( DB_SLAVE
);
3734 $options = ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
)
3735 ?
array( 'LOCK IN SHARE MODE' )
3738 $id = $db->selectField( 'user',
3739 'user_id', array( 'user_name' => $s ), __METHOD__
, $options );
3745 * Add a user to the database, return the user object
3747 * @param string $name Username to add
3748 * @param array $params Array of Strings Non-default parameters to save to
3749 * the database as user_* fields:
3750 * - email: The user's email address.
3751 * - email_authenticated: The email authentication timestamp.
3752 * - real_name: The user's real name.
3753 * - options: An associative array of non-default options.
3754 * - token: Random authentication token. Do not set.
3755 * - registration: Registration timestamp. Do not set.
3757 * @return User|null User object, or null if the username already exists.
3759 public static function createNew( $name, $params = array() ) {
3760 foreach ( array( 'password', 'newpassword', 'newpass_time', 'password_expires' ) as $field ) {
3761 if ( isset( $params[$field] ) ) {
3762 wfDeprecated( __METHOD__
. " with param '$field'", '1.27' );
3763 unset( $params[$field] );
3769 $user->setToken(); // init token
3770 if ( isset( $params['options'] ) ) {
3771 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
3772 unset( $params['options'] );
3774 $dbw = wfGetDB( DB_MASTER
);
3775 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3777 $noPass = PasswordFactory
::newInvalidPassword()->toString();
3780 'user_id' => $seqVal,
3781 'user_name' => $name,
3782 'user_password' => $noPass,
3783 'user_newpassword' => $noPass,
3784 'user_email' => $user->mEmail
,
3785 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
3786 'user_real_name' => $user->mRealName
,
3787 'user_token' => strval( $user->mToken
),
3788 'user_registration' => $dbw->timestamp( $user->mRegistration
),
3789 'user_editcount' => 0,
3790 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
3792 foreach ( $params as $name => $value ) {
3793 $fields["user_$name"] = $value;
3795 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
3796 if ( $dbw->affectedRows() ) {
3797 $newUser = User
::newFromId( $dbw->insertId() );
3805 * Add this existing user object to the database. If the user already
3806 * exists, a fatal status object is returned, and the user object is
3807 * initialised with the data from the database.
3809 * Previously, this function generated a DB error due to a key conflict
3810 * if the user already existed. Many extension callers use this function
3811 * in code along the lines of:
3813 * $user = User::newFromName( $name );
3814 * if ( !$user->isLoggedIn() ) {
3815 * $user->addToDatabase();
3817 * // do something with $user...
3819 * However, this was vulnerable to a race condition (bug 16020). By
3820 * initialising the user object if the user exists, we aim to support this
3821 * calling sequence as far as possible.
3823 * Note that if the user exists, this function will acquire a write lock,
3824 * so it is still advisable to make the call conditional on isLoggedIn(),
3825 * and to commit the transaction after calling.
3827 * @throws MWException
3830 public function addToDatabase() {
3832 if ( !$this->mToken
) {
3833 $this->setToken(); // init token
3836 $this->mTouched
= $this->newTouchedTimestamp();
3838 $noPass = PasswordFactory
::newInvalidPassword()->toString();
3840 $dbw = wfGetDB( DB_MASTER
);
3841 $inWrite = $dbw->writesOrCallbacksPending();
3842 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3843 $dbw->insert( 'user',
3845 'user_id' => $seqVal,
3846 'user_name' => $this->mName
,
3847 'user_password' => $noPass,
3848 'user_newpassword' => $noPass,
3849 'user_email' => $this->mEmail
,
3850 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3851 'user_real_name' => $this->mRealName
,
3852 'user_token' => strval( $this->mToken
),
3853 'user_registration' => $dbw->timestamp( $this->mRegistration
),
3854 'user_editcount' => 0,
3855 'user_touched' => $dbw->timestamp( $this->mTouched
),
3859 if ( !$dbw->affectedRows() ) {
3860 // The queries below cannot happen in the same REPEATABLE-READ snapshot.
3861 // Handle this by COMMIT, if possible, or by LOCK IN SHARE MODE otherwise.
3863 // Can't commit due to pending writes that may need atomicity.
3864 // This may cause some lock contention unlike the case below.
3865 $options = array( 'LOCK IN SHARE MODE' );
3866 $flags = self
::READ_LOCKING
;
3868 // Often, this case happens early in views before any writes when
3869 // using CentralAuth. It's should be OK to commit and break the snapshot.
3870 $dbw->commit( __METHOD__
, 'flush' );
3872 $flags = self
::READ_LATEST
;
3874 $this->mId
= $dbw->selectField( 'user', 'user_id',
3875 array( 'user_name' => $this->mName
), __METHOD__
, $options );
3878 if ( $this->loadFromDatabase( $flags ) ) {
3883 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
3884 "to insert user '{$this->mName}' row, but it was not present in select!" );
3886 return Status
::newFatal( 'userexists' );
3888 $this->mId
= $dbw->insertId();
3889 self
::$idCacheByName[$this->mName
] = $this->mId
;
3891 // Clear instance cache other than user table data, which is already accurate
3892 $this->clearInstanceCache();
3894 $this->saveOptions();
3895 return Status
::newGood();
3899 * If this user is logged-in and blocked,
3900 * block any IP address they've successfully logged in from.
3901 * @return bool A block was spread
3903 public function spreadAnyEditBlock() {
3904 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3905 return $this->spreadBlock();
3911 * If this (non-anonymous) user is blocked,
3912 * block the IP address they've successfully logged in from.
3913 * @return bool A block was spread
3915 protected function spreadBlock() {
3916 wfDebug( __METHOD__
. "()\n" );
3918 if ( $this->mId
== 0 ) {
3922 $userblock = Block
::newFromTarget( $this->getName() );
3923 if ( !$userblock ) {
3927 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3931 * Get whether the user is explicitly blocked from account creation.
3932 * @return bool|Block
3934 public function isBlockedFromCreateAccount() {
3935 $this->getBlockedStatus();
3936 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
3937 return $this->mBlock
;
3940 # bug 13611: if the IP address the user is trying to create an account from is
3941 # blocked with createaccount disabled, prevent new account creation there even
3942 # when the user is logged in
3943 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3944 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
3946 return $this->mBlockedFromCreateAccount
instanceof Block
3947 && $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
3948 ?
$this->mBlockedFromCreateAccount
3953 * Get whether the user is blocked from using Special:Emailuser.
3956 public function isBlockedFromEmailuser() {
3957 $this->getBlockedStatus();
3958 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
3962 * Get whether the user is allowed to create an account.
3965 public function isAllowedToCreateAccount() {
3966 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
3970 * Get this user's personal page title.
3972 * @return Title User's personal page title
3974 public function getUserPage() {
3975 return Title
::makeTitle( NS_USER
, $this->getName() );
3979 * Get this user's talk page title.
3981 * @return Title User's talk page title
3983 public function getTalkPage() {
3984 $title = $this->getUserPage();
3985 return $title->getTalkPage();
3989 * Determine whether the user is a newbie. Newbies are either
3990 * anonymous IPs, or the most recently created accounts.
3993 public function isNewbie() {
3994 return !$this->isAllowed( 'autoconfirmed' );
3998 * Check to see if the given clear-text password is one of the accepted passwords
3999 * @deprecated since 1.27. AuthManager is coming.
4000 * @param string $password User password
4001 * @return bool True if the given password is correct, otherwise False
4003 public function checkPassword( $password ) {
4004 global $wgAuth, $wgLegacyEncoding;
4008 // Some passwords will give a fatal Status, which means there is
4009 // some sort of technical or security reason for this password to
4010 // be completely invalid and should never be checked (e.g., T64685)
4011 if ( !$this->checkPasswordValidity( $password )->isOK() ) {
4015 // Certain authentication plugins do NOT want to save
4016 // domain passwords in a mysql database, so we should
4017 // check this (in case $wgAuth->strict() is false).
4018 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
4020 } elseif ( $wgAuth->strict() ) {
4021 // Auth plugin doesn't allow local authentication
4023 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
4024 // Auth plugin doesn't allow local authentication for this user name
4028 $passwordFactory = new PasswordFactory();
4029 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4030 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
4031 ?
wfGetDB( DB_MASTER
)
4032 : wfGetDB( DB_SLAVE
);
4035 $mPassword = $passwordFactory->newFromCiphertext( $db->selectField(
4036 'user', 'user_password', array( 'user_id' => $this->getId() ), __METHOD__
4038 } catch ( PasswordError
$e ) {
4039 wfDebug( 'Invalid password hash found in database.' );
4040 $mPassword = PasswordFactory
::newInvalidPassword();
4043 if ( !$mPassword->equals( $password ) ) {
4044 if ( $wgLegacyEncoding ) {
4045 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
4046 // Check for this with iconv
4047 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
4048 if ( $cp1252Password === $password ||
!$mPassword->equals( $cp1252Password ) ) {
4056 if ( $passwordFactory->needsUpdate( $mPassword ) && !wfReadOnly() ) {
4057 $this->setPasswordInternal( $password );
4064 * Check if the given clear-text password matches the temporary password
4065 * sent by e-mail for password reset operations.
4067 * @deprecated since 1.27. AuthManager is coming.
4068 * @param string $plaintext
4069 * @return bool True if matches, false otherwise
4071 public function checkTemporaryPassword( $plaintext ) {
4072 global $wgNewPasswordExpiry;
4076 $passwordFactory = new PasswordFactory();
4077 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4078 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
4079 ?
wfGetDB( DB_MASTER
)
4080 : wfGetDB( DB_SLAVE
);
4082 $row = $db->selectRow(
4084 array( 'user_newpassword', 'user_newpass_time' ),
4085 array( 'user_id' => $this->getId() ),
4089 $newPassword = $passwordFactory->newFromCiphertext( $row->user_newpassword
);
4090 } catch ( PasswordError
$e ) {
4091 wfDebug( 'Invalid password hash found in database.' );
4092 $newPassword = PasswordFactory
::newInvalidPassword();
4095 if ( $newPassword->equals( $plaintext ) ) {
4096 if ( is_null( $row->user_newpass_time
) ) {
4099 $expiry = wfTimestamp( TS_UNIX
, $row->user_newpass_time
) +
$wgNewPasswordExpiry;
4100 return ( time() < $expiry );
4107 * Internal implementation for self::getEditToken() and
4108 * self::matchEditToken().
4110 * @param string|array $salt
4111 * @param WebRequest $request
4112 * @param string|int $timestamp
4115 private function getEditTokenAtTimestamp( $salt, $request, $timestamp ) {
4116 if ( $this->isAnon() ) {
4117 return self
::EDIT_TOKEN_SUFFIX
;
4119 $token = $request->getSessionData( 'wsEditToken' );
4120 if ( $token === null ) {
4121 $token = MWCryptRand
::generateHex( 32 );
4122 $request->setSessionData( 'wsEditToken', $token );
4124 if ( is_array( $salt ) ) {
4125 $salt = implode( '|', $salt );
4127 return hash_hmac( 'md5', $timestamp . $salt, $token, false ) .
4128 dechex( $timestamp ) .
4129 self
::EDIT_TOKEN_SUFFIX
;
4134 * Initialize (if necessary) and return a session token value
4135 * which can be used in edit forms to show that the user's
4136 * login credentials aren't being hijacked with a foreign form
4141 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4142 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4143 * @return string The new edit token
4145 public function getEditToken( $salt = '', $request = null ) {
4146 return $this->getEditTokenAtTimestamp(
4147 $salt, $request ?
: $this->getRequest(), wfTimestamp()
4152 * Generate a looking random token for various uses.
4154 * @return string The new random token
4155 * @deprecated since 1.20: Use MWCryptRand for secure purposes or
4156 * wfRandomString for pseudo-randomness.
4158 public static function generateToken() {
4159 return MWCryptRand
::generateHex( 32 );
4163 * Get the embedded timestamp from a token.
4164 * @param string $val Input token
4167 public static function getEditTokenTimestamp( $val ) {
4168 $suffixLen = strlen( self
::EDIT_TOKEN_SUFFIX
);
4169 if ( strlen( $val ) <= 32 +
$suffixLen ) {
4173 return hexdec( substr( $val, 32, -$suffixLen ) );
4177 * Check given value against the token value stored in the session.
4178 * A match should confirm that the form was submitted from the
4179 * user's own login session, not a form submission from a third-party
4182 * @param string $val Input value to compare
4183 * @param string $salt Optional function-specific data for hashing
4184 * @param WebRequest|null $request Object to use or null to use $wgRequest
4185 * @param int $maxage Fail tokens older than this, in seconds
4186 * @return bool Whether the token matches
4188 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4189 if ( $this->isAnon() ) {
4190 return $val === self
::EDIT_TOKEN_SUFFIX
;
4193 $timestamp = self
::getEditTokenTimestamp( $val );
4194 if ( $timestamp === null ) {
4197 if ( $maxage !== null && $timestamp < wfTimestamp() - $maxage ) {
4202 $sessionToken = $this->getEditTokenAtTimestamp(
4203 $salt, $request ?
: $this->getRequest(), $timestamp
4206 if ( !hash_equals( $sessionToken, $val ) ) {
4207 wfDebug( "User::matchEditToken: broken session data\n" );
4210 return hash_equals( $sessionToken, $val );
4214 * Check given value against the token value stored in the session,
4215 * ignoring the suffix.
4217 * @param string $val Input value to compare
4218 * @param string $salt Optional function-specific data for hashing
4219 * @param WebRequest|null $request Object to use or null to use $wgRequest
4220 * @param int $maxage Fail tokens older than this, in seconds
4221 * @return bool Whether the token matches
4223 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4224 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . self
::EDIT_TOKEN_SUFFIX
;
4225 return $this->matchEditToken( $val, $salt, $request, $maxage );
4229 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4230 * mail to the user's given address.
4232 * @param string $type Message to send, either "created", "changed" or "set"
4235 public function sendConfirmationMail( $type = 'created' ) {
4237 $expiration = null; // gets passed-by-ref and defined in next line.
4238 $token = $this->confirmationToken( $expiration );
4239 $url = $this->confirmationTokenUrl( $token );
4240 $invalidateURL = $this->invalidationTokenUrl( $token );
4241 $this->saveSettings();
4243 if ( $type == 'created' ||
$type === false ) {
4244 $message = 'confirmemail_body';
4245 } elseif ( $type === true ) {
4246 $message = 'confirmemail_body_changed';
4248 // Messages: confirmemail_body_changed, confirmemail_body_set
4249 $message = 'confirmemail_body_' . $type;
4252 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4253 wfMessage( $message,
4254 $this->getRequest()->getIP(),
4257 $wgLang->userTimeAndDate( $expiration, $this ),
4259 $wgLang->userDate( $expiration, $this ),
4260 $wgLang->userTime( $expiration, $this ) )->text() );
4264 * Send an e-mail to this user's account. Does not check for
4265 * confirmed status or validity.
4267 * @param string $subject Message subject
4268 * @param string $body Message body
4269 * @param User|null $from Optional sending user; if unspecified, default
4270 * $wgPasswordSender will be used.
4271 * @param string $replyto Reply-To address
4274 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4275 global $wgPasswordSender;
4277 if ( $from instanceof User
) {
4278 $sender = MailAddress
::newFromUser( $from );
4280 $sender = new MailAddress( $wgPasswordSender,
4281 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4283 $to = MailAddress
::newFromUser( $this );
4285 return UserMailer
::send( $to, $sender, $subject, $body, array(
4286 'replyTo' => $replyto,
4291 * Generate, store, and return a new e-mail confirmation code.
4292 * A hash (unsalted, since it's used as a key) is stored.
4294 * @note Call saveSettings() after calling this function to commit
4295 * this change to the database.
4297 * @param string &$expiration Accepts the expiration time
4298 * @return string New token
4300 protected function confirmationToken( &$expiration ) {
4301 global $wgUserEmailConfirmationTokenExpiry;
4303 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4304 $expiration = wfTimestamp( TS_MW
, $expires );
4306 $token = MWCryptRand
::generateHex( 32 );
4307 $hash = md5( $token );
4308 $this->mEmailToken
= $hash;
4309 $this->mEmailTokenExpires
= $expiration;
4314 * Return a URL the user can use to confirm their email address.
4315 * @param string $token Accepts the email confirmation token
4316 * @return string New token URL
4318 protected function confirmationTokenUrl( $token ) {
4319 return $this->getTokenUrl( 'ConfirmEmail', $token );
4323 * Return a URL the user can use to invalidate their email address.
4324 * @param string $token Accepts the email confirmation token
4325 * @return string New token URL
4327 protected function invalidationTokenUrl( $token ) {
4328 return $this->getTokenUrl( 'InvalidateEmail', $token );
4332 * Internal function to format the e-mail validation/invalidation URLs.
4333 * This uses a quickie hack to use the
4334 * hardcoded English names of the Special: pages, for ASCII safety.
4336 * @note Since these URLs get dropped directly into emails, using the
4337 * short English names avoids insanely long URL-encoded links, which
4338 * also sometimes can get corrupted in some browsers/mailers
4339 * (bug 6957 with Gmail and Internet Explorer).
4341 * @param string $page Special page
4342 * @param string $token Token
4343 * @return string Formatted URL
4345 protected function getTokenUrl( $page, $token ) {
4346 // Hack to bypass localization of 'Special:'
4347 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4348 return $title->getCanonicalURL();
4352 * Mark the e-mail address confirmed.
4354 * @note Call saveSettings() after calling this function to commit the change.
4358 public function confirmEmail() {
4359 // Check if it's already confirmed, so we don't touch the database
4360 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4361 if ( !$this->isEmailConfirmed() ) {
4362 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4363 Hooks
::run( 'ConfirmEmailComplete', array( $this ) );
4369 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4370 * address if it was already confirmed.
4372 * @note Call saveSettings() after calling this function to commit the change.
4373 * @return bool Returns true
4375 public function invalidateEmail() {
4377 $this->mEmailToken
= null;
4378 $this->mEmailTokenExpires
= null;
4379 $this->setEmailAuthenticationTimestamp( null );
4381 Hooks
::run( 'InvalidateEmailComplete', array( $this ) );
4386 * Set the e-mail authentication timestamp.
4387 * @param string $timestamp TS_MW timestamp
4389 public function setEmailAuthenticationTimestamp( $timestamp ) {
4391 $this->mEmailAuthenticated
= $timestamp;
4392 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
4396 * Is this user allowed to send e-mails within limits of current
4397 * site configuration?
4400 public function canSendEmail() {
4401 global $wgEnableEmail, $wgEnableUserEmail;
4402 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4405 $canSend = $this->isEmailConfirmed();
4406 Hooks
::run( 'UserCanSendEmail', array( &$this, &$canSend ) );
4411 * Is this user allowed to receive e-mails within limits of current
4412 * site configuration?
4415 public function canReceiveEmail() {
4416 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4420 * Is this user's e-mail address valid-looking and confirmed within
4421 * limits of the current site configuration?
4423 * @note If $wgEmailAuthentication is on, this may require the user to have
4424 * confirmed their address by returning a code or using a password
4425 * sent to the address from the wiki.
4429 public function isEmailConfirmed() {
4430 global $wgEmailAuthentication;
4433 if ( Hooks
::run( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
4434 if ( $this->isAnon() ) {
4437 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4440 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4450 * Check whether there is an outstanding request for e-mail confirmation.
4453 public function isEmailConfirmationPending() {
4454 global $wgEmailAuthentication;
4455 return $wgEmailAuthentication &&
4456 !$this->isEmailConfirmed() &&
4457 $this->mEmailToken
&&
4458 $this->mEmailTokenExpires
> wfTimestamp();
4462 * Get the timestamp of account creation.
4464 * @return string|bool|null Timestamp of account creation, false for
4465 * non-existent/anonymous user accounts, or null if existing account
4466 * but information is not in database.
4468 public function getRegistration() {
4469 if ( $this->isAnon() ) {
4473 return $this->mRegistration
;
4477 * Get the timestamp of the first edit
4479 * @return string|bool Timestamp of first edit, or false for
4480 * non-existent/anonymous user accounts.
4482 public function getFirstEditTimestamp() {
4483 if ( $this->getId() == 0 ) {
4484 return false; // anons
4486 $dbr = wfGetDB( DB_SLAVE
);
4487 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4488 array( 'rev_user' => $this->getId() ),
4490 array( 'ORDER BY' => 'rev_timestamp ASC' )
4493 return false; // no edits
4495 return wfTimestamp( TS_MW
, $time );
4499 * Get the permissions associated with a given list of groups
4501 * @param array $groups Array of Strings List of internal group names
4502 * @return array Array of Strings List of permission key names for given groups combined
4504 public static function getGroupPermissions( $groups ) {
4505 global $wgGroupPermissions, $wgRevokePermissions;
4507 // grant every granted permission first
4508 foreach ( $groups as $group ) {
4509 if ( isset( $wgGroupPermissions[$group] ) ) {
4510 $rights = array_merge( $rights,
4511 // array_filter removes empty items
4512 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4515 // now revoke the revoked permissions
4516 foreach ( $groups as $group ) {
4517 if ( isset( $wgRevokePermissions[$group] ) ) {
4518 $rights = array_diff( $rights,
4519 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4522 return array_unique( $rights );
4526 * Get all the groups who have a given permission
4528 * @param string $role Role to check
4529 * @return array Array of Strings List of internal group names with the given permission
4531 public static function getGroupsWithPermission( $role ) {
4532 global $wgGroupPermissions;
4533 $allowedGroups = array();
4534 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4535 if ( self
::groupHasPermission( $group, $role ) ) {
4536 $allowedGroups[] = $group;
4539 return $allowedGroups;
4543 * Check, if the given group has the given permission
4545 * If you're wanting to check whether all users have a permission, use
4546 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4550 * @param string $group Group to check
4551 * @param string $role Role to check
4554 public static function groupHasPermission( $group, $role ) {
4555 global $wgGroupPermissions, $wgRevokePermissions;
4556 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4557 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4561 * Check if all users have the given permission
4564 * @param string $right Right to check
4567 public static function isEveryoneAllowed( $right ) {
4568 global $wgGroupPermissions, $wgRevokePermissions;
4569 static $cache = array();
4571 // Use the cached results, except in unit tests which rely on
4572 // being able change the permission mid-request
4573 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4574 return $cache[$right];
4577 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4578 $cache[$right] = false;
4582 // If it's revoked anywhere, then everyone doesn't have it
4583 foreach ( $wgRevokePermissions as $rights ) {
4584 if ( isset( $rights[$right] ) && $rights[$right] ) {
4585 $cache[$right] = false;
4590 // Allow extensions (e.g. OAuth) to say false
4591 if ( !Hooks
::run( 'UserIsEveryoneAllowed', array( $right ) ) ) {
4592 $cache[$right] = false;
4596 $cache[$right] = true;
4601 * Get the localized descriptive name for a group, if it exists
4603 * @param string $group Internal group name
4604 * @return string Localized descriptive group name
4606 public static function getGroupName( $group ) {
4607 $msg = wfMessage( "group-$group" );
4608 return $msg->isBlank() ?
$group : $msg->text();
4612 * Get the localized descriptive name for a member of a group, if it exists
4614 * @param string $group Internal group name
4615 * @param string $username Username for gender (since 1.19)
4616 * @return string Localized name for group member
4618 public static function getGroupMember( $group, $username = '#' ) {
4619 $msg = wfMessage( "group-$group-member", $username );
4620 return $msg->isBlank() ?
$group : $msg->text();
4624 * Return the set of defined explicit groups.
4625 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4626 * are not included, as they are defined automatically, not in the database.
4627 * @return array Array of internal group names
4629 public static function getAllGroups() {
4630 global $wgGroupPermissions, $wgRevokePermissions;
4632 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4633 self
::getImplicitGroups()
4638 * Get a list of all available permissions.
4639 * @return string[] Array of permission names
4641 public static function getAllRights() {
4642 if ( self
::$mAllRights === false ) {
4643 global $wgAvailableRights;
4644 if ( count( $wgAvailableRights ) ) {
4645 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
4647 self
::$mAllRights = self
::$mCoreRights;
4649 Hooks
::run( 'UserGetAllRights', array( &self
::$mAllRights ) );
4651 return self
::$mAllRights;
4655 * Get a list of implicit groups
4656 * @return array Array of Strings Array of internal group names
4658 public static function getImplicitGroups() {
4659 global $wgImplicitGroups;
4661 $groups = $wgImplicitGroups;
4662 # Deprecated, use $wgImplicitGroups instead
4663 Hooks
::run( 'UserGetImplicitGroups', array( &$groups ), '1.25' );
4669 * Get the title of a page describing a particular group
4671 * @param string $group Internal group name
4672 * @return Title|bool Title of the page if it exists, false otherwise
4674 public static function getGroupPage( $group ) {
4675 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4676 if ( $msg->exists() ) {
4677 $title = Title
::newFromText( $msg->text() );
4678 if ( is_object( $title ) ) {
4686 * Create a link to the group in HTML, if available;
4687 * else return the group name.
4689 * @param string $group Internal name of the group
4690 * @param string $text The text of the link
4691 * @return string HTML link to the group
4693 public static function makeGroupLinkHTML( $group, $text = '' ) {
4694 if ( $text == '' ) {
4695 $text = self
::getGroupName( $group );
4697 $title = self
::getGroupPage( $group );
4699 return Linker
::link( $title, htmlspecialchars( $text ) );
4701 return htmlspecialchars( $text );
4706 * Create a link to the group in Wikitext, if available;
4707 * else return the group name.
4709 * @param string $group Internal name of the group
4710 * @param string $text The text of the link
4711 * @return string Wikilink to the group
4713 public static function makeGroupLinkWiki( $group, $text = '' ) {
4714 if ( $text == '' ) {
4715 $text = self
::getGroupName( $group );
4717 $title = self
::getGroupPage( $group );
4719 $page = $title->getFullText();
4720 return "[[$page|$text]]";
4727 * Returns an array of the groups that a particular group can add/remove.
4729 * @param string $group The group to check for whether it can add/remove
4730 * @return array Array( 'add' => array( addablegroups ),
4731 * 'remove' => array( removablegroups ),
4732 * 'add-self' => array( addablegroups to self),
4733 * 'remove-self' => array( removable groups from self) )
4735 public static function changeableByGroup( $group ) {
4736 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4740 'remove' => array(),
4741 'add-self' => array(),
4742 'remove-self' => array()
4745 if ( empty( $wgAddGroups[$group] ) ) {
4746 // Don't add anything to $groups
4747 } elseif ( $wgAddGroups[$group] === true ) {
4748 // You get everything
4749 $groups['add'] = self
::getAllGroups();
4750 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4751 $groups['add'] = $wgAddGroups[$group];
4754 // Same thing for remove
4755 if ( empty( $wgRemoveGroups[$group] ) ) {
4757 } elseif ( $wgRemoveGroups[$group] === true ) {
4758 $groups['remove'] = self
::getAllGroups();
4759 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4760 $groups['remove'] = $wgRemoveGroups[$group];
4763 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4764 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4765 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4766 if ( is_int( $key ) ) {
4767 $wgGroupsAddToSelf['user'][] = $value;
4772 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
4773 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4774 if ( is_int( $key ) ) {
4775 $wgGroupsRemoveFromSelf['user'][] = $value;
4780 // Now figure out what groups the user can add to him/herself
4781 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4783 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4784 // No idea WHY this would be used, but it's there
4785 $groups['add-self'] = User
::getAllGroups();
4786 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4787 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4790 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4792 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4793 $groups['remove-self'] = User
::getAllGroups();
4794 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4795 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4802 * Returns an array of groups that this user can add and remove
4803 * @return array Array( 'add' => array( addablegroups ),
4804 * 'remove' => array( removablegroups ),
4805 * 'add-self' => array( addablegroups to self),
4806 * 'remove-self' => array( removable groups from self) )
4808 public function changeableGroups() {
4809 if ( $this->isAllowed( 'userrights' ) ) {
4810 // This group gives the right to modify everything (reverse-
4811 // compatibility with old "userrights lets you change
4813 // Using array_merge to make the groups reindexed
4814 $all = array_merge( User
::getAllGroups() );
4818 'add-self' => array(),
4819 'remove-self' => array()
4823 // Okay, it's not so simple, we will have to go through the arrays
4826 'remove' => array(),
4827 'add-self' => array(),
4828 'remove-self' => array()
4830 $addergroups = $this->getEffectiveGroups();
4832 foreach ( $addergroups as $addergroup ) {
4833 $groups = array_merge_recursive(
4834 $groups, $this->changeableByGroup( $addergroup )
4836 $groups['add'] = array_unique( $groups['add'] );
4837 $groups['remove'] = array_unique( $groups['remove'] );
4838 $groups['add-self'] = array_unique( $groups['add-self'] );
4839 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4845 * Deferred version of incEditCountImmediate()
4847 public function incEditCount() {
4849 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle( function() use ( $that ) {
4850 $that->incEditCountImmediate();
4855 * Increment the user's edit-count field.
4856 * Will have no effect for anonymous users.
4859 public function incEditCountImmediate() {
4860 if ( $this->isAnon() ) {
4864 $dbw = wfGetDB( DB_MASTER
);
4865 // No rows will be "affected" if user_editcount is NULL
4868 array( 'user_editcount=user_editcount+1' ),
4869 array( 'user_id' => $this->getId(), 'user_editcount IS NOT NULL' ),
4872 // Lazy initialization check...
4873 if ( $dbw->affectedRows() == 0 ) {
4874 // Now here's a goddamn hack...
4875 $dbr = wfGetDB( DB_SLAVE
);
4876 if ( $dbr !== $dbw ) {
4877 // If we actually have a slave server, the count is
4878 // at least one behind because the current transaction
4879 // has not been committed and replicated.
4880 $this->initEditCount( 1 );
4882 // But if DB_SLAVE is selecting the master, then the
4883 // count we just read includes the revision that was
4884 // just added in the working transaction.
4885 $this->initEditCount();
4888 // Edit count in user cache too
4889 $this->invalidateCache();
4893 * Initialize user_editcount from data out of the revision table
4895 * @param int $add Edits to add to the count from the revision table
4896 * @return int Number of edits
4898 protected function initEditCount( $add = 0 ) {
4899 // Pull from a slave to be less cruel to servers
4900 // Accuracy isn't the point anyway here
4901 $dbr = wfGetDB( DB_SLAVE
);
4902 $count = (int)$dbr->selectField(
4905 array( 'rev_user' => $this->getId() ),
4908 $count = $count +
$add;
4910 $dbw = wfGetDB( DB_MASTER
);
4913 array( 'user_editcount' => $count ),
4914 array( 'user_id' => $this->getId() ),
4922 * Get the description of a given right
4924 * @param string $right Right to query
4925 * @return string Localized description of the right
4927 public static function getRightDescription( $right ) {
4928 $key = "right-$right";
4929 $msg = wfMessage( $key );
4930 return $msg->isBlank() ?
$right : $msg->text();
4934 * Make a new-style password hash
4936 * @param string $password Plain-text password
4937 * @param bool|string $salt Optional salt, may be random or the user ID.
4938 * If unspecified or false, will generate one automatically
4939 * @return string Password hash
4940 * @deprecated since 1.24, use Password class
4942 public static function crypt( $password, $salt = false ) {
4943 wfDeprecated( __METHOD__
, '1.24' );
4944 $passwordFactory = new PasswordFactory();
4945 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4946 $hash = $passwordFactory->newFromPlaintext( $password );
4947 return $hash->toString();
4951 * Compare a password hash with a plain-text password. Requires the user
4952 * ID if there's a chance that the hash is an old-style hash.
4954 * @param string $hash Password hash
4955 * @param string $password Plain-text password to compare
4956 * @param string|bool $userId User ID for old-style password salt
4959 * @deprecated since 1.24, use Password class
4961 public static function comparePasswords( $hash, $password, $userId = false ) {
4962 wfDeprecated( __METHOD__
, '1.24' );
4964 // Check for *really* old password hashes that don't even have a type
4965 // The old hash format was just an md5 hex hash, with no type information
4966 if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) {
4967 global $wgPasswordSalt;
4968 if ( $wgPasswordSalt ) {
4969 $password = ":B:{$userId}:{$hash}";
4971 $password = ":A:{$hash}";
4975 $passwordFactory = new PasswordFactory();
4976 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4977 $hash = $passwordFactory->newFromCiphertext( $hash );
4978 return $hash->equals( $password );
4982 * Add a newuser log entry for this user.
4983 * Before 1.19 the return value was always true.
4985 * @param string|bool $action Account creation type.
4986 * - String, one of the following values:
4987 * - 'create' for an anonymous user creating an account for himself.
4988 * This will force the action's performer to be the created user itself,
4989 * no matter the value of $wgUser
4990 * - 'create2' for a logged in user creating an account for someone else
4991 * - 'byemail' when the created user will receive its password by e-mail
4992 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
4993 * - Boolean means whether the account was created by e-mail (deprecated):
4994 * - true will be converted to 'byemail'
4995 * - false will be converted to 'create' if this object is the same as
4996 * $wgUser and to 'create2' otherwise
4998 * @param string $reason User supplied reason
5000 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
5002 public function addNewUserLogEntry( $action = false, $reason = '' ) {
5003 global $wgUser, $wgNewUserLog;
5004 if ( empty( $wgNewUserLog ) ) {
5005 return true; // disabled
5008 if ( $action === true ) {
5009 $action = 'byemail';
5010 } elseif ( $action === false ) {
5011 if ( $this->equals( $wgUser ) ) {
5014 $action = 'create2';
5018 if ( $action === 'create' ||
$action === 'autocreate' ) {
5021 $performer = $wgUser;
5024 $logEntry = new ManualLogEntry( 'newusers', $action );
5025 $logEntry->setPerformer( $performer );
5026 $logEntry->setTarget( $this->getUserPage() );
5027 $logEntry->setComment( $reason );
5028 $logEntry->setParameters( array(
5029 '4::userid' => $this->getId(),
5031 $logid = $logEntry->insert();
5033 if ( $action !== 'autocreate' ) {
5034 $logEntry->publish( $logid );
5041 * Add an autocreate newuser log entry for this user
5042 * Used by things like CentralAuth and perhaps other authplugins.
5043 * Consider calling addNewUserLogEntry() directly instead.
5047 public function addNewUserLogEntryAutoCreate() {
5048 $this->addNewUserLogEntry( 'autocreate' );
5054 * Load the user options either from cache, the database or an array
5056 * @param array $data Rows for the current user out of the user_properties table
5058 protected function loadOptions( $data = null ) {
5063 if ( $this->mOptionsLoaded
) {
5067 $this->mOptions
= self
::getDefaultOptions();
5069 if ( !$this->getId() ) {
5070 // For unlogged-in users, load language/variant options from request.
5071 // There's no need to do it for logged-in users: they can set preferences,
5072 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5073 // so don't override user's choice (especially when the user chooses site default).
5074 $variant = $wgContLang->getDefaultVariant();
5075 $this->mOptions
['variant'] = $variant;
5076 $this->mOptions
['language'] = $variant;
5077 $this->mOptionsLoaded
= true;
5081 // Maybe load from the object
5082 if ( !is_null( $this->mOptionOverrides
) ) {
5083 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5084 foreach ( $this->mOptionOverrides
as $key => $value ) {
5085 $this->mOptions
[$key] = $value;
5088 if ( !is_array( $data ) ) {
5089 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5090 // Load from database
5091 $dbr = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
5092 ?
wfGetDB( DB_MASTER
)
5093 : wfGetDB( DB_SLAVE
);
5095 $res = $dbr->select(
5097 array( 'up_property', 'up_value' ),
5098 array( 'up_user' => $this->getId() ),
5102 $this->mOptionOverrides
= array();
5104 foreach ( $res as $row ) {
5105 $data[$row->up_property
] = $row->up_value
;
5108 foreach ( $data as $property => $value ) {
5109 $this->mOptionOverrides
[$property] = $value;
5110 $this->mOptions
[$property] = $value;
5114 $this->mOptionsLoaded
= true;
5116 Hooks
::run( 'UserLoadOptions', array( $this, &$this->mOptions
) );
5120 * Saves the non-default options for this user, as previously set e.g. via
5121 * setOption(), in the database's "user_properties" (preferences) table.
5122 * Usually used via saveSettings().
5124 protected function saveOptions() {
5125 $this->loadOptions();
5127 // Not using getOptions(), to keep hidden preferences in database
5128 $saveOptions = $this->mOptions
;
5130 // Allow hooks to abort, for instance to save to a global profile.
5131 // Reset options to default state before saving.
5132 if ( !Hooks
::run( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
5136 $userId = $this->getId();
5138 $insert_rows = array(); // all the new preference rows
5139 foreach ( $saveOptions as $key => $value ) {
5140 // Don't bother storing default values
5141 $defaultOption = self
::getDefaultOption( $key );
5142 if ( ( $defaultOption === null && $value !== false && $value !== null )
5143 ||
$value != $defaultOption
5145 $insert_rows[] = array(
5146 'up_user' => $userId,
5147 'up_property' => $key,
5148 'up_value' => $value,
5153 $dbw = wfGetDB( DB_MASTER
);
5155 $res = $dbw->select( 'user_properties',
5156 array( 'up_property', 'up_value' ), array( 'up_user' => $userId ), __METHOD__
);
5158 // Find prior rows that need to be removed or updated. These rows will
5159 // all be deleted (the later so that INSERT IGNORE applies the new values).
5160 $keysDelete = array();
5161 foreach ( $res as $row ) {
5162 if ( !isset( $saveOptions[$row->up_property
] )
5163 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
5165 $keysDelete[] = $row->up_property
;
5169 if ( count( $keysDelete ) ) {
5170 // Do the DELETE by PRIMARY KEY for prior rows.
5171 // In the past a very large portion of calls to this function are for setting
5172 // 'rememberpassword' for new accounts (a preference that has since been removed).
5173 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5174 // caused gap locks on [max user ID,+infinity) which caused high contention since
5175 // updates would pile up on each other as they are for higher (newer) user IDs.
5176 // It might not be necessary these days, but it shouldn't hurt either.
5177 $dbw->delete( 'user_properties',
5178 array( 'up_user' => $userId, 'up_property' => $keysDelete ), __METHOD__
);
5180 // Insert the new preference rows
5181 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, array( 'IGNORE' ) );
5185 * Lazily instantiate and return a factory object for making passwords
5187 * @deprecated since 1.27, create a PasswordFactory directly instead
5188 * @return PasswordFactory
5190 public static function getPasswordFactory() {
5191 wfDeprecated( __METHOD__
, '1.27' );
5192 $ret = new PasswordFactory();
5193 $ret->init( RequestContext
::getMain()->getConfig() );
5198 * Provide an array of HTML5 attributes to put on an input element
5199 * intended for the user to enter a new password. This may include
5200 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
5202 * Do *not* use this when asking the user to enter his current password!
5203 * Regardless of configuration, users may have invalid passwords for whatever
5204 * reason (e.g., they were set before requirements were tightened up).
5205 * Only use it when asking for a new password, like on account creation or
5208 * Obviously, you still need to do server-side checking.
5210 * NOTE: A combination of bugs in various browsers means that this function
5211 * actually just returns array() unconditionally at the moment. May as
5212 * well keep it around for when the browser bugs get fixed, though.
5214 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
5216 * @deprecated since 1.27
5217 * @return array Array of HTML attributes suitable for feeding to
5218 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
5219 * That will get confused by the boolean attribute syntax used.)
5221 public static function passwordChangeInputAttribs() {
5222 global $wgMinimalPasswordLength;
5224 if ( $wgMinimalPasswordLength == 0 ) {
5228 # Note that the pattern requirement will always be satisfied if the
5229 # input is empty, so we need required in all cases.
5231 # @todo FIXME: Bug 23769: This needs to not claim the password is required
5232 # if e-mail confirmation is being used. Since HTML5 input validation
5233 # is b0rked anyway in some browsers, just return nothing. When it's
5234 # re-enabled, fix this code to not output required for e-mail
5236 # $ret = array( 'required' );
5239 # We can't actually do this right now, because Opera 9.6 will print out
5240 # the entered password visibly in its error message! When other
5241 # browsers add support for this attribute, or Opera fixes its support,
5242 # we can add support with a version check to avoid doing this on Opera
5243 # versions where it will be a problem. Reported to Opera as
5244 # DSK-262266, but they don't have a public bug tracker for us to follow.
5246 if ( $wgMinimalPasswordLength > 1 ) {
5247 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
5248 $ret['title'] = wfMessage( 'passwordtooshort' )
5249 ->numParams( $wgMinimalPasswordLength )->text();
5257 * Return the list of user fields that should be selected to create
5258 * a new user object.
5261 public static function selectFields() {
5269 'user_email_authenticated',
5271 'user_email_token_expires',
5272 'user_registration',
5278 * Factory function for fatal permission-denied errors
5281 * @param string $permission User right required
5284 static function newFatalPermissionDeniedStatus( $permission ) {
5287 $groups = array_map(
5288 array( 'User', 'makeGroupLinkWiki' ),
5289 User
::getGroupsWithPermission( $permission )
5293 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5295 return Status
::newFatal( 'badaccess-group0' );
5300 * Get a new instance of this user that was loaded from the master via a locking read
5302 * Use this instead of the main context User when updating that user. This avoids races
5303 * where that user was loaded from a slave or even the master but without proper locks.
5305 * @return User|null Returns null if the user was not found in the DB
5308 public function getInstanceForUpdate() {
5309 if ( !$this->getId() ) {
5310 return null; // anon
5313 $user = self
::newFromId( $this->getId() );
5314 if ( !$user->loadFromId( self
::READ_EXCLUSIVE
) ) {
5322 * Checks if two user objects point to the same user.
5328 public function equals( User
$user ) {
5329 return $this->getName() === $user->getName();